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