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