harn-lsp 0.5.55

Language Server Protocol implementation for Harn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
/// Known builtin names with their signatures for completion.
/// Each entry is (name, detail) where detail shows the parameter signature.
pub(crate) const BUILTINS: &[(&str, &str)] = &[
    // I/O
    ("println", "println(msg) -> nil"),
    ("print", "print(msg) -> nil"),
    ("log", "log(msg) -> nil"),
    // Type conversion
    ("type_of", "type_of(value) -> string"),
    ("to_string", "to_string(value) -> string"),
    ("to_int", "to_int(value) -> int"),
    ("to_float", "to_float(value) -> float"),
    // JSON
    ("json_parse", "json_parse(str) -> value"),
    ("json_stringify", "json_stringify(value) -> string"),
    ("json_validate", "json_validate(data, schema) -> bool"),
    ("schema_check", "schema_check(data, schema) -> Result"),
    ("schema_parse", "schema_parse(data, schema) -> Result"),
    (
        "schema_to_json_schema",
        "schema_to_json_schema(schema) -> dict",
    ),
    ("schema_extend", "schema_extend(base, overrides) -> dict"),
    ("schema_partial", "schema_partial(schema) -> dict"),
    ("schema_pick", "schema_pick(schema, keys) -> dict"),
    ("schema_omit", "schema_omit(schema, keys) -> dict"),
    ("json_extract", "json_extract(text, key?) -> value"),
    // File system
    ("read_file", "read_file(path) -> string"),
    ("write_file", "write_file(path, content) -> nil"),
    ("file_exists", "file_exists(path) -> bool"),
    ("delete_file", "delete_file(path) -> nil"),
    ("list_dir", "list_dir(path) -> list"),
    ("mkdir", "mkdir(path) -> nil"),
    ("stat", "stat(path) -> dict"),
    ("copy_file", "copy_file(src, dst) -> nil"),
    ("append_file", "append_file(path, content) -> nil"),
    ("path_join", "path_join(parts...) -> string"),
    ("temp_dir", "temp_dir() -> string"),
    // Process
    ("exec", "exec(cmd, args...) -> dict"),
    ("exec_at", "exec_at(dir, cmd, args...) -> dict"),
    ("shell", "shell(cmd) -> dict"),
    ("shell_at", "shell_at(dir, cmd) -> dict"),
    // Environment
    ("env", "env(name) -> string"),
    ("timestamp", "timestamp() -> float"),
    ("exit", "exit(code) -> nil"),
    // Regex
    ("regex_match", "regex_match(pattern, text) -> list"),
    (
        "regex_replace",
        "regex_replace(pattern, replacement, text) -> string",
    ),
    // HTTP
    ("http_get", "http_get(url) -> dict"),
    ("http_post", "http_post(url, body, headers?) -> dict"),
    ("http_put", "http_put(url, body, headers?) -> dict"),
    ("http_patch", "http_patch(url, body, headers?) -> dict"),
    ("http_delete", "http_delete(url) -> dict"),
    (
        "http_request",
        "http_request(method, url, options?) -> dict",
    ),
    // Mock HTTP
    (
        "http_mock",
        "http_mock(method, url_pattern, response) -> nil",
    ),
    ("http_mock_clear", "http_mock_clear() -> nil"),
    ("http_mock_calls", "http_mock_calls() -> list"),
    (
        "host_mock",
        "host_mock(capability, op, response_or_config, params?) -> nil",
    ),
    ("host_mock_clear", "host_mock_clear() -> nil"),
    ("host_mock_calls", "host_mock_calls() -> list"),
    // LLM
    ("llm_call", "llm_call(prompt, system?, options?) -> dict"),
    (
        "llm_completion",
        "llm_completion(prefix, suffix?, system?, options?) -> dict",
    ),
    // LLM cost tracking
    (
        "llm_cost",
        "llm_cost(model, input_tokens, output_tokens) -> float",
    ),
    ("llm_session_cost", "llm_session_cost() -> dict"),
    ("llm_budget", "llm_budget(max_cost) -> nil"),
    ("llm_budget_remaining", "llm_budget_remaining() -> float"),
    (
        "llm_stream",
        "llm_stream(prompt, system?, options?) -> string",
    ),
    (
        "agent_loop",
        "agent_loop(prompt, system?, options?) -> dict",
    ),
    ("resume_agent", "resume_agent(id_or_snapshot_path) -> dict"),
    // MCP
    ("mcp_connect", "mcp_connect(command, args?) -> client"),
    ("mcp_list_tools", "mcp_list_tools(client) -> list"),
    ("mcp_call", "mcp_call(client, name, args?) -> value"),
    ("mcp_list_resources", "mcp_list_resources(client) -> list"),
    (
        "mcp_read_resource",
        "mcp_read_resource(client, uri) -> string",
    ),
    (
        "mcp_list_resource_templates",
        "mcp_list_resource_templates(client) -> list",
    ),
    ("mcp_list_prompts", "mcp_list_prompts(client) -> list"),
    (
        "mcp_get_prompt",
        "mcp_get_prompt(client, name, args?) -> dict",
    ),
    ("mcp_server_info", "mcp_server_info(client) -> dict"),
    ("mcp_disconnect", "mcp_disconnect(client) -> nil"),
    // MCP server
    ("mcp_tools", "mcp_tools(registry) -> nil"),
    ("mcp_serve", "mcp_serve(registry) -> nil"),
    (
        "mcp_resource",
        "mcp_resource({uri, name, text, ...}) -> nil",
    ),
    (
        "mcp_resource_template",
        "mcp_resource_template({uri_template, name, handler, ...}) -> nil",
    ),
    ("mcp_prompt", "mcp_prompt({name, handler, ...}) -> nil"),
    // Conversation management
    ("conversation", "conversation() -> list"),
    ("add_message", "add_message(conv, role, content) -> list"),
    ("add_user", "add_user(conv, content) -> list"),
    ("add_assistant", "add_assistant(conv, content) -> list"),
    ("add_system", "add_system(conv, content) -> list"),
    (
        "add_tool_result",
        "add_tool_result(conv, tool_use_id, content) -> list",
    ),
    // Concurrency
    ("sleep", "sleep(duration) -> nil"),
    ("channel", "channel(name?) -> channel"),
    ("send", "send(ch, value) -> nil"),
    ("receive", "receive(ch) -> value"),
    ("try_receive", "try_receive(ch) -> value"),
    ("close_channel", "close_channel(ch) -> nil"),
    ("select", "select(channels...) -> value"),
    ("atomic", "atomic(initial?) -> atomic"),
    ("atomic_get", "atomic_get(a) -> value"),
    ("atomic_set", "atomic_set(a, value) -> nil"),
    ("atomic_add", "atomic_add(a, delta) -> value"),
    ("atomic_cas", "atomic_cas(a, expected, new) -> bool"),
    // Graceful cancellation
    (
        "cancel_graceful",
        "cancel_graceful(handle, timeout?) -> Result",
    ),
    ("is_cancelled", "is_cancelled() -> bool"),
    // Assertions
    ("assert", "assert(condition, msg?) -> nil"),
    ("assert_eq", "assert_eq(a, b, msg?) -> nil"),
    ("assert_ne", "assert_ne(a, b, msg?) -> nil"),
    // Math
    ("abs", "abs(n) -> number"),
    ("min", "min(a, b) -> number"),
    ("max", "max(a, b) -> number"),
    ("floor", "floor(n) -> int"),
    ("ceil", "ceil(n) -> int"),
    ("round", "round(n) -> int"),
    ("sqrt", "sqrt(n) -> float"),
    ("pow", "pow(base, exp) -> number"),
    ("random", "random() -> float"),
    ("random_int", "random_int(min, max) -> int"),
    // Math: trig
    ("sin", "sin(n) -> float"),
    ("cos", "cos(n) -> float"),
    ("tan", "tan(n) -> float"),
    ("asin", "asin(n) -> float"),
    ("acos", "acos(n) -> float"),
    ("atan", "atan(n) -> float"),
    ("atan2", "atan2(y, x) -> float"),
    // Math: logarithms/exponentials
    ("log2", "log2(n) -> float"),
    ("log10", "log10(n) -> float"),
    ("ln", "ln(n) -> float"),
    ("exp", "exp(n) -> float"),
    // Math: constants/utilities
    ("pi", "pi: float"),
    ("e", "e: float"),
    ("sign", "sign(n) -> int"),
    ("is_nan", "is_nan(n) -> bool"),
    ("is_infinite", "is_infinite(n) -> bool"),
    // Sets
    ("set", "set(items?) -> set"),
    ("set_add", "set_add(s, value) -> set"),
    ("set_remove", "set_remove(s, value) -> set"),
    ("set_contains", "set_contains(s, value) -> bool"),
    ("set_union", "set_union(a, b) -> set"),
    ("set_intersect", "set_intersect(a, b) -> set"),
    ("set_difference", "set_difference(a, b) -> set"),
    ("to_list", "to_list(s) -> list"),
    // String
    ("format", "format(template, args...) -> string"),
    ("trim", "trim(str) -> string"),
    ("lowercase", "lowercase(str) -> string"),
    ("uppercase", "uppercase(str) -> string"),
    ("split", "split(str, sep) -> list"),
    // Date/time
    ("date_now", "date_now() -> string"),
    ("date_format", "date_format(ts, fmt?) -> string"),
    ("date_parse", "date_parse(str) -> int"),
    // Logging
    ("log_debug", "log_debug(msg) -> nil"),
    ("log_info", "log_info(msg) -> nil"),
    ("log_warn", "log_warn(msg) -> nil"),
    ("log_error", "log_error(msg) -> nil"),
    ("log_set_level", "log_set_level(level) -> nil"),
    // Tracing
    ("trace_start", "trace_start(name) -> span"),
    ("trace_end", "trace_end(span) -> nil"),
    ("trace_id", "trace_id() -> string"),
    ("enable_tracing", "enable_tracing(enabled?) -> nil"),
    ("trace_spans", "trace_spans() -> list"),
    ("trace_summary", "trace_summary() -> string"),
    // Tool registry
    ("tool_registry", "tool_registry() -> registry"),
    ("tool_list", "tool_list(registry) -> list"),
    ("tool_find", "tool_find(registry, name) -> dict"),
    ("tool_select", "tool_select(registry, names) -> registry"),
    ("tool_describe", "tool_describe(registry) -> string"),
    ("tool_remove", "tool_remove(registry, name) -> nil"),
    ("tool_count", "tool_count(registry) -> int"),
    ("tool_schema", "tool_schema(registry) -> dict"),
    ("tool_prompt", "tool_prompt(registry) -> string"),
    ("tool_parse_call", "tool_parse_call(registry, text) -> dict"),
    (
        "tool_format_result",
        "tool_format_result(name, result) -> string",
    ),
    // User interaction
    ("prompt_user", "prompt_user(msg) -> string"),
    // Host interop
    ("host_call", "host_call(name, args) -> value"),
    // LLM introspection
    ("llm_info", "llm_info() -> dict"),
    ("llm_usage", "llm_usage() -> dict"),
    // LLM provider config
    (
        "llm_infer_provider",
        "llm_infer_provider(model_id) -> string",
    ),
    ("llm_model_tier", "llm_model_tier(model_id) -> string"),
    ("llm_pick_model", "llm_pick_model(target, options?) -> dict"),
    ("llm_resolve_model", "llm_resolve_model(alias) -> dict"),
    ("transcript", "transcript(metadata?) -> dict"),
    ("transcript_reset", "transcript_reset(options?) -> dict"),
    (
        "transcript_archive",
        "transcript_archive(transcript) -> dict",
    ),
    (
        "transcript_abandon",
        "transcript_abandon(transcript) -> dict",
    ),
    ("transcript_resume", "transcript_resume(transcript) -> dict"),
    (
        "transcript_compact",
        "transcript_compact(transcript, options?) -> dict",
    ),
    (
        "transcript_summarize",
        "transcript_summarize(transcript, options?) -> dict",
    ),
    ("transcript_assets", "transcript_assets(transcript) -> list"),
    (
        "transcript_add_asset",
        "transcript_add_asset(transcript, asset) -> dict",
    ),
    (
        "transcript_auto_compact",
        "transcript_auto_compact(messages, options?) -> list",
    ),
    ("host_capabilities", "host_capabilities() -> dict"),
    ("host_has", "host_has(capability, op?) -> bool"),
    ("host_call", "host_call(name, args) -> value"),
    (
        "workflow_policy_report",
        "workflow_policy_report(graph, ceiling?) -> dict",
    ),
    (
        "artifact_workspace_file",
        "artifact_workspace_file(path, content, extra?) -> dict",
    ),
    (
        "artifact_workspace_snapshot",
        "artifact_workspace_snapshot(paths, summary?, extra?) -> dict",
    ),
    (
        "artifact_editor_selection",
        "artifact_editor_selection(path, text, extra?) -> dict",
    ),
    (
        "artifact_verification_result",
        "artifact_verification_result(title, text, extra?) -> dict",
    ),
    (
        "artifact_test_result",
        "artifact_test_result(title, text, extra?) -> dict",
    ),
    (
        "artifact_command_result",
        "artifact_command_result(command, output, extra?) -> dict",
    ),
    (
        "artifact_diff",
        "artifact_diff(path, before, after, extra?) -> dict",
    ),
    (
        "artifact_git_diff",
        "artifact_git_diff(diff_text, extra?) -> dict",
    ),
    (
        "artifact_diff_review",
        "artifact_diff_review(target, summary?, extra?) -> dict",
    ),
    (
        "artifact_review_decision",
        "artifact_review_decision(target, decision, extra?) -> dict",
    ),
    (
        "artifact_patch_proposal",
        "artifact_patch_proposal(target, patch, extra?) -> dict",
    ),
    (
        "artifact_verification_bundle",
        "artifact_verification_bundle(title, checks, extra?) -> dict",
    ),
    (
        "artifact_apply_intent",
        "artifact_apply_intent(target, intent, extra?) -> dict",
    ),
    ("load_run_tree", "load_run_tree(path) -> dict"),
    ("run_record_fixture", "run_record_fixture(run) -> dict"),
    ("run_record_eval", "run_record_eval(run, fixture?) -> dict"),
    (
        "run_record_eval_suite",
        "run_record_eval_suite(cases) -> dict",
    ),
    ("run_record_diff", "run_record_diff(left, right) -> dict"),
    (
        "eval_suite_manifest",
        "eval_suite_manifest(payload) -> dict",
    ),
    ("eval_suite_run", "eval_suite_run(manifest) -> dict"),
    ("eval_metric", "eval_metric(name, value, metadata?) -> nil"),
    ("eval_metrics", "eval_metrics() -> list"),
    ("llm_providers", "llm_providers() -> list"),
    ("llm_config", "llm_config(provider?) -> dict"),
    ("llm_healthcheck", "llm_healthcheck(provider?) -> dict"),
    // Timers
    ("timer_start", "timer_start(name?) -> dict"),
    ("timer_end", "timer_end(timer) -> int"),
    ("elapsed", "elapsed() -> int"),
    // Structured logging
    ("log_json", "log_json(key, value) -> nil"),
    // Metadata
    ("metadata_get", "metadata_get(dir, namespace?) -> dict"),
    (
        "metadata_resolve",
        "metadata_resolve(dir, namespace?) -> dict",
    ),
    ("metadata_entries", "metadata_entries(namespace?) -> list"),
    ("metadata_set", "metadata_set(dir, namespace, data) -> nil"),
    ("metadata_save", "metadata_save() -> nil"),
    ("metadata_stale", "metadata_stale(project) -> dict"),
    ("metadata_status", "metadata_status(namespace?) -> dict"),
    (
        "metadata_refresh_hashes",
        "metadata_refresh_hashes() -> nil",
    ),
    (
        "compute_content_hash",
        "compute_content_hash(dir) -> string",
    ),
    ("invalidate_facts", "invalidate_facts(dir) -> nil"),
    // Encoding
    ("url_encode", "url_encode(str) -> string"),
    ("url_decode", "url_decode(str) -> string"),
    ("base64_encode", "base64_encode(str) -> string"),
    ("base64_decode", "base64_decode(str) -> string"),
    ("sha256", "sha256(str) -> string"),
    ("md5", "md5(str) -> string"),
];

