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
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct StdlibPublicFunction {
21    pub name: String,
22    pub signature: String,
23    pub required_params: usize,
24    pub total_params: usize,
25    pub variadic: bool,
26    pub doc: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct StdlibEntrypointModule {
31    pub import_path: String,
32    pub category: String,
33}
34
35pub const STDLIB_SOURCES: &[StdlibSource] = &[
36    StdlibSource {
37        module: "text",
38        source: include_str!("stdlib/stdlib_text.harn"),
39    },
40    StdlibSource {
41        module: "collections",
42        source: include_str!("stdlib/stdlib_collections.harn"),
43    },
44    StdlibSource {
45        module: "math",
46        source: include_str!("stdlib/stdlib_math.harn"),
47    },
48    StdlibSource {
49        module: "path",
50        source: include_str!("stdlib/stdlib_path.harn"),
51    },
52    StdlibSource {
53        module: "json",
54        source: include_str!("stdlib/stdlib_json.harn"),
55    },
56    StdlibSource {
57        module: "cache",
58        source: include_str!("stdlib/stdlib_cache.harn"),
59    },
60    StdlibSource {
61        module: "tools",
62        source: include_str!("stdlib/stdlib_tools.harn"),
63    },
64    StdlibSource {
65        module: "graphql",
66        source: include_str!("stdlib/stdlib_graphql.harn"),
67    },
68    StdlibSource {
69        module: "schema",
70        source: include_str!("stdlib/stdlib_schema.harn"),
71    },
72    StdlibSource {
73        module: "testing",
74        source: include_str!("stdlib/stdlib_testing.harn"),
75    },
76    StdlibSource {
77        module: "files",
78        source: include_str!("stdlib/stdlib_files.harn"),
79    },
80    StdlibSource {
81        module: "vision",
82        source: include_str!("stdlib/stdlib_vision.harn"),
83    },
84    StdlibSource {
85        module: "context",
86        source: include_str!("stdlib/stdlib_context.harn"),
87    },
88    StdlibSource {
89        module: "runtime",
90        source: include_str!("stdlib/stdlib_runtime.harn"),
91    },
92    StdlibSource {
93        module: "command",
94        source: include_str!("stdlib/stdlib_command.harn"),
95    },
96    StdlibSource {
97        module: "review",
98        source: include_str!("stdlib/stdlib_review.harn"),
99    },
100    StdlibSource {
101        module: "experiments",
102        source: include_str!("stdlib/stdlib_experiments.harn"),
103    },
104    StdlibSource {
105        module: "project",
106        source: include_str!("stdlib/stdlib_project.harn"),
107    },
108    StdlibSource {
109        module: "prompt_library",
110        source: include_str!("stdlib/stdlib_prompt_library.harn"),
111    },
112    StdlibSource {
113        module: "async",
114        source: include_str!("stdlib/stdlib_async.harn"),
115    },
116    StdlibSource {
117        module: "agents",
118        source: include_str!("stdlib/stdlib_agents.harn"),
119    },
120    StdlibSource {
121        module: "agent/prompts",
122        source: include_str!("stdlib/agent/prompts.harn"),
123    },
124    StdlibSource {
125        module: "llm/media",
126        source: include_str!("stdlib/llm/media.harn"),
127    },
128    StdlibSource {
129        module: "llm/catalog",
130        source: include_str!("stdlib/llm/catalog.harn"),
131    },
132    StdlibSource {
133        module: "llm/safe",
134        source: include_str!("stdlib/llm/safe.harn"),
135    },
136    StdlibSource {
137        module: "llm/budget",
138        source: include_str!("stdlib/llm/budget.harn"),
139    },
140    StdlibSource {
141        module: "llm/prompts",
142        source: include_str!("stdlib/llm/prompts.harn"),
143    },
144    StdlibSource {
145        module: "llm/defaults",
146        source: include_str!("stdlib/llm/defaults.harn"),
147    },
148    StdlibSource {
149        module: "llm/handlers",
150        source: include_str!("stdlib/llm/handlers.harn"),
151    },
152    StdlibSource {
153        module: "llm/tool_middleware",
154        source: include_str!("stdlib/llm/tool_middleware.harn"),
155    },
156    StdlibSource {
157        module: "llm/refine",
158        source: include_str!("stdlib/llm/refine.harn"),
159    },
160    StdlibSource {
161        module: "llm/ensemble",
162        source: include_str!("stdlib/llm/ensemble.harn"),
163    },
164    StdlibSource {
165        module: "llm/rerank",
166        source: include_str!("stdlib/llm/rerank.harn"),
167    },
168    StdlibSource {
169        module: "agent/options",
170        source: include_str!("stdlib/agent/options.harn"),
171    },
172    StdlibSource {
173        module: "llm/judge",
174        source: include_str!("stdlib/llm/judge.harn"),
175    },
176    StdlibSource {
177        module: "llm/optimize",
178        source: include_str!("stdlib/llm/optimize.harn"),
179    },
180    StdlibSource {
181        module: "agent/events",
182        source: include_str!("stdlib/agent/events.harn"),
183    },
184    StdlibSource {
185        module: "agent/primitives",
186        source: include_str!("stdlib/agent/primitives.harn"),
187    },
188    StdlibSource {
189        module: "agent/loop",
190        source: include_str!("stdlib/agent/loop.harn"),
191    },
192    StdlibSource {
193        module: "agent/tool_search",
194        source: include_str!("stdlib/agent/tool_search.harn"),
195    },
196    StdlibSource {
197        module: "agent/turn",
198        source: include_str!("stdlib/agent/turn.harn"),
199    },
200    StdlibSource {
201        module: "agent/workers",
202        source: include_str!("stdlib/agent/workers.harn"),
203    },
204    StdlibSource {
205        module: "agent/state",
206        source: include_str!("stdlib/agent/state.harn"),
207    },
208    StdlibSource {
209        module: "agent/skills",
210        source: include_str!("stdlib/agent/skills.harn"),
211    },
212    StdlibSource {
213        module: "agent/autocompact",
214        source: include_str!("stdlib/agent/autocompact.harn"),
215    },
216    StdlibSource {
217        module: "agent/mcp",
218        source: include_str!("stdlib/agent/mcp.harn"),
219    },
220    StdlibSource {
221        module: "agent/host_tools",
222        source: include_str!("stdlib/agent/host_tools.harn"),
223    },
224    StdlibSource {
225        module: "agent/budget",
226        source: include_str!("stdlib/agent/budget.harn"),
227    },
228    StdlibSource {
229        module: "agent/daemon",
230        source: include_str!("stdlib/agent/daemon.harn"),
231    },
232    StdlibSource {
233        module: "agent/preflight",
234        source: include_str!("stdlib/agent/preflight.harn"),
235    },
236    StdlibSource {
237        module: "agent/postturn",
238        source: include_str!("stdlib/agent/postturn.harn"),
239    },
240    StdlibSource {
241        module: "agent/judge",
242        source: include_str!("stdlib/agent/judge.harn"),
243    },
244    StdlibSource {
245        module: "agent/presets",
246        source: include_str!("stdlib/agent/presets.harn"),
247    },
248    StdlibSource {
249        module: "agent_state",
250        source: include_str!("stdlib/stdlib_agent_state.harn"),
251    },
252    StdlibSource {
253        module: "memory",
254        source: include_str!("stdlib/stdlib_memory.harn"),
255    },
256    StdlibSource {
257        module: "postgres",
258        source: include_str!("stdlib/stdlib_postgres.harn"),
259    },
260    StdlibSource {
261        module: "checkpoint",
262        source: include_str!("stdlib/stdlib_checkpoint.harn"),
263    },
264    StdlibSource {
265        module: "host",
266        source: include_str!("stdlib/stdlib_host.harn"),
267    },
268    StdlibSource {
269        module: "git",
270        source: include_str!("stdlib/stdlib_git.harn"),
271    },
272    StdlibSource {
273        module: "hitl",
274        source: include_str!("stdlib/stdlib_hitl.harn"),
275    },
276    StdlibSource {
277        module: "trust",
278        source: include_str!("stdlib/stdlib_trust.harn"),
279    },
280    StdlibSource {
281        module: "corrections",
282        source: include_str!("stdlib/stdlib_corrections.harn"),
283    },
284    StdlibSource {
285        module: "plan",
286        source: include_str!("stdlib/stdlib_plan.harn"),
287    },
288    StdlibSource {
289        module: "waitpoints",
290        source: include_str!("stdlib/stdlib_waitpoints.harn"),
291    },
292    StdlibSource {
293        module: "waitpoint",
294        source: include_str!("stdlib/stdlib_waitpoint.harn"),
295    },
296    StdlibSource {
297        module: "monitors",
298        source: include_str!("stdlib/stdlib_monitors.harn"),
299    },
300    StdlibSource {
301        module: "worktree",
302        source: include_str!("stdlib/stdlib_worktree.harn"),
303    },
304    StdlibSource {
305        module: "acp",
306        source: include_str!("stdlib/stdlib_acp.harn"),
307    },
308    StdlibSource {
309        module: "triggers",
310        source: include_str!("stdlib/stdlib_triggers.harn"),
311    },
312    StdlibSource {
313        module: "handoffs",
314        source: include_str!("stdlib/stdlib_handoffs.harn"),
315    },
316    StdlibSource {
317        module: "personas/prelude",
318        source: include_str!("stdlib/stdlib_personas_prelude.harn"),
319    },
320    StdlibSource {
321        module: "connectors/shared",
322        source: include_str!("stdlib/stdlib_connectors_shared.harn"),
323    },
324    StdlibSource {
325        module: "connectors/github",
326        source: include_str!("stdlib/stdlib_connectors_github.harn"),
327    },
328    StdlibSource {
329        module: "connectors/linear",
330        source: include_str!("stdlib/stdlib_connectors_linear.harn"),
331    },
332    StdlibSource {
333        module: "connectors/notion",
334        source: include_str!("stdlib/stdlib_connectors_notion.harn"),
335    },
336    StdlibSource {
337        module: "connectors/slack",
338        source: include_str!("stdlib/stdlib_connectors_slack.harn"),
339    },
340    StdlibSource {
341        module: "workflow/prompts",
342        source: include_str!("stdlib/workflow/prompts.harn"),
343    },
344    StdlibSource {
345        module: "workflow/context",
346        source: include_str!("stdlib/workflow/context.harn"),
347    },
348    StdlibSource {
349        module: "workflow/options",
350        source: include_str!("stdlib/workflow/options.harn"),
351    },
352    StdlibSource {
353        module: "workflow/checkpoints",
354        source: include_str!("stdlib/workflow/checkpoints.harn"),
355    },
356    StdlibSource {
357        module: "workflow/stage",
358        source: include_str!("stdlib/workflow/stage.harn"),
359    },
360    StdlibSource {
361        module: "workflow/map",
362        source: include_str!("stdlib/workflow/map.harn"),
363    },
364    StdlibSource {
365        module: "workflow/schedule",
366        source: include_str!("stdlib/workflow/schedule.harn"),
367    },
368    StdlibSource {
369        module: "workflow/execute",
370        source: include_str!("stdlib/workflow/execute.harn"),
371    },
372];
373
374pub const STDLIB_PROMPT_ASSETS: &[StdlibPromptAsset] = &[
375    StdlibPromptAsset {
376        path: "agent/prompts/tool_contract_text.harn.prompt",
377        source: include_str!("stdlib/agent/prompts/tool_contract_text.harn.prompt"),
378    },
379    StdlibPromptAsset {
380        path: "agent/prompts/tool_contract_native.harn.prompt",
381        source: include_str!("stdlib/agent/prompts/tool_contract_native.harn.prompt"),
382    },
383    StdlibPromptAsset {
384        path: "agent/prompts/tool_contract_text_response_protocol.harn.prompt",
385        source: include_str!(
386            "stdlib/agent/prompts/tool_contract_text_response_protocol.harn.prompt"
387        ),
388    },
389    StdlibPromptAsset {
390        path: "agent/prompts/tool_contract_action_native.harn.prompt",
391        source: include_str!("stdlib/agent/prompts/tool_contract_action_native.harn.prompt"),
392    },
393    StdlibPromptAsset {
394        path: "agent/prompts/tool_contract_action_text.harn.prompt",
395        source: include_str!("stdlib/agent/prompts/tool_contract_action_text.harn.prompt"),
396    },
397    StdlibPromptAsset {
398        path: "agent/prompts/tool_contract_task_ledger.harn.prompt",
399        source: include_str!("stdlib/agent/prompts/tool_contract_task_ledger.harn.prompt"),
400    },
401    StdlibPromptAsset {
402        path: "agent/prompts/tool_contract_deferred_tools.harn.prompt",
403        source: include_str!("stdlib/agent/prompts/tool_contract_deferred_tools.harn.prompt"),
404    },
405    StdlibPromptAsset {
406        path: "agent/prompts/deferred_tool_listing.harn.prompt",
407        source: include_str!("stdlib/agent/prompts/deferred_tool_listing.harn.prompt"),
408    },
409    StdlibPromptAsset {
410        path: "agent/prompts/action_turn_nudge.harn.prompt",
411        source: include_str!("stdlib/agent/prompts/action_turn_nudge.harn.prompt"),
412    },
413    StdlibPromptAsset {
414        path: "agent/prompts/agent_turn_preamble.harn.prompt",
415        source: include_str!("stdlib/agent/prompts/agent_turn_preamble.harn.prompt"),
416    },
417    StdlibPromptAsset {
418        path: "agent/prompts/default_nudge.harn.prompt",
419        source: include_str!("stdlib/agent/prompts/default_nudge.harn.prompt"),
420    },
421    StdlibPromptAsset {
422        path: "agent/prompts/loop_until_done_system.harn.prompt",
423        source: include_str!("stdlib/agent/prompts/loop_until_done_system.harn.prompt"),
424    },
425    StdlibPromptAsset {
426        path: "agent/prompts/completion_judge_default.harn.prompt",
427        source: include_str!("stdlib/agent/prompts/completion_judge_default.harn.prompt"),
428    },
429    StdlibPromptAsset {
430        path: "agent/prompts/completion_judge_feedback_fallback.harn.prompt",
431        source: include_str!("stdlib/agent/prompts/completion_judge_feedback_fallback.harn.prompt"),
432    },
433    StdlibPromptAsset {
434        path: "agent/prompts/completion_judge_user.harn.prompt",
435        source: include_str!("stdlib/agent/prompts/completion_judge_user.harn.prompt"),
436    },
437    StdlibPromptAsset {
438        path: "agent/prompts/parse_guidance.harn.prompt",
439        source: include_str!("stdlib/agent/prompts/parse_guidance.harn.prompt"),
440    },
441    StdlibPromptAsset {
442        path: "agent/prompts/protocol_violation_feedback.harn.prompt",
443        source: include_str!("stdlib/agent/prompts/protocol_violation_feedback.harn.prompt"),
444    },
445    StdlibPromptAsset {
446        path: "agent/prompts/native_tool_contract_feedback.harn.prompt",
447        source: include_str!("stdlib/agent/prompts/native_tool_contract_feedback.harn.prompt"),
448    },
449    StdlibPromptAsset {
450        path: "agent/prompts/verification_gate_feedback.harn.prompt",
451        source: include_str!("stdlib/agent/prompts/verification_gate_feedback.harn.prompt"),
452    },
453    StdlibPromptAsset {
454        path: "agent/prompts/action_required_feedback.harn.prompt",
455        source: include_str!("stdlib/agent/prompts/action_required_feedback.harn.prompt"),
456    },
457    StdlibPromptAsset {
458        path: "agent/prompts/daemon_watch_feedback.harn.prompt",
459        source: include_str!("stdlib/agent/prompts/daemon_watch_feedback.harn.prompt"),
460    },
461    StdlibPromptAsset {
462        path: "agent/prompts/daemon_timer_feedback.harn.prompt",
463        source: include_str!("stdlib/agent/prompts/daemon_timer_feedback.harn.prompt"),
464    },
465    StdlibPromptAsset {
466        path: "llm/prompts/completion_fallback_system.harn.prompt",
467        source: include_str!("stdlib/llm/prompts/completion_fallback_system.harn.prompt"),
468    },
469    StdlibPromptAsset {
470        path: "llm/prompts/completion_fallback_user.harn.prompt",
471        source: include_str!("stdlib/llm/prompts/completion_fallback_user.harn.prompt"),
472    },
473    StdlibPromptAsset {
474        path: "llm/prompts/transcript_summarize_user.harn.prompt",
475        source: include_str!("stdlib/llm/prompts/transcript_summarize_user.harn.prompt"),
476    },
477    StdlibPromptAsset {
478        path: "llm/prompts/structural_chain_of_draft.harn.prompt",
479        source: include_str!("stdlib/llm/prompts/structural_chain_of_draft.harn.prompt"),
480    },
481    StdlibPromptAsset {
482        path: "llm/prompts/schema_recover_repair.harn.prompt",
483        source: include_str!("stdlib/llm/prompts/schema_recover_repair.harn.prompt"),
484    },
485    StdlibPromptAsset {
486        path: "llm/prompts/structured_envelope_schema_contract.harn.prompt",
487        source: include_str!("stdlib/llm/prompts/structured_envelope_schema_contract.harn.prompt"),
488    },
489    StdlibPromptAsset {
490        path: "llm/prompts/structured_envelope_repair.harn.prompt",
491        source: include_str!("stdlib/llm/prompts/structured_envelope_repair.harn.prompt"),
492    },
493    StdlibPromptAsset {
494        path: "llm/prompts/pairwise_rerank_user.harn.prompt",
495        source: include_str!("stdlib/llm/prompts/pairwise_rerank_user.harn.prompt"),
496    },
497    StdlibPromptAsset {
498        path: "workflow/prompts/stage.harn.prompt",
499        source: include_str!("stdlib/workflow/prompts/stage.harn.prompt"),
500    },
501    StdlibPromptAsset {
502        path: "workflow/prompts/verification_context_intro.harn.prompt",
503        source: include_str!("stdlib/workflow/prompts/verification_context_intro.harn.prompt"),
504    },
505    StdlibPromptAsset {
506        path: "orchestration/prompts/compaction_summary.harn.prompt",
507        source: include_str!("stdlib/orchestration/prompts/compaction_summary.harn.prompt"),
508    },
509];
510
511pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
512    STDLIB_SOURCES
513        .iter()
514        .find_map(|entry| (entry.module == module).then_some(entry.source))
515}
516
517pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
518    let path = path.strip_prefix("std/").unwrap_or(path);
519    STDLIB_PROMPT_ASSETS
520        .iter()
521        .find_map(|entry| (entry.path == path).then_some(entry.source))
522}
523
524pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
525    let Some(source) = get_stdlib_source(module) else {
526        return Vec::new();
527    };
528    public_functions_from_source(source)
529}
530
531pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
532    STDLIB_SOURCES
533        .iter()
534        .filter_map(|entry| {
535            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
536                import_path: format!("std/{}", entry.module),
537                category,
538            })
539        })
540        .collect()
541}
542
543fn entrypoint_category_from_source(source: &str) -> Option<String> {
544    for line in source.lines() {
545        let line = line.trim();
546        if line.is_empty() {
547            continue;
548        }
549        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
550            let category = category.trim();
551            return (!category.is_empty()).then(|| category.to_string());
552        }
553        if !line.starts_with("//") {
554            return None;
555        }
556    }
557    None
558}
559
560fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
561    let mut out = Vec::new();
562    let mut doc: Option<String> = None;
563    let lines = source.lines().collect::<Vec<_>>();
564    let mut index = 0usize;
565    while index < lines.len() {
566        let line = lines[index].trim();
567        if line.starts_with("/**") {
568            let (parsed, next) = parse_harndoc(&lines, index);
569            doc = parsed;
570            index = next;
571            continue;
572        }
573        if line.starts_with("pub fn ") {
574            let (signature_line, next) = collect_public_function_signature(&lines, index);
575            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
576                out.push(function);
577                index = next;
578                continue;
579            }
580        }
581        if let Some(function) = parse_public_function_line(line, doc.take()) {
582            out.push(function);
583        } else if !line.is_empty() && !line.starts_with("//") {
584            doc = None;
585        }
586        index += 1;
587    }
588    out
589}
590
591fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
592    let mut parts = Vec::new();
593    let mut index = start;
594    while index < lines.len() {
595        parts.push(lines[index].trim().to_string());
596        let candidate = parts.join(" ");
597        if public_function_signature_complete(&candidate) {
598            return (candidate, index + 1);
599        }
600        index += 1;
601    }
602    (parts.join(" "), index)
603}
604
605fn public_function_signature_complete(line: &str) -> bool {
606    let Some(rest) = line.strip_prefix("pub fn ") else {
607        return false;
608    };
609    let Some(name_end) = rest.find('(') else {
610        return false;
611    };
612    matching_paren_len(&rest[name_end + 1..]).is_some()
613}
614
615fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
616    let mut parts = Vec::new();
617    let mut index = start;
618    while index < lines.len() {
619        let mut line = lines[index].trim();
620        if index == start {
621            line = line.trim_start_matches("/**").trim();
622        }
623        let done = line.ends_with("*/");
624        line = line.trim_end_matches("*/").trim();
625        line = line.trim_start_matches('*').trim();
626        if !line.is_empty() {
627            parts.push(line.to_string());
628        }
629        index += 1;
630        if done {
631            break;
632        }
633    }
634    let text = parts.join("\n").trim().to_string();
635    ((!text.is_empty()).then_some(text), index)
636}
637
638fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
639    let rest = line.strip_prefix("pub fn ")?.trim();
640    let name_end = rest.find('(')?;
641    let name = rest[..name_end].trim();
642    if name.is_empty() {
643        return None;
644    }
645    let params_start = name_end + 1;
646    let params_len = matching_paren_len(&rest[params_start..])?;
647    let params = &rest[params_start..params_start + params_len];
648    let after = rest[params_start + params_len + 1..].trim();
649    let return_type = after
650        .strip_prefix("->")
651        .and_then(|tail| tail.split('{').next())
652        .map(str::trim)
653        .filter(|value| !value.is_empty());
654    let signature = match return_type {
655        Some(ret) => format!("{name}({params}) -> {ret}"),
656        None => format!("{name}({params})"),
657    };
658    let param_parts = split_top_level_params(params);
659    let total_params = param_parts
660        .iter()
661        .filter(|param| !param.trim().is_empty())
662        .count();
663    let variadic = param_parts
664        .iter()
665        .any(|param| param.trim_start().starts_with("..."));
666    let required_params = param_parts
667        .iter()
668        .filter(|param| {
669            let param = param.trim();
670            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
671        })
672        .count();
673    Some(StdlibPublicFunction {
674        name: name.to_string(),
675        signature,
676        required_params,
677        total_params,
678        variadic,
679        doc,
680    })
681}
682
683fn matching_paren_len(input: &str) -> Option<usize> {
684    let mut depth = 1usize;
685    for (offset, ch) in input.char_indices() {
686        match ch {
687            '(' | '[' | '{' => depth += 1,
688            ')' => {
689                depth = depth.saturating_sub(1);
690                if depth == 0 {
691                    return Some(offset);
692                }
693            }
694            ']' | '}' => depth = depth.saturating_sub(1),
695            _ => {}
696        }
697    }
698    None
699}
700
701fn split_top_level_params(params: &str) -> Vec<&str> {
702    let mut out = Vec::new();
703    let mut depth = 0isize;
704    let mut start = 0usize;
705    for (offset, ch) in params.char_indices() {
706        match ch {
707            '(' | '[' | '{' => depth += 1,
708            ')' | ']' | '}' => depth -= 1,
709            ',' if depth == 0 => {
710                out.push(&params[start..offset]);
711                start = offset + 1;
712            }
713            _ => {}
714        }
715    }
716    out.push(&params[start..]);
717    out
718}
719
720#[cfg(test)]
721mod tests {
722    use std::collections::BTreeSet;
723
724    use super::{
725        entrypoint_modules, get_stdlib_prompt_asset, get_stdlib_source,
726        public_functions_for_module, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
727    };
728
729    #[test]
730    fn stdlib_sources_are_non_empty() {
731        for entry in STDLIB_SOURCES {
732            assert!(
733                !entry.source.trim().is_empty(),
734                "{} should have non-empty source",
735                entry.module
736            );
737        }
738    }
739
740    #[test]
741    fn stdlib_source_names_are_unique() {
742        let mut names = BTreeSet::new();
743        for entry in STDLIB_SOURCES {
744            assert!(names.insert(entry.module), "duplicate {}", entry.module);
745        }
746    }
747
748    #[test]
749    fn stdlib_prompt_assets_are_non_empty() {
750        for entry in STDLIB_PROMPT_ASSETS {
751            assert!(
752                !entry.source.trim().is_empty(),
753                "{} should have non-empty prompt asset source",
754                entry.path
755            );
756        }
757    }
758
759    #[test]
760    fn stdlib_prompt_asset_paths_are_unique() {
761        let mut paths = BTreeSet::new();
762        for entry in STDLIB_PROMPT_ASSETS {
763            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
764        }
765    }
766
767    #[test]
768    fn key_stdlib_modules_resolve() {
769        for module in [
770            "context",
771            "command",
772            "waitpoint",
773            "llm/handlers",
774            "llm/tool_middleware",
775            "llm/ensemble",
776            "llm/rerank",
777            "personas/prelude",
778            "agent/host_tools",
779            "llm/optimize",
780            "llm/judge",
781            "llm/refine",
782            "connectors/shared",
783            "connectors/github",
784            "connectors/linear",
785            "connectors/notion",
786            "connectors/slack",
787        ] {
788            assert!(
789                get_stdlib_source(module).is_some(),
790                "std/{module} should resolve"
791            );
792        }
793    }
794
795    #[test]
796    fn key_stdlib_prompt_assets_resolve() {
797        for path in [
798            "std/agent/prompts/tool_contract_text.harn.prompt",
799            "std/agent/prompts/action_turn_nudge.harn.prompt",
800            "std/agent/prompts/completion_judge_default.harn.prompt",
801            "std/workflow/prompts/stage.harn.prompt",
802            "std/orchestration/prompts/compaction_summary.harn.prompt",
803        ] {
804            assert!(
805                get_stdlib_prompt_asset(path).is_some(),
806                "{path} should resolve"
807            );
808        }
809    }
810
811    #[test]
812    fn public_function_catalog_derives_signatures_from_harn_source() {
813        let exports = public_functions_for_module("workflow/execute");
814        assert_eq!(exports.len(), 1);
815        assert_eq!(exports[0].name, "workflow_execute");
816        assert_eq!(
817            exports[0].signature,
818            "workflow_execute(task, graph, artifacts = nil, options = nil)"
819        );
820        assert_eq!(exports[0].required_params, 2);
821        assert_eq!(exports[0].total_params, 4);
822    }
823
824    #[test]
825    fn command_stdlib_module_exports_step_helpers() {
826        let exports = public_functions_for_module("command")
827            .into_iter()
828            .map(|function| function.name)
829            .collect::<BTreeSet<_>>();
830        for name in [
831            "command_run",
832            "command_output_tail",
833            "command_step",
834            "command_steps_append",
835            "command_last_failed_step",
836            "command_step_ref",
837        ] {
838            assert!(exports.contains(name), "std/command should export {name}");
839        }
840    }
841
842    #[test]
843    fn async_stdlib_exports_predicate_backoff_name_only() {
844        let exports = public_functions_for_module("async")
845            .into_iter()
846            .map(|function| function.name)
847            .collect::<BTreeSet<_>>();
848        assert!(
849            exports.contains("retry_predicate_with_backoff"),
850            "std/async should export retry_predicate_with_backoff"
851        );
852        assert!(
853            !exports.contains("retry_with_backoff"),
854            "std/async should not retain the old retry_with_backoff export"
855        );
856    }
857
858    #[test]
859    fn git_stdlib_module_exports_local_wrappers() {
860        let exports = public_functions_for_module("git")
861            .into_iter()
862            .map(|function| function.name)
863            .collect::<BTreeSet<_>>();
864        for name in [
865            "git_run",
866            "git_status",
867            "git_current_branch",
868            "git_log",
869            "git_switch",
870            "git_pull_ff_only",
871            "git_find_tool",
872            "git_run_tool",
873            "git_tools",
874            "git_toolbox_tools",
875        ] {
876            assert!(exports.contains(name), "std/git should export {name}");
877        }
878    }
879
880    #[test]
881    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
882        let modules = entrypoint_modules();
883        let entries = modules
884            .iter()
885            .map(|module| (module.import_path.as_str(), module.category.as_str()))
886            .collect::<BTreeSet<_>>();
887        for entry in [
888            ("std/agent/loop", "agent.stdlib"),
889            ("std/agent/turn", "agent.stdlib"),
890            ("std/agent/primitives", "agent.stdlib"),
891            ("std/workflow/execute", "workflow.stdlib"),
892        ] {
893            assert!(entries.contains(&entry), "{entry:?} should be declared");
894        }
895    }
896}