Skip to main content

harn_parser/
diagnostic.rs

1use std::io::IsTerminal;
2
3use harn_lexer::Span;
4use yansi::{Color, Paint};
5
6use crate::diagnostic_codes::Repair;
7use crate::ParserError;
8
9mod harness_migrations_generated;
10
11/// The typed harness path that replaced a removed global, from the generated
12/// projection of `harn_vm::stdlib::harness_migration_for_builtin`.
13///
14/// `harn-parser` compiles below `harn-vm`, so it cannot query the registry;
15/// `make gen-harness-migrations` emits the table and
16/// `make check-harness-migrations` keeps it from drifting.
17///
18/// **This is the fallback, not the first answer.** The hand-written tables
19/// above it encode migration decisions the registry cannot express, because the
20/// registry is keyed by name and some legacy globals collide with unrelated
21/// typed methods — the ambient `read_file` migrated to `harness.fs.read_text`,
22/// but a *different* `harness.tools.read_file` also exists, and that is what a
23/// name lookup finds. [`removed_global_replacement`] composes the sources in
24/// the right order; [`HARNESS_MIGRATION_DISAGREEMENTS`] is the audited list.
25pub fn generated_harness_migration(name: &str) -> Option<&'static str> {
26    harness_migrations_generated::HARNESS_MIGRATIONS
27        .binary_search_by_key(&name, |(legacy, _)| *legacy)
28        .ok()
29        .map(|index| harness_migrations_generated::HARNESS_MIGRATIONS[index].1)
30}
31
32pub struct RelatedSpanLabel<'a> {
33    pub span: &'a Span,
34    pub label: &'a str,
35}
36
37/// Normalize diagnostic filenames lexically for display.
38///
39/// This deliberately does not touch the filesystem: diagnostics should cancel
40/// `.` and `..` path components even when the path points at a file that no
41/// longer exists, without resolving symlinks.
42pub fn normalize_diagnostic_path(path: &str) -> String {
43    let posix = path.replace('\\', "/");
44    if posix.is_empty() {
45        return String::new();
46    }
47
48    let bytes = posix.as_bytes();
49    let mut drive = "";
50    let mut rest = posix.as_str();
51    #[expect(
52        clippy::string_slice,
53        reason = "bytes 0 and 1 are ASCII, so 2 is a char boundary"
54    )]
55    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
56        drive = &posix[..2];
57        rest = &posix[2..];
58    }
59
60    let absolute = rest.starts_with('/');
61    let mut stack: Vec<&str> = Vec::new();
62    for segment in rest.split('/').filter(|segment| !segment.is_empty()) {
63        match segment {
64            "." => {}
65            ".." => {
66                if let Some(top) = stack.last() {
67                    if *top != ".." {
68                        stack.pop();
69                        continue;
70                    }
71                }
72                if !absolute {
73                    stack.push("..");
74                }
75            }
76            _ => stack.push(segment),
77        }
78    }
79
80    let mut normalized = String::new();
81    normalized.push_str(drive);
82    if absolute {
83        normalized.push('/');
84    }
85    normalized.push_str(&stack.join("/"));
86    if normalized.is_empty() {
87        ".".to_string()
88    } else {
89        normalized
90    }
91}
92
93fn has_same_snake_case_segments(a: &str, b: &str) -> bool {
94    if !a.contains('_') || !b.contains('_') {
95        return false;
96    }
97    let mut a_segments: Vec<_> = a.split('_').collect();
98    let mut b_segments: Vec<_> = b.split('_').collect();
99    if a_segments.len() < 2
100        || a_segments.len() != b_segments.len()
101        || a_segments.iter().any(|segment| segment.is_empty())
102        || b_segments.iter().any(|segment| segment.is_empty())
103    {
104        return false;
105    }
106    a_segments.sort_unstable();
107    b_segments.sort_unstable();
108    a_segments == b_segments
109}
110
111/// Find the closest match to `name` among `candidates`, within `max_dist` edits
112/// or by reordering its non-empty underscore-separated segments. Candidates
113/// within the edit-distance threshold rank ahead of reorder-only matches.
114pub fn find_closest_match<'a>(
115    name: &str,
116    candidates: impl Iterator<Item = &'a str>,
117    max_dist: usize,
118) -> Option<&'a str> {
119    candidates
120        .filter(|candidate| *candidate != name)
121        .filter_map(|candidate| {
122            let reordered = has_same_snake_case_segments(name, candidate);
123            if candidate.len().abs_diff(name.len()) > max_dist && !reordered {
124                return None;
125            }
126            let distance = strsim::levenshtein(name, candidate);
127            (distance <= max_dist || reordered).then_some((distance, candidate))
128        })
129        .min_by_key(|(distance, _)| *distance)
130        .map(|(_, candidate)| candidate)
131}
132
133/// Return the replacement for stdlib symbols that were directly renamed.
134pub fn renamed_stdlib_symbol(name: &str) -> Option<&'static str> {
135    match name {
136        "retry_with_backoff" => Some("retry_predicate_with_backoff"),
137        "print" => Some("harness.stdio.print"),
138        "println" => Some("harness.stdio.println"),
139        "eprint" => Some("harness.stdio.eprint"),
140        "eprintln" => Some("harness.stdio.eprintln"),
141        "read_line" => Some("harness.stdio.read_line"),
142        "prompt_user" => Some("harness.stdio.prompt"),
143        "agent_session_open" => Some("harness.agent.open"),
144        "agent_session_workspace_anchor" => Some("harness.agent.workspace_anchor"),
145        "agent_session_set_workspace_anchor" => Some("harness.agent.set_workspace_anchor"),
146        "agent_session_workspace_policy" => Some("harness.agent.workspace_policy"),
147        "agent_session_set_workspace_policy" => Some("harness.agent.set_workspace_policy"),
148        "agent_session_add_root" => Some("harness.agent.add_root"),
149        "agent_session_remove_root" => Some("harness.agent.remove_root"),
150        "agent_session_list_roots" => Some("harness.agent.list_roots"),
151        "agent_session_exists" => Some("harness.agent.exists"),
152        "agent_session_length" => Some("harness.agent.length"),
153        "agent_session_snapshot" => Some("harness.agent.snapshot"),
154        "agent_session_ancestry" => Some("harness.agent.ancestry"),
155        "agent_session_current_id" => Some("harness.agent.current_id"),
156        "agent_session_record_changed_path" => Some("harness.agent.record_changed_path"),
157        "agent_session_actor_chain" => Some("harness.agent.actor_chain"),
158        "agent_session_tool_format" => Some("harness.agent.tool_format"),
159        "agent_session_system_prompt" => Some("harness.agent.system_prompt"),
160        "agent_session_scratchpad" => Some("harness.agent.scratchpad"),
161        "agent_session_set_scratchpad" => Some("harness.agent.set_scratchpad"),
162        "agent_session_clear_scratchpad" => Some("harness.agent.clear_scratchpad"),
163        "agent_session_claim_tool_format" => Some("harness.agent.claim_tool_format"),
164        "agent_session_reset" => Some("harness.agent.reset"),
165        "agent_session_fork" => Some("harness.agent.fork"),
166        "agent_session_fork_at" => Some("harness.agent.fork_at"),
167        "agent_session_rollback" => Some("harness.agent.rollback"),
168        "agent_session_redo" => Some("harness.agent.redo"),
169        "agent_session_close" => Some("harness.agent.close"),
170        "agent_session_trim" => Some("harness.agent.trim"),
171        "agent_session_attach" => Some("harness.agent.attach"),
172        "agent_session_takeover" => Some("harness.agent.takeover"),
173        "agent_session_detach" => Some("harness.agent.detach"),
174        "agent_session_heartbeat" => Some("harness.agent.heartbeat"),
175        "agent_session_live_clients" => Some("harness.agent.live_clients"),
176        "agent_session_client_inject_prompt" => Some("harness.agent.client_inject_prompt"),
177        "agent_session_route_permission" => Some("harness.agent.route_permission"),
178        "agent_session_inject" => Some("harness.agent.inject"),
179        "agent_session_post_event" => Some("harness.agent.post_event"),
180        "agent_session_drain_inbox" => Some("harness.agent.drain_inbox"),
181        "agent_session_seed_from_jsonl" => Some("harness.agent.seed_from_jsonl"),
182        "agent_session_reanchor" => Some("harness.agent.reanchor"),
183        "agent_session_compact" => Some("harness.agent.compact"),
184        _ => None,
185    }
186}
187
188/// What an undefined name *should* have been, for the type checker's
189/// "did you mean".
190///
191/// Three sources, narrowest first: the in-place renames above, then the
192/// `harness_*_replacement` families, then [`generated_harness_migration`] for
193/// the long tail — 417 generated rows against roughly 60 hand-written ones.
194///
195/// Deliberately separate from [`renamed_stdlib_symbol`], which the linter uses
196/// to decide whether to raise `HARN-LNT-001`. Widening *that* makes every
197/// migrated global draw two warnings: the rename lint and the capability-family
198/// lint that already claims the name (`HARN-LNT-052`/`053`/`054`/`057`/`071`).
199/// Measured before splitting them — a four-call probe went from four findings to
200/// eight. Which lint should own a name is a policy question; answering "what
201/// replaced it" is not, and only the type checker asks this one.
202///
203/// Order matters, and not for style. The generated table is keyed by builtin
204/// name, and some legacy globals share a name with an unrelated typed method —
205/// the ambient `read_file` migrated to `harness.fs.read_text`, while a separate
206/// `harness.tools.read_file` agent tool is what a name lookup finds.
207/// [`HARNESS_MIGRATION_DISAGREEMENTS`] pins those, so a new one is a build
208/// failure rather than a confidently wrong suggestion.
209pub fn removed_global_replacement(name: &str) -> Option<&'static str> {
210    if let Some(replacement) = renamed_stdlib_symbol(name) {
211        return Some(replacement);
212    }
213    for family in HARNESS_REPLACEMENT_FAMILIES {
214        if let Some(replacement) = family(name) {
215            return Some(replacement);
216        }
217    }
218    generated_harness_migration(name)
219}
220
221/// The `harness_*_replacement` families, in one list so anything meaning "any
222/// capability migration" walks the same set.
223///
224/// A new family belongs here as well as beside its siblings. Nothing proves
225/// that mechanically — Rust has no reflection over free functions — but this
226/// list is the only way anything reaches them in bulk, so forgetting it leaves
227/// the new family unreachable rather than half-wired.
228pub const HARNESS_REPLACEMENT_FAMILIES: &[fn(&str) -> Option<&'static str>] = &[
229    harness_clock_replacement,
230    harness_stdio_replacement,
231    harness_fs_replacement,
232    harness_env_replacement,
233    harness_random_replacement,
234    harness_net_replacement,
235];
236
237/// Legacy globals whose hand-written migration deliberately differs from what a
238/// name lookup in the generated table finds, with the reason.
239///
240/// Reviewed rather than discovered: a new entry means the runtime registry and
241/// the migration record disagree about a name, which is a finding to
242/// investigate — not a list to extend casually.
243pub const HARNESS_MIGRATION_DISAGREEMENTS: &[(&str, &str, &str)] = &[
244    (
245        "read_file",
246        "harness.fs.read_text",
247        "`harness.tools.read_file` is an agent tool, not the filesystem capability",
248    ),
249    (
250        "write_file",
251        "harness.fs.write_text",
252        "`harness.tools.write_file` is an agent tool, not the filesystem capability",
253    ),
254    (
255        "delete_file",
256        "harness.fs.delete",
257        "`harness.tools.delete_file` is an agent tool, not the filesystem capability",
258    ),
259    (
260        "elapsed",
261        "harness.clock.monotonic_ms",
262        "`elapsed` was renamed, so the same-named `harness.clock.elapsed` is not its successor",
263    ),
264];
265
266/// Map an ambient clock-capability builtin to its `harness.clock.*`
267/// replacement. Returns the new identifier text (including the receiver
268/// path) so the `bindings/thread-harness-clock` repair can replace the
269/// call-site identifier in place. The mapping is the source of truth for
270/// the E4.3 → E4.6 migration; downstream replatform agents query it via
271/// [`Code::repair_template`].
272pub fn harness_clock_replacement(name: &str) -> Option<&'static str> {
273    match name {
274        "now_ms" => Some("harness.clock.now_ms"),
275        "monotonic_ms" => Some("harness.clock.monotonic_ms"),
276        "sleep_ms" => Some("harness.clock.sleep_ms"),
277        "sleep" => Some("harness.clock.sleep_ms"),
278        "timestamp" => Some("harness.clock.timestamp"),
279        "elapsed" => Some("harness.clock.monotonic_ms"),
280        "date_now" => Some("harness.clock.now"),
281        "date_now_iso" => Some("harness.clock.date_iso"),
282        _ => None,
283    }
284}
285
286/// Map an ambient stdio-capability builtin to its `harness.stdio.*`
287/// replacement so `harn fix` can replace the call in place once the
288/// relevant harness binding is available.
289pub fn harness_stdio_replacement(name: &str) -> Option<&'static str> {
290    match name {
291        "print" => Some("harness.stdio.print"),
292        "println" => Some("harness.stdio.println"),
293        "eprint" => Some("harness.stdio.eprint"),
294        "eprintln" => Some("harness.stdio.eprintln"),
295        "read_line" => Some("harness.stdio.read_line"),
296        "prompt_user" => Some("harness.stdio.prompt"),
297        _ => None,
298    }
299}
300
301/// Map an ambient fs-capability builtin to its `harness.fs.*` replacement.
302/// Backs the `bindings/thread-harness-fs` repair the E4.4 → E4.6
303/// migration uses to rewrite `.harn` scripts off the legacy surface.
304pub fn harness_fs_replacement(name: &str) -> Option<&'static str> {
305    match name {
306        "read_file" => Some("harness.fs.read_text"),
307        "read_file_result" => Some("harness.fs.read_text_result"),
308        "read_file_bytes" => Some("harness.fs.read_bytes"),
309        "write_file" => Some("harness.fs.write_text"),
310        "write_file_bytes" => Some("harness.fs.write_bytes"),
311        "replace_file" => Some("harness.fs.replace_text"),
312        "replace_file_result" => Some("harness.fs.replace_text_result"),
313        "replace_file_bytes" => Some("harness.fs.replace_bytes"),
314        "replace_file_bytes_result" => Some("harness.fs.replace_bytes_result"),
315        "file_exists" => Some("harness.fs.exists"),
316        "path_status" => Some("harness.fs.status"),
317        "delete_file" => Some("harness.fs.delete"),
318        "append_file" => Some("harness.fs.append"),
319        "append_file_locked" => Some("harness.fs.append_locked"),
320        "list_dir" => Some("harness.fs.list_dir"),
321        "mkdir" => Some("harness.fs.mkdir"),
322        "copy_file" => Some("harness.fs.copy"),
323        "temp_dir" => Some("harness.fs.temp_dir"),
324        "workspace_temp_dir" => Some("harness.fs.workspace_temp_dir"),
325        "mkdtemp" => Some("harness.fs.mkdtemp"),
326        "mkdtemp_in_workspace" => Some("harness.fs.mkdtemp_in_workspace"),
327        "stat" => Some("harness.fs.stat"),
328        "move_file" => Some("harness.fs.rename"),
329        "read_lines" => Some("harness.fs.read_lines"),
330        "read_lines_page_result" => Some("harness.fs.read_lines_page_result"),
331        "walk_dir" => Some("harness.fs.walk"),
332        "glob" => Some("harness.fs.glob"),
333        "find_text" => Some("harness.fs.find_text"),
334        "find_evidence" => Some("harness.fs.find_evidence"),
335        "cwd" => Some("harness.fs.cwd"),
336        _ => None,
337    }
338}
339
340/// Map an ambient env-capability builtin to its `harness.env.*` replacement.
341/// Backs the `bindings/thread-harness-env` repair.
342pub fn harness_env_replacement(name: &str) -> Option<&'static str> {
343    match name {
344        "env" => Some("harness.env.get"),
345        "env_or" => Some("harness.env.get_or"),
346        _ => None,
347    }
348}
349
350/// Map an ambient random-capability builtin to its `harness.random.*`
351/// replacement. Backs the `bindings/thread-harness-random` repair.
352pub fn harness_random_replacement(name: &str) -> Option<&'static str> {
353    match name {
354        "random" => Some("harness.random.f64"),
355        "random_int" => Some("harness.random.range"),
356        "random_choice" => Some("harness.random.choice"),
357        "random_shuffle" => Some("harness.random.shuffle"),
358        _ => None,
359    }
360}
361
362/// Map an ambient net-capability builtin to its `harness.net.*`
363/// replacement. Backs the `bindings/thread-harness-net` repair. Every
364/// script-facing network effect is exposed only through `HarnessNet`; response
365/// constructors and event encoders remain pure globals.
366pub fn harness_net_replacement(name: &str) -> Option<&'static str> {
367    match name {
368        "http_get" => Some("harness.net.get"),
369        "http_post" => Some("harness.net.post"),
370        "http_put" => Some("harness.net.put"),
371        "http_patch" => Some("harness.net.patch"),
372        "http_delete" => Some("harness.net.delete"),
373        "http_request" => Some("harness.net.request"),
374        "http_download" => Some("harness.net.download"),
375        "http_server" => Some("harness.net.server"),
376        "http_server_after" => Some("harness.net.server_after"),
377        "http_server_before" => Some("harness.net.server_before"),
378        "http_server_on_shutdown" => Some("harness.net.server_on_shutdown"),
379        "http_server_readiness" => Some("harness.net.server_readiness"),
380        "http_server_ready" => Some("harness.net.server_ready"),
381        "http_server_request" => Some("harness.net.server_request"),
382        "http_server_route" => Some("harness.net.server_route"),
383        "http_server_security_headers" => Some("harness.net.server_security_headers"),
384        "http_server_set_ready" => Some("harness.net.server_set_ready"),
385        "http_server_shutdown" => Some("harness.net.server_shutdown"),
386        "http_server_test" => Some("harness.net.server_test"),
387        "http_server_tls_edge" => Some("harness.net.server_tls_edge"),
388        "http_server_tls_pem" => Some("harness.net.server_tls_pem"),
389        "http_server_tls_plain" => Some("harness.net.server_tls_plain"),
390        "http_server_tls_self_signed_dev" => Some("harness.net.server_tls_self_signed_dev"),
391        "http_session" => Some("harness.net.session"),
392        "http_session_close" => Some("harness.net.session_close"),
393        "http_session_request" => Some("harness.net.session_request"),
394        "http_stream_close" => Some("harness.net.stream_close"),
395        "http_stream_info" => Some("harness.net.stream_info"),
396        "http_stream_open" => Some("harness.net.stream_open"),
397        "http_stream_read" => Some("harness.net.stream_read"),
398        "sse_close" => Some("harness.net.sse_close"),
399        "sse_connect" => Some("harness.net.sse_connect"),
400        "sse_receive" => Some("harness.net.sse_receive"),
401        "sse_server_cancel" => Some("harness.net.sse_server_cancel"),
402        "sse_server_cancelled" => Some("harness.net.sse_server_cancelled"),
403        "sse_server_close" => Some("harness.net.sse_server_close"),
404        "sse_server_disconnected" => Some("harness.net.sse_server_disconnected"),
405        "sse_server_flush" => Some("harness.net.sse_server_flush"),
406        "sse_server_heartbeat" => Some("harness.net.sse_server_heartbeat"),
407        "sse_server_response" => Some("harness.net.sse_server_response"),
408        "sse_server_send" => Some("harness.net.sse_server_send"),
409        "sse_server_status" => Some("harness.net.sse_server_status"),
410        "websocket_accept" => Some("harness.net.websocket_accept"),
411        "websocket_close" => Some("harness.net.websocket_close"),
412        "websocket_connect" => Some("harness.net.websocket_connect"),
413        "websocket_receive" => Some("harness.net.websocket_receive"),
414        "websocket_route" => Some("harness.net.websocket_route"),
415        "websocket_send" => Some("harness.net.websocket_send"),
416        "websocket_server" => Some("harness.net.websocket_server"),
417        "websocket_server_close" => Some("harness.net.websocket_server_close"),
418        _ => None,
419    }
420}
421
422/// Render a Rust-style diagnostic message.
423///
424/// Example output:
425/// ```text
426/// error: undefined variable `x`
427///   --> example.harn:5:12
428///    |
429///  5 |     let y = x + 1
430///    |             ^ not found in this scope
431/// ```
432pub fn render_diagnostic(
433    source: &str,
434    filename: &str,
435    span: &Span,
436    severity: &str,
437    message: &str,
438    label: Option<&str>,
439    help: Option<&str>,
440) -> String {
441    render_diagnostic_inner(RenderDiagnostic {
442        source,
443        filename,
444        span,
445        severity,
446        code: None,
447        message,
448        label,
449        help,
450        related: &[],
451        repair: None,
452    })
453}
454
455pub fn render_diagnostic_with_code(
456    source: &str,
457    filename: &str,
458    span: &Span,
459    severity: &str,
460    code: crate::diagnostic_codes::Code,
461    message: &str,
462    label: Option<&str>,
463    help: Option<&str>,
464) -> String {
465    let repair_owned = code.repair_template().map(Repair::from_template);
466    render_diagnostic_inner(RenderDiagnostic {
467        source,
468        filename,
469        span,
470        severity,
471        code: Some(code.as_str()),
472        message,
473        label,
474        help,
475        related: &[],
476        repair: repair_owned.as_ref(),
477    })
478}
479
480pub fn render_diagnostic_with_related(
481    source: &str,
482    filename: &str,
483    span: &Span,
484    severity: &str,
485    message: &str,
486    label: Option<&str>,
487    help: Option<&str>,
488    related: &[RelatedSpanLabel<'_>],
489) -> String {
490    render_diagnostic_inner(RenderDiagnostic {
491        source,
492        filename,
493        span,
494        severity,
495        code: None,
496        message,
497        label,
498        help,
499        related,
500        repair: None,
501    })
502}
503
504struct RenderDiagnostic<'a> {
505    source: &'a str,
506    filename: &'a str,
507    span: &'a Span,
508    severity: &'a str,
509    code: Option<&'a str>,
510    message: &'a str,
511    label: Option<&'a str>,
512    help: Option<&'a str>,
513    related: &'a [RelatedSpanLabel<'a>],
514    repair: Option<&'a Repair>,
515}
516
517fn render_diagnostic_inner(input: RenderDiagnostic<'_>) -> String {
518    let mut out = String::new();
519    let source = input.source;
520    let span = input.span;
521    let severity = input.severity;
522    let message = input.message;
523    let label = input.label;
524    let help = input.help;
525    let related = input.related;
526    let filename = normalize_diagnostic_path(input.filename);
527    let severity_color = severity_color(severity);
528    let gutter = style_fragment("|", Color::Blue, false);
529    let arrow = style_fragment("-->", Color::Blue, true);
530    let help_prefix = style_fragment("help", Color::Cyan, true);
531    let note_prefix = style_fragment("note", Color::Magenta, true);
532
533    out.push_str(&style_fragment(severity, severity_color, true));
534    if let Some(code) = input.code {
535        out.push('[');
536        out.push_str(code);
537        out.push(']');
538    }
539    out.push_str(": ");
540    out.push_str(message);
541    out.push('\n');
542
543    let line_num = span.line;
544    let col_num = span.column;
545
546    let gutter_width = line_num.to_string().len();
547
548    out.push_str(&format!(
549        "{:>width$}{arrow} {filename}:{line_num}:{col_num}\n",
550        " ",
551        width = gutter_width + 1,
552    ));
553
554    out.push_str(&format!(
555        "{:>width$} {gutter}\n",
556        " ",
557        width = gutter_width + 1,
558    ));
559
560    let source_line_opt = line_num.checked_sub(1).and_then(|n| source.lines().nth(n));
561    if let Some(source_line) = source_line_opt {
562        out.push_str(&format!(
563            "{:>width$} {gutter} {source_line}\n",
564            line_num,
565            width = gutter_width + 1,
566        ));
567
568        if let Some(label_text) = label {
569            // Span width must use char count, not byte offsets, so carets align with the source text.
570            let span_len = diagnostic_span_char_len(source, span);
571            let col_num = col_num.max(1);
572            let padding = " ".repeat(col_num - 1);
573            let carets = style_fragment(&"^".repeat(span_len), severity_color, true);
574            out.push_str(&format!(
575                "{:>width$} {gutter} {padding}{carets} {label_text}\n",
576                " ",
577                width = gutter_width + 1,
578            ));
579        }
580    }
581
582    if let Some(help_text) = help {
583        out.push_str(&format!(
584            "{:>width$} = {help_prefix}: {help_text}\n",
585            " ",
586            width = gutter_width + 1,
587        ));
588    }
589
590    if let Some(repair) = input.repair {
591        let repair_prefix = style_fragment("repair", Color::Cyan, true);
592        out.push_str(&format!(
593            "{:>width$} = {repair_prefix}: {} [{}] — {}\n",
594            " ",
595            repair.id,
596            repair.safety,
597            repair.summary,
598            width = gutter_width + 1,
599        ));
600    }
601
602    for item in related {
603        out.push_str(&format!(
604            "{:>width$} = {note_prefix}: {}\n",
605            " ",
606            item.label,
607            width = gutter_width + 1,
608        ));
609        render_related_span(
610            &mut out,
611            source,
612            &filename,
613            item.span,
614            item.label,
615            gutter_width,
616        );
617    }
618
619    if let Some(note_text) = fun_note(severity) {
620        out.push_str(&format!(
621            "{:>width$} = {note_prefix}: {note_text}\n",
622            " ",
623            width = gutter_width + 1,
624        ));
625    }
626
627    out
628}
629
630pub fn render_type_diagnostic(
631    source: &str,
632    filename: &str,
633    diag: &crate::typechecker::TypeDiagnostic,
634) -> String {
635    let severity = match diag.severity {
636        crate::typechecker::DiagnosticSeverity::Error => "error",
637        crate::typechecker::DiagnosticSeverity::Warning => "warning",
638    };
639    let related = diag
640        .related
641        .iter()
642        .map(|related| RelatedSpanLabel {
643            span: &related.span,
644            label: &related.message,
645        })
646        .collect::<Vec<_>>();
647    let primary_label = type_diagnostic_primary_label(diag);
648    match &diag.span {
649        Some(span) => render_diagnostic_inner(RenderDiagnostic {
650            source,
651            filename,
652            span,
653            severity,
654            code: Some(diag.code.as_str()),
655            message: &diag.message,
656            label: primary_label.as_deref(),
657            help: diag.help.as_deref(),
658            related: &related,
659            repair: diag.repair.as_ref(),
660        }),
661        None => match diag.repair.as_ref() {
662            Some(repair) => format!(
663                "{severity}[{}]: {}\n  = repair: {} [{}] — {}\n",
664                diag.code, diag.message, repair.id, repair.safety, repair.summary,
665            ),
666            None => format!("{severity}[{}]: {}\n", diag.code, diag.message),
667        },
668    }
669}
670
671pub fn lexer_error_code(err: &harn_lexer::LexerError) -> crate::diagnostic_codes::Code {
672    match err {
673        harn_lexer::LexerError::UnexpectedCharacter(_, _) => {
674            crate::diagnostic_codes::Code::ParserUnexpectedCharacter
675        }
676        harn_lexer::LexerError::UnterminatedString(_) => {
677            crate::diagnostic_codes::Code::ParserUnterminatedString
678        }
679        harn_lexer::LexerError::UnterminatedBlockComment(_) => {
680            crate::diagnostic_codes::Code::ParserUnterminatedBlockComment
681        }
682        harn_lexer::LexerError::IntegerLiteralOutOfRange(_, _) => {
683            crate::diagnostic_codes::Code::ParserIntegerLiteralOutOfRange
684        }
685    }
686}
687
688pub fn parser_error_code(err: &crate::parser::ParserError) -> crate::diagnostic_codes::Code {
689    match err {
690        crate::parser::ParserError::Unexpected { .. } => {
691            crate::diagnostic_codes::Code::ParserUnexpectedToken
692        }
693        crate::parser::ParserError::UnexpectedEof { .. } => {
694            crate::diagnostic_codes::Code::ParserUnexpectedEof
695        }
696    }
697}
698
699fn type_diagnostic_primary_label(diag: &crate::typechecker::TypeDiagnostic) -> Option<String> {
700    match &diag.details {
701        Some(crate::typechecker::DiagnosticDetails::LintRule { rule }) => {
702            Some(format!("lint[{rule}]"))
703        }
704        Some(crate::typechecker::DiagnosticDetails::TypeMismatch { .. }) => {
705            Some("found this type".to_string())
706        }
707        _ => None,
708    }
709}
710
711fn render_related_span(
712    out: &mut String,
713    source: &str,
714    filename: &str,
715    span: &Span,
716    label: &str,
717    primary_gutter_width: usize,
718) {
719    let filename = normalize_diagnostic_path(filename);
720    let severity_color = Color::Magenta;
721    let gutter = style_fragment("|", Color::Blue, false);
722    let arrow = style_fragment("-->", Color::Blue, true);
723    let line_num = span.line;
724    let col_num = span.column;
725    let gutter_width = primary_gutter_width.max(line_num.to_string().len());
726
727    out.push_str(&format!(
728        "{:>width$}{arrow} {filename}:{line_num}:{col_num}\n",
729        " ",
730        width = gutter_width + 1,
731    ));
732    out.push_str(&format!(
733        "{:>width$} {gutter}\n",
734        " ",
735        width = gutter_width + 1,
736    ));
737
738    if let Some(source_line) = line_num.checked_sub(1).and_then(|n| source.lines().nth(n)) {
739        out.push_str(&format!(
740            "{:>width$} {gutter} {source_line}\n",
741            line_num,
742            width = gutter_width + 1,
743        ));
744        let span_len = diagnostic_span_char_len(source, span);
745        let padding = " ".repeat(col_num.max(1) - 1);
746        let carets = style_fragment(&"^".repeat(span_len), severity_color, true);
747        out.push_str(&format!(
748            "{:>width$} {gutter} {padding}{carets} {label}\n",
749            " ",
750            width = gutter_width + 1,
751        ));
752    }
753}
754
755fn diagnostic_span_char_len(source: &str, span: &Span) -> usize {
756    if span.end <= span.start || span.start >= source.len() {
757        return 1;
758    }
759    let mut start = span.start.min(source.len());
760    while start > 0 && !source.is_char_boundary(start) {
761        start -= 1;
762    }
763    let mut end = span.end.min(source.len());
764    while end < source.len() && !source.is_char_boundary(end) {
765        end += 1;
766    }
767    source
768        .get(start..end)
769        .map(|text| text.chars().count().max(1))
770        .unwrap_or(1)
771}
772
773fn severity_color(severity: &str) -> Color {
774    match severity {
775        "error" => Color::Red,
776        "warning" => Color::Yellow,
777        "note" => Color::Magenta,
778        _ => Color::Cyan,
779    }
780}
781
782fn style_fragment(text: &str, color: Color, bold: bool) -> String {
783    if !colors_enabled() {
784        return text.to_string();
785    }
786
787    let mut paint = Paint::new(text).fg(color);
788    if bold {
789        paint = paint.bold();
790    }
791    paint.to_string()
792}
793
794thread_local! {
795    /// Per-thread override for color output. When `Some`, it wins over the
796    /// `NO_COLOR` env var and TTY detection. This lets tests force colors off
797    /// deterministically without mutating the process-global `NO_COLOR` env
798    /// var, which races across parallel tests (each test runs on its own
799    /// thread, so the override is naturally isolated).
800    static COLOR_OVERRIDE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
801}
802
803/// Force color output on (`Some(true)`), off (`Some(false)`), or restore the
804/// default env/TTY behavior (`None`) for the current thread only.
805#[cfg(test)]
806pub(crate) fn set_color_override(force: Option<bool>) {
807    COLOR_OVERRIDE.with(|cell| cell.set(force));
808}
809
810fn colors_enabled() -> bool {
811    if let Some(forced) = COLOR_OVERRIDE.with(std::cell::Cell::get) {
812        return forced;
813    }
814    std::env::var_os("NO_COLOR").is_none() && std::io::stderr().is_terminal()
815}
816
817fn fun_note(severity: &str) -> Option<&'static str> {
818    if std::env::var("HARN_FUN").ok().as_deref() != Some("1") {
819        return None;
820    }
821
822    Some(match severity {
823        "error" => "the compiler stepped on a rake here.",
824        "warning" => "this still runs, but it has strong 'double-check me' energy.",
825        _ => "a tiny gremlin has left a note in the margins.",
826    })
827}
828
829pub fn parser_error_message(err: &ParserError) -> String {
830    match err {
831        ParserError::Unexpected { got, expected, .. } => {
832            format!("expected {expected}, found {got}")
833        }
834        ParserError::UnexpectedEof { expected, .. } => {
835            format!("unexpected end of file, expected {expected}")
836        }
837    }
838}
839
840pub fn parser_error_label(err: &ParserError) -> &'static str {
841    match err {
842        ParserError::Unexpected { got, .. } if got == "Newline" => "line break not allowed here",
843        ParserError::Unexpected { .. } => "unexpected token",
844        ParserError::UnexpectedEof { .. } => "file ends here",
845    }
846}
847
848pub fn parser_error_help(err: &ParserError) -> Option<&'static str> {
849    match err {
850        ParserError::UnexpectedEof { expected, .. } | ParserError::Unexpected { expected, .. } => {
851            match expected.as_str() {
852                "}" => Some("add a closing `}` to finish this block"),
853                ")" => Some("add a closing `)` to finish this expression or parameter list"),
854                "]" => Some("add a closing `]` to finish this list or subscript"),
855                "fn, struct, enum, or pipeline after pub" => {
856                    Some("use `pub fn`, `pub pipeline`, `pub enum`, or `pub struct`")
857                }
858                "fn, tool, skill, eval_pack, struct, enum, type, pipeline, const, let, or import after pub" => Some(
859                    "use `pub` with `fn`, `tool`, `skill`, `eval_pack`, `struct`, `enum`, `type`, `pipeline`, `const`, `let`, or `import`",
860                ),
861                _ => None,
862            }
863        }
864    }
865}
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870
871    /// Ensure ANSI colors are off so plain-text assertions work regardless
872    /// of whether the test runner's stderr is a TTY. Uses a thread-local
873    /// override rather than the process-global `NO_COLOR` env var so it can't
874    /// race with color-sensitive assertions in parallel tests.
875    fn disable_colors() {
876        set_color_override(Some(false));
877    }
878
879    #[test]
880    fn test_basic_diagnostic() {
881        disable_colors();
882        let source = "pipeline default(task) {\n    const y = x + 1\n}";
883        let span = Span {
884            start: 28,
885            end: 29,
886            line: 2,
887            column: 13,
888            end_line: 2,
889        };
890        let output = render_diagnostic(
891            source,
892            "example.harn",
893            &span,
894            "error",
895            "undefined variable `x`",
896            Some("not found in this scope"),
897            None,
898        );
899        assert!(output.contains("error: undefined variable `x`"));
900        assert!(output.contains("--> example.harn:2:13"));
901        assert!(output.contains("const y = x + 1"));
902        assert!(output.contains("^ not found in this scope"));
903    }
904
905    #[test]
906    fn test_diagnostic_normalizes_filename() {
907        disable_colors();
908        let source = "const value = thing";
909        let span = Span {
910            start: 12,
911            end: 17,
912            line: 1,
913            column: 13,
914            end_line: 1,
915        };
916        let output = render_diagnostic(
917            source,
918            "/workspace/pipelines/mode/../lib/runtime/loop.harn",
919            &span,
920            "error",
921            "bad value",
922            Some("here"),
923            None,
924        );
925        assert!(output.contains("--> /workspace/pipelines/lib/runtime/loop.harn:1:13"));
926        assert!(!output.contains("/../"));
927    }
928
929    #[test]
930    fn test_diagnostic_with_help() {
931        disable_colors();
932        let source = "const y = xx + 1";
933        let span = Span {
934            start: 8,
935            end: 10,
936            line: 1,
937            column: 9,
938            end_line: 1,
939        };
940        let output = render_diagnostic(
941            source,
942            "test.harn",
943            &span,
944            "error",
945            "undefined variable `xx`",
946            Some("not found in this scope"),
947            Some("did you mean `x`?"),
948        );
949        assert!(output.contains("help: did you mean `x`?"));
950    }
951
952    #[test]
953    fn test_multiline_source() {
954        disable_colors();
955        let source = "line1\nline2\nline3";
956        let span = Span::with_offsets(6, 11, 2, 1); // "line2"
957        let result = render_diagnostic(
958            source,
959            "test.harn",
960            &span,
961            "error",
962            "bad line",
963            Some("here"),
964            None,
965        );
966        assert!(result.contains("line2"));
967        assert!(result.contains("^^^^^"));
968    }
969
970    #[test]
971    fn diagnostic_rendering_tolerates_offsets_inside_utf8_codepoints() {
972        disable_colors();
973        let source = "// capability owner — narrow helper";
974        let em_dash = source.find('—').expect("em dash");
975        let span = Span::with_offsets(0, em_dash + 1, 1, 1);
976        let output = render_diagnostic(
977            source,
978            "unicode.harn",
979            &span,
980            "warning",
981            "legacy comment",
982            Some("rewrite this comment"),
983            None,
984        );
985        assert!(output.contains("capability owner — narrow helper"));
986        assert!(output.contains("rewrite this comment"));
987    }
988
989    #[test]
990    fn test_single_char_span() {
991        disable_colors();
992        let source = "const x = 42";
993        let span = Span::with_offsets(4, 5, 1, 5); // "x"
994        let result = render_diagnostic(
995            source,
996            "test.harn",
997            &span,
998            "warning",
999            "unused",
1000            Some("never used"),
1001            None,
1002        );
1003        assert!(result.contains('^'));
1004        assert!(result.contains("never used"));
1005    }
1006
1007    #[test]
1008    fn test_with_help() {
1009        disable_colors();
1010        let source = "const y = reponse";
1011        let span = Span::with_offsets(8, 15, 1, 9);
1012        let result = render_diagnostic(
1013            source,
1014            "test.harn",
1015            &span,
1016            "error",
1017            "undefined",
1018            None,
1019            Some("did you mean `response`?"),
1020        );
1021        assert!(result.contains("help:"));
1022        assert!(result.contains("response"));
1023    }
1024
1025    #[test]
1026    fn closest_match_suggests_reordered_snake_case_segments() {
1027        assert_eq!(
1028            find_closest_match("parse_json", ["json_parse"].into_iter(), 2),
1029            Some("json_parse")
1030        );
1031        assert_eq!(
1032            find_closest_match("read_file", ["file_read"].into_iter(), 2),
1033            Some("file_read")
1034        );
1035        assert_eq!(
1036            find_closest_match("parse_json", ["parse_yaml"].into_iter(), 2),
1037            None
1038        );
1039    }
1040
1041    #[test]
1042    fn closest_match_suggests_plain_typo() {
1043        assert_eq!(
1044            find_closest_match("json_pars", ["json_parse"].into_iter(), 2),
1045            Some("json_parse")
1046        );
1047    }
1048
1049    #[test]
1050    fn test_parser_error_helpers_for_eof() {
1051        disable_colors();
1052        let err = ParserError::UnexpectedEof {
1053            expected: "}".into(),
1054            span: Span::with_offsets(10, 10, 3, 1),
1055        };
1056        assert_eq!(
1057            parser_error_message(&err),
1058            "unexpected end of file, expected }"
1059        );
1060        assert_eq!(parser_error_label(&err), "file ends here");
1061        assert_eq!(
1062            parser_error_help(&err),
1063            Some("add a closing `}` to finish this block")
1064        );
1065    }
1066}
1067
1068#[cfg(test)]
1069mod harness_migration_tests {
1070    use super::{
1071        generated_harness_migration, removed_global_replacement, renamed_stdlib_symbol,
1072        HARNESS_MIGRATION_DISAGREEMENTS, HARNESS_REPLACEMENT_FAMILIES,
1073    };
1074
1075    /// The case that motivated harn#6151: the type checker's fuzzy fallback
1076    /// answered `uuid_v5` — a name-based UUID — for the time-ordered `uuid_v7`,
1077    /// while the runtime record one crate away already knew the answer.
1078    #[test]
1079    fn a_migrated_global_resolves_instead_of_falling_through_to_a_guess() {
1080        assert_eq!(
1081            removed_global_replacement("uuid_v7"),
1082            Some("harness.random.uuid_v7")
1083        );
1084        // And the linter's narrower question is unchanged, so `uuid_v7` does
1085        // not start drawing a rename lint on top of its capability lint.
1086        assert_eq!(renamed_stdlib_symbol("uuid_v7"), None);
1087    }
1088
1089    /// The generated table is keyed by builtin name, and a few legacy globals
1090    /// share a name with an unrelated typed method. The hand-written answer has
1091    /// to win, or `harn check` sends a filesystem call to an agent tool.
1092    #[test]
1093    fn a_name_collision_resolves_to_the_migration_not_the_same_named_method() {
1094        for (legacy, migration, reason) in HARNESS_MIGRATION_DISAGREEMENTS {
1095            assert_eq!(
1096                removed_global_replacement(legacy),
1097                Some(*migration),
1098                "`{legacy}` must resolve to its migration — {reason}"
1099            );
1100            assert_ne!(
1101                generated_harness_migration(legacy),
1102                Some(*migration),
1103                "`{legacy}` is pinned as a disagreement but the generated table now \
1104                 agrees; drop it from HARNESS_MIGRATION_DISAGREEMENTS"
1105            );
1106        }
1107    }
1108
1109    /// Every hand-written family entry either matches the generated table or is
1110    /// a pinned disagreement. A fifth divergence fails here rather than shipping
1111    /// a confidently wrong "did you mean".
1112    #[test]
1113    fn no_unreviewed_disagreement_between_the_hand_written_and_generated_tables() {
1114        let pinned: Vec<&str> = HARNESS_MIGRATION_DISAGREEMENTS
1115            .iter()
1116            .map(|(legacy, _, _)| *legacy)
1117            .collect();
1118        let mut unreviewed = Vec::new();
1119        for (legacy, generated) in super::harness_migrations_generated::HARNESS_MIGRATIONS {
1120            if pinned.contains(legacy) {
1121                continue;
1122            }
1123            for family in HARNESS_REPLACEMENT_FAMILIES {
1124                if let Some(hand_written) = family(legacy) {
1125                    if hand_written != *generated {
1126                        unreviewed.push(format!(
1127                            "`{legacy}`: hand-written={hand_written} generated={generated}"
1128                        ));
1129                    }
1130                }
1131            }
1132        }
1133        assert!(
1134            unreviewed.is_empty(),
1135            "these names disagree without a reviewed reason:\n{}",
1136            unreviewed.join("\n")
1137        );
1138    }
1139
1140    /// The generator emits the table sorted; the lookup binary-searches it.
1141    #[test]
1142    fn the_generated_table_is_sorted_and_unique() {
1143        let table = super::harness_migrations_generated::HARNESS_MIGRATIONS;
1144        assert!(table.len() > 100, "expected the whole migrated surface");
1145        for pair in table.windows(2) {
1146            assert!(
1147                pair[0].0 < pair[1].0,
1148                "`{}` and `{}` are out of order or duplicated",
1149                pair[0].0,
1150                pair[1].0
1151            );
1152        }
1153    }
1154}