/// Known keywords for completion.
pub(crate) const KEYWORDS: &[&str] = &[
    "pipeline",
    "extends",
    "override",
    "let",
    "var",
    "if",
    "else",
    "for",
    "in",
    "match",
    "retry",
    "parallel",
    "parallel_map",
    "parallel_settle",
    "return",
    "import",
    "true",
    "false",
    "nil",
    "try",
    "catch",
    "throw",
    "fn",
    "spawn",
    "while",
    "break",
    "continue",
    "interface",
    "pub",
    "from",
    "struct",
    "enum",
    "type",
    "guard",
    "deadline",
    "yield",
    "mutex",
];

/// String methods offered after `.` on a string value.
pub(crate) const STRING_METHODS: &[&str] = &[
    "count",
    "empty",
    "trim",
    "split",
    "contains",
    "starts_with",
    "ends_with",
    "replace",
    "uppercase",
    "lowercase",
    "substring",
    "index_of",
    "chars",
    "repeat",
    "reverse",
    "pad_left",
    "pad_right",
];

/// List methods offered after `.` on a list value.
pub(crate) const LIST_METHODS: &[&str] = &[
    "count",
    "empty",
    "push",
    "pop",
    "map",
    "filter",
    "reduce",
    "find",
    "any",
    "all",
    "contains",
    "index_of",
    "join",
    "sort",
    "sort_by",
    "reverse",
    "flat_map",
    "flatten",
    "slice",
    "enumerate",
    "zip",
    "unique",
    "take",
    "skip",
    "sum",
    "min",
    "max",
];

