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