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