/// Dict methods offered after `.` on a dict value.
pub(crate) const DICT_METHODS: &[&str] = &[
    "keys",
    "values",
    "entries",
    "count",
    "has",
    "merge",
    "map_values",
    "filter",
    "remove",
    "get",
];

/// Known type names used after `:` in type annotations.
pub(crate) const TYPE_NAMES: &[&str] = &[
    "int", "float", "string", "bool", "nil", "list", "dict", "any", "void", "channel", "atomic",
    "mutex", "closure",
];

// ---------------------------------------------------------------------------
// Hover documentation
// ---------------------------------------------------------------------------

pub(crate) fn builtin_doc(name: &str) -> Option<String> {
    let doc = match name {
        "log" => "**log(value)** — Print value to stdout with `[harn]` prefix",
        "print" => "**print(value)** — Print value to stdout (no newline)",
        "println" => "**println(value)** — Print value to stdout with newline",
        "type_of" => "**type_of(value)** → string — Returns the type name",
        "to_string" => "**to_string(value)** → string — Convert to string",
        "to_int" => "**to_int(value)** → int — Convert to integer",
        "to_float" => "**to_float(value)** → float — Convert to float",
        "json_parse" => "**json_parse(text)** → value — Parse JSON string into Harn value",
        "json_stringify" => "**json_stringify(value)** → string — Convert value to JSON string",
        "env" => "**env(name)** → string | nil — Get environment variable",
        "timestamp" => "**timestamp()** → float — Unix timestamp in seconds",
        "sleep" => "**sleep(ms)** → nil — Async sleep for milliseconds",
        "read_file" => "**read_file(path)** → string — Read file contents",
        "write_file" => "**write_file(path, content)** → nil — Write string to file",
        "exit" => "**exit(code)** — Terminate process with exit code",
        "regex_match" => "**regex_match(pattern, text)** → list | nil — Find all regex matches",
        "regex_replace" => {
            "**regex_replace(pattern, replacement, text)** → string — Replace regex matches"
        }
        "http_get" => "**http_get(url)** → string — HTTP GET request",
        "http_post" => "**http_post(url, body, headers?)** → string — HTTP POST request",
        "llm_call" => "**llm_call(prompt, system?, options?)** → dict — Call an LLM API\n\nReturns: `{text, model, input_tokens, output_tokens, transcript?}`",
        "llm_completion" => "**llm_completion(prefix, suffix?, system?, options?)** → dict — Text completion / fill-in-the-middle generation",
        "agent_loop" => "**agent_loop(prompt, system?, options?)** → dict — Agent loop with tool dispatch\n\nReturns: `{status, text, iterations, duration_ms, tools_used, transcript}`\n\nOptions: `{provider, model, persistent, max_iterations, max_nudges, nudge}`\n\nIn persistent mode, loop continues until `##DONE##` sentinel is output.",
        "await" => "**await(handle)** → value — Wait for spawned task to complete",
        "cancel" => "**cancel(handle)** → nil — Cancel a spawned task",
        "abs" => "**abs(value)** → int | float — Absolute value",
        "min" => "**min(a, b)** → int | float — Minimum of two values",
        "max" => "**max(a, b)** → int | float — Maximum of two values",
        "floor" => "**floor(value)** → int — Floor of a float",
        "ceil" => "**ceil(value)** → int — Ceiling of a float",
        "round" => "**round(value)** → int — Round a float to nearest integer",
        "sqrt" => "**sqrt(value)** → float — Square root",
        "pow" => "**pow(base, exp)** → int | float — Exponentiation",
        "random" => "**random()** → float — Random float in [0, 1)",
        "random_int" => "**random_int(min, max)** → int — Random integer in [min, max]",
        "sin" => "**sin(n)** → float — Sine (radians)",
        "cos" => "**cos(n)** → float — Cosine (radians)",
        "tan" => "**tan(n)** → float — Tangent (radians)",
        "asin" => "**asin(n)** → float — Inverse sine",
        "acos" => "**acos(n)** → float — Inverse cosine",
        "atan" => "**atan(n)** → float — Inverse tangent",
        "atan2" => "**atan2(y, x)** → float — Two-argument inverse tangent",
        "log2" => "**log2(n)** → float — Base-2 logarithm",
        "log10" => "**log10(n)** → float — Base-10 logarithm",
        "ln" => "**ln(n)** → float — Natural logarithm",
        "exp" => "**exp(n)** → float — e raised to the power n",
        "pi" => "**pi** → float — The constant pi (3.14159...)",
        "e" => "**e** → float — Euler's number (2.71828...)",
        "sign" => "**sign(n)** → int — Sign of a number: -1, 0, or 1",
        "is_nan" => "**is_nan(n)** → bool — Check if value is NaN",
        "is_infinite" => "**is_infinite(n)** → bool — Check if value is infinite",
        "set" => "**set(items?)** → set — Create a new set, optionally from a list",
        "set_add" => "**set_add(s, value)** → set — Add a value to a set",
        "set_remove" => "**set_remove(s, value)** → set — Remove a value from a set",
        "set_contains" => "**set_contains(s, value)** → bool — Check if set contains a value",
        "set_union" => "**set_union(a, b)** → set — Union of two sets",
        "set_intersect" => "**set_intersect(a, b)** → set — Intersection of two sets",
        "set_difference" => "**set_difference(a, b)** → set — Difference of two sets",
        "to_list" => "**to_list(s)** → list — Convert a set to a sorted list",
        "assert" => "**assert(condition, message?)** — Assert condition is truthy",
        "assert_eq" => "**assert_eq(actual, expected, message?)** — Assert two values are equal",
        "assert_ne" => "**assert_ne(actual, expected, message?)** — Assert two values are not equal",
        "file_exists" => "**file_exists(path)** → bool — Check if file or directory exists",
        "delete_file" => "**delete_file(path)** → nil — Delete a file or directory",
        "list_dir" => "**list_dir(path?)** → list — List directory entries (sorted)",
        "mkdir" => "**mkdir(path)** → nil — Create directory (and parents)",
        "path_join" => "**path_join(parts...)** → string — Join path segments",
        "copy_file" => "**copy_file(src, dst)** → nil — Copy a file",
        "append_file" => "**append_file(path, content)** → nil — Append to a file",
        "temp_dir" => "**temp_dir()** → string — System temp directory path",
        "stat" => "**stat(path)** → dict — File metadata: size, is_file, is_dir, readonly, modified",
        "exec" => "**exec(cmd, args...)** → dict — Run a command, returns {stdout, stderr, status, success}",
        "shell" => "**shell(cmd)** → dict — Run shell command, returns {stdout, stderr, status, success}",
        "date_now" => "**date_now()** → dict — Current UTC date: {year, month, day, hour, minute, second, weekday, timestamp}",
        "date_format" => "**date_format(timestamp, fmt?)** → string — Format timestamp (%Y, %m, %d, %H, %M, %S)",
        "date_parse" => "**date_parse(str)** → float — Parse date string to Unix timestamp",
        "format" => "**format(template, args...)** → string — String formatting with {} placeholders",
        "channel" => "**channel(name?, capacity?)** → channel — Create an async channel",
        "send" => "**send(channel, value)** → bool — Send a value on a channel",
        "receive" => "**receive(channel)** → value — Receive next value from channel (blocks)",
        "try_receive" => "**try_receive(channel)** → value | nil — Non-blocking receive",
        "close_channel" => "**close_channel(channel)** → nil — Close a channel",
        "atomic" => "**atomic(initial?)** → atomic — Create an atomic integer",
        "atomic_get" => "**atomic_get(a)** → int — Read atomic value",
        "atomic_set" => "**atomic_set(a, value)** → int — Set atomic value, returns old",
        "atomic_add" => "**atomic_add(a, n)** → int — Atomically add, returns previous value",
        "atomic_cas" => "**atomic_cas(a, expected, new)** → bool — Compare-and-swap",
        "select" => "**select(ch1, ch2, ...)** → dict — Wait for first channel with data: {index, value, channel}",
        "prompt_user" => "**prompt_user(message?)** → string — Read a line from stdin",
        "llm_info" => "**llm_info()** → dict — LLM configuration: {provider, model, api_key_set}",
        "llm_usage" => "**llm_usage()** → dict — Cumulative LLM usage: {input_tokens, output_tokens, total_duration_ms, call_count, total_calls}",
        "timer_start" => "**timer_start(name?)** → dict — Start a named timer, returns timer handle",
        "timer_end" => "**timer_end(timer)** → int — Stop timer, prints elapsed, returns milliseconds",
        "elapsed" => "**elapsed()** → int — Milliseconds since process start",
        "log_json" => "**log_json(key, value)** → nil — Emit structured JSON log line with timestamp",
        "metadata_get" => "**metadata_get(dir, namespace?)** → dict | nil — Read metadata with inheritance and flatten namespaces",
        "metadata_resolve" => "**metadata_resolve(dir, namespace?)** → dict | nil — Read resolved metadata while preserving namespace structure",
        "metadata_entries" => "**metadata_entries(namespace?)** → list — List local and resolved metadata for each stored directory",
        "metadata_set" => "**metadata_set(dir, namespace, data)** → nil — Write metadata for a directory/namespace",
        "metadata_save" => "**metadata_save()** → nil — Flush metadata to .harn/metadata/ files",
        "metadata_stale" => "**metadata_stale(project)** → dict — Check for stale metadata: {any_stale, tier1, tier2}",
        "metadata_status" => "**metadata_status(namespace?)** → dict — Summarize metadata directories, namespaces, missing hashes, and stale state",
        "transcript_assets" => "**transcript_assets(transcript)** → list — Return transcript asset descriptors used by multimodal messages",
        "transcript_add_asset" => "**transcript_add_asset(transcript, asset)** → dict — Register a durable asset reference and return the updated transcript",
        "metadata_refresh_hashes" => "**metadata_refresh_hashes()** → nil — Recompute content hashes",
        "compute_content_hash" => "**compute_content_hash(dir)** → string — Hash of directory contents for staleness detection",
        "invalidate_facts" => "**invalidate_facts(dir)** → nil — Mark cached facts as stale",
        "mcp_connect" => "**mcp_connect(command, args?)** → mcp_client — Spawn an MCP server and connect",
        "mcp_list_tools" => "**mcp_list_tools(client)** → list — List available tools from MCP server",
        "mcp_call" => "**mcp_call(client, name, arguments?)** → string | list — Call an MCP tool",
        "mcp_list_resources" => "**mcp_list_resources(client)** → list — List resources from MCP server",
        "mcp_list_resource_templates" => "**mcp_list_resource_templates(client)** → list — List resource templates from MCP server",
        "mcp_read_resource" => "**mcp_read_resource(client, uri)** → string | list — Read a resource by URI",
        "mcp_list_prompts" => "**mcp_list_prompts(client)** → list — List prompts from MCP server",
        "mcp_get_prompt" => "**mcp_get_prompt(client, name, arguments?)** → dict — Get a prompt with optional arguments",
        "mcp_server_info" => "**mcp_server_info(client)** → dict — Server info: `{name, connected}`",
        "mcp_disconnect" => "**mcp_disconnect(client)** → nil — Disconnect and kill MCP server process",
        // MCP server
        "mcp_tools" => "**mcp_tools(registry)** → nil — Register a tool registry for the MCP server (used with `harn mcp-serve`)",
        "mcp_serve" => "**mcp_serve(registry)** → nil — Alias for `mcp_tools` (deprecated)",
        "mcp_resource" => "**mcp_resource({uri, name, text, description?, mime_type?})** → nil — Register a static resource for the MCP server",
        "mcp_resource_template" => "**mcp_resource_template({uri_template, name, handler, description?, mime_type?})** → nil — Register a parameterized resource template (RFC 6570 URI template)",
        "mcp_prompt" => "**mcp_prompt({name, handler, description?, arguments?})** → nil — Register a prompt template for the MCP server",
        // Conversation management
        "conversation" => "**conversation()** → list — Create an empty conversation message list",
        "add_message" => "**add_message(conv, role, content)** → list — Add a message with given role to conversation",
        "add_user" => "**add_user(conv, content)** → list — Add a user message to conversation",
        "add_assistant" => "**add_assistant(conv, content)** → list — Add an assistant message to conversation",
        "add_system" => "**add_system(conv, content)** → list — Add a system message to conversation",
        "add_tool_result" => "**add_tool_result(conv, tool_use_id, content)** → list — Add a tool result to conversation",
        // LLM cost tracking
        "llm_cost" => "**llm_cost(model, input_tokens, output_tokens)** → float — Estimate USD cost from embedded pricing table",
        "llm_session_cost" => "**llm_session_cost()** → dict — Session totals: {total_cost, input_tokens, output_tokens, call_count}",
        "llm_budget" => "**llm_budget(max_cost)** → nil — Set session budget in USD",
        "llm_budget_remaining" => "**llm_budget_remaining()** → float — Remaining budget (nil if no budget set)",
        // LLM provider config
        "llm_infer_provider" => "**llm_infer_provider(model_id)** → string — Infer provider name from model ID",
        "llm_model_tier" => "**llm_model_tier(model_id)** → string — Get model tier (e.g. flagship, mid, small)",
        "llm_pick_model" => "**llm_pick_model(target, options?)** → dict — Resolve a model alias or tier to `{id, provider, tier}`",
        "llm_resolve_model" => "**llm_resolve_model(alias)** → dict — Resolve a model alias to full model info",
        "llm_providers" => "**llm_providers()** → list — List all configured LLM providers",
        "llm_config" => "**llm_config(provider?)** → dict — Get provider configuration",
        "llm_healthcheck" => "**llm_healthcheck(provider?)** → dict — Check provider health and connectivity",
        "transcript" => "**transcript(metadata?)** → dict — Create a new transcript",
        "transcript_compact" => "**transcript_compact(transcript, options?)** → dict — Compact a transcript locally",
        "transcript_summarize" => "**transcript_summarize(transcript, options?)** → dict — Summarize and compact a transcript with an LLM",
        "transcript_auto_compact" => "**transcript_auto_compact(messages, options?)** → list — Apply the agent-loop compaction pipeline to a message list",
        "schema_check" => "**schema_check(data, schema)** → Result — Validate data against an extended Harn schema without applying defaults",
        "schema_parse" => "**schema_parse(data, schema)** → Result — Validate data against an extended Harn schema and apply defaults",
        "schema_to_json_schema" => "**schema_to_json_schema(schema)** → dict — Convert an extended Harn schema into JSON Schema",
        "schema_extend" => "**schema_extend(base, overrides)** → dict — Shallow-merge two schema dicts",
        "schema_partial" => "**schema_partial(schema)** → dict — Make schema properties optional by removing `required` recursively",
        "schema_pick" => "**schema_pick(schema, keys)** → dict — Keep only selected top-level properties from a schema",
        "schema_omit" => "**schema_omit(schema, keys)** → dict — Remove selected top-level properties from a schema",
        "host_capabilities" => "**host_capabilities()** → dict — Typed host capability manifest",
        "host_has" => "**host_has(capability, op?)** → bool — Check host capability support",
        "host_call" => "**host_call(name, args)** → any — Invoke a host capability operation using capability.operation naming",
        "host_mock" => "**host_mock(capability, op, response_or_config, params?)** → nil — Register a typed host mock for tests. The third argument may be a direct result value or a config dict containing `result`, `params`, and/or `error`.",
        "host_mock_clear" => "**host_mock_clear()** → nil — Clear typed host mocks and recorded mock invocations",
        "host_mock_calls" => "**host_mock_calls()** → list — Return recorded typed host mock invocations",
        "workflow_policy_report" => "**workflow_policy_report(graph, ceiling?)** → dict — Show effective workflow and node policies against a ceiling",
        "artifact_workspace_file" => "**artifact_workspace_file(path, content, extra?)** → dict — Build a normalized workspace-file artifact with path provenance",
        "artifact_workspace_snapshot" => "**artifact_workspace_snapshot(paths, summary?, extra?)** → dict — Build a workspace snapshot artifact for host/editor context handoff",
        "artifact_editor_selection" => "**artifact_editor_selection(path, text, extra?)** → dict — Build an editor-selection artifact from host UI state",
        "artifact_verification_result" => "**artifact_verification_result(title, text, extra?)** → dict — Build a verification-result artifact",
        "artifact_test_result" => "**artifact_test_result(title, text, extra?)** → dict — Build a test-result artifact",
        "artifact_command_result" => "**artifact_command_result(command, output, extra?)** → dict — Build a command-result artifact with structured output",
        "artifact_diff" => "**artifact_diff(path, before, after, extra?)** → dict — Build a unified diff artifact from before/after text",
        "artifact_git_diff" => "**artifact_git_diff(diff_text, extra?)** → dict — Build a git-diff artifact from host or tool output",
        "artifact_diff_review" => "**artifact_diff_review(target, summary?, extra?)** → dict — Build a pending diff-review artifact linked to a diff or patch artifact",
        "artifact_review_decision" => "**artifact_review_decision(target, decision, extra?)** → dict — Build an accept/reject review-decision artifact linked to a review target",
        "artifact_patch_proposal" => "**artifact_patch_proposal(target, patch, extra?)** → dict — Build a proposed patch artifact linked to an existing review target",
        "artifact_verification_bundle" => "**artifact_verification_bundle(title, checks, extra?)** → dict — Bundle multiple verification checks into one review-ready artifact",
        "artifact_apply_intent" => "**artifact_apply_intent(target, intent, extra?)** → dict — Record an apply or merge intent linked to a reviewed artifact",
        "load_run_tree" => "**load_run_tree(path)** → dict — Load a persisted run together with delegated child-run lineage",
        "run_record_fixture" => "**run_record_fixture(run)** → dict — Derive a replay fixture from a run record",
        "run_record_eval" => "**run_record_eval(run, fixture?)** → dict — Evaluate one run against a fixture",
        "run_record_eval_suite" => "**run_record_eval_suite(cases)** → dict — Evaluate a list of run/fixture cases as a regression suite",
        "run_record_diff" => "**run_record_diff(left, right)** → dict — Compare two run records by status, stages, artifacts, and checkpoints",
        "eval_suite_manifest" => "**eval_suite_manifest(payload)** → dict — Normalize an eval-suite manifest for grouped regression runs",
        "eval_suite_run" => "**eval_suite_run(manifest)** → dict — Run an eval-suite manifest, including optional baseline comparisons",
        "eval_metric" => "**eval_metric(name, value, metadata?)** → nil — Record a named metric into the eval metric store for inclusion in run records",
        "eval_metrics" => "**eval_metrics()** → list — Return all recorded eval metrics as a list of `{name, value, metadata?}` dicts",
        // Mock HTTP
        "http_mock" => "**http_mock(method, url_pattern, response)** → nil — Register a mock HTTP response for testing",
        "http_mock_clear" => "**http_mock_clear()** → nil — Clear all mocks and recorded calls",
        "http_mock_calls" => "**http_mock_calls()** → list — Return recorded HTTP calls",
        // Graceful cancellation
        "cancel_graceful" => "**cancel_graceful(handle, timeout?)** → Result — Signal cancellation and wait for graceful shutdown",
        "is_cancelled" => "**is_cancelled()** → bool — Check if current task has been cancelled",
        _ => return None,
    };
    Some(doc.to_string())
}

pub(crate) fn keyword_doc(name: &str) -> Option<String> {
    let doc = match name {
        "pipeline" => "**pipeline** — Declare a named pipeline\n\n```harn\npipeline name(params) {\n  // body\n}\n```",
        "fn" => "**fn** — Declare a function\n\n```harn\nfn name(params) -> return_type {\n  // body\n}\n```",
        "let" => "**let** — Immutable variable binding\n\n```harn\nlet x: type = value\n```",
        "var" => "**var** — Mutable variable binding\n\n```harn\nvar x: type = value\n```",
        "if" => "**if** — Conditional expression\n\n```harn\nif condition {\n  // then\n} else {\n  // else\n}\n```",
        "else" => "**else** — Else branch of an if expression",
        "for" => "**for** — For-in loop\n\n```harn\nfor item in iterable {\n  // body\n}\n```",
        "while" => "**while** — While loop\n\n```harn\nwhile condition {\n  // body\n}\n```",
        "match" => "**match** — Pattern matching expression\n\n```harn\nmatch value {\n  pattern => body\n}\n```",
        "require" => "**require** — Runtime precondition check\n\n```harn\nrequire condition, \"message\"\n```\n\nThrows if the condition is false.",
        "return" => "**return** — Return a value from a function",
        "try" => "**try** — Try-catch error handling\n\n```harn\ntry {\n  // body\n} catch e {\n  // handle\n}\n```",
        "catch" => "**catch** — Catch block for error handling",
        "throw" => "**throw** — Throw an error value",
        "import" => "**import** — Import a module\n\n```harn\nimport \"path/to/module\"\n```",
        "spawn" => "**spawn** — Spawn an async task\n\n```harn\nlet handle = spawn {\n  // async body\n}\n```",
        "parallel" => "**parallel** — Execute N parallel tasks\n\n```harn\nparallel N {\n  // body\n}\n```",
        "parallel_map" => "**parallel_map** — Map over a list in parallel\n\n```harn\nparallel_map list as item {\n  // body\n}\n```",
        "parallel_settle" => "**parallel_settle** — Map over a list in parallel, collecting Ok/Err results\n\n```harn\nparallel_settle(items) { item ->\n  // body\n}\n// Returns {results: [Result], succeeded: int, failed: int}\n```",
        "retry" => "**retry** — Retry a block N times\n\n```harn\nretry N {\n  // body\n}\n```",
        "extends" => "**extends** — Inherit from another pipeline",
        "override" => "**override** — Override an inherited pipeline step",
        "true" | "false" => "**bool** — Boolean literal",
        "nil" => "**nil** — Nil value (absence of a value)",
        "in" => "**in** — Used in `for x in collection`",
        _ => return None,
    };
    Some(doc.to_string())
}