Skip to main content

calcit_cli/cli_handlers/
query.rs

1//! Query subcommand handlers
2//!
3//! Handles: calcit query ns, defs, def, at, peek, examples, find, usages, pkg, config, error, modules
4
5use super::chunk_display::{ChunkDisplayOptions, ChunkedDisplay, maybe_chunk_node};
6use super::common::{
7  cirru_to_json_value, deps_path_for_snapshot, emit_cli_output, format_path, markdown_fenced_block, parse_path,
8  print_cli_warning_block, resolve_definition_lookup, shell_quote,
9};
10use super::cursor::{
11  CursorLastQuery, resolve_active_cursor_reference, resolve_cursor_path_argument, resolve_cursor_target_argument,
12  set_cursor_from_query_match,
13};
14use super::fix::{SOURCE_SCOPE_HEADS, source_reference_paths};
15use super::stdout::{cli_print as print, cli_println as println};
16use super::structured_output::{StructuredOutputFormat, format_json_value_as_edn, json_value_to_edn};
17use super::tips::command_guidance_enabled;
18use crate::call_tree::{CallTreeAnalyzer, CallTreeConfig};
19use crate::cli_args::{
20  ConfigCommand, ConfigShowCommand, ConfigSubcommand, QueryCommand, QueryConfigCommand, QueryContextCommand, QueryDefCommand,
21  QueryDefsCommand, QuerySubcommand, QueryTypeAtCommand, QueryTypeCommand,
22};
23use calcit_core::CalcitTypeAnnotation;
24use calcit_core::calcit::{Calcit, CalcitFnTypeAnnotation, CalcitProc, CalcitSyntax, DYNAMIC_TYPE, LocatedWarning};
25use calcit_core::call_stack::CallStackList;
26use calcit_core::data::cirru::code_to_calcit;
27use calcit_core::data::edn::format_edn_display;
28use calcit_core::js_ffi_source::{JsFfiSource, parse_js_source};
29use calcit_core::load_core_snapshot;
30use calcit_core::project_state::{self, ERROR_STATE_FILE};
31use calcit_core::snapshot;
32use calcit_core::util::string::strip_shebang;
33use calcit_core::{program, runner};
34use cirru_edn::EdnTag;
35use cirru_parser::Cirru;
36use colored::Colorize;
37use md5::{Digest, Md5};
38use serde::Serialize;
39use std::cell::RefCell;
40use std::collections::{BTreeMap, HashSet};
41use std::fmt::Write as _;
42use std::fs;
43use std::path::Path;
44use std::sync::Arc;
45
46use super::edit::navigate_to_path;
47
48/// Type alias for search results: (namespace, definition, matches)
49type SearchResults = Vec<(String, String, Vec<(Vec<usize>, Cirru)>)>;
50
51/// Type alias for reference results: (namespace, definition, context, coordinate-path, source-label)
52type RefResults = Vec<(String, String, String, Vec<Vec<usize>>, &'static str)>;
53
54struct SearchCommonOpts<'a> {
55  filter: Option<&'a str>,
56  loose: bool,
57  regex: bool,
58  max_depth: usize,
59  entry: Option<&'a str>,
60  source: SearchSource,
61  detail_offset: usize,
62  parent_path: bool,
63  format: QueryRenderFormat,
64  set_cursor: Option<usize>,
65  compact_output: bool,
66}
67
68const DETAILED_RESULTS_WINDOW: usize = 3;
69const TYPE_AT_SCHEMA_VERSION: u32 = 2;
70
71struct SpecialBuiltinQueryMeta {
72  doc: &'static str,
73  schema: Arc<CalcitTypeAnnotation>,
74  runtime_arity: Option<RuntimeCallArity>,
75  examples: Vec<Cirru>,
76  expr_preview: &'static str,
77  cirru_note: &'static str,
78  semantic_tags: &'static [&'static str],
79}
80
81type QueryRenderFormat = StructuredOutputFormat;
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
84#[serde(rename_all = "lowercase")]
85enum SearchSource {
86  Project,
87  Core,
88  Deps,
89  All,
90}
91
92impl SearchSource {
93  fn parse(raw: &str) -> Result<Self, String> {
94    match raw {
95      "project" => Ok(Self::Project),
96      "core" => Ok(Self::Core),
97      "deps" => Ok(Self::Deps),
98      "all" => Ok(Self::All),
99      other => Err(format!(
100        "Unknown query search source `{other}`. Expected `project`, `core`, `deps`, or `all`."
101      )),
102    }
103  }
104
105  fn as_str(self) -> &'static str {
106    match self {
107      Self::Project => "project",
108      Self::Core => "core",
109      Self::Deps => "deps",
110      Self::All => "all",
111    }
112  }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116struct SearchOrigin {
117  package: String,
118  module: Option<String>,
119}
120
121#[derive(Debug)]
122struct SearchCatalog {
123  snapshot: snapshot::Snapshot,
124  sources: BTreeMap<String, (SearchSource, SearchOrigin)>,
125}
126
127fn parse_query_render_format(raw: &str) -> Result<QueryRenderFormat, String> {
128  StructuredOutputFormat::parse(raw, "query output")
129}
130
131fn emit_query_structured<T: Serialize>(value: &T, format: QueryRenderFormat, context: &str) -> Result<(), String> {
132  let rendered = match format {
133    QueryRenderFormat::Edn => {
134      let json = serde_json::to_value(value).map_err(|error| format!("Failed to encode {context}: {error}"))?;
135      format_json_value_as_edn(&json)?
136    }
137    QueryRenderFormat::Json => serde_json::to_string_pretty(value).map_err(|error| format!("Failed to encode {context}: {error}"))?,
138    QueryRenderFormat::Human => return Err(format!("Cannot emit human {context} as structured output")),
139  };
140  println!("{rendered}");
141  Ok(())
142}
143
144fn semantic_revision(parts: &[&str]) -> String {
145  let mut hasher = Md5::new();
146  for part in parts {
147    hasher.update((part.len() as u64).to_le_bytes());
148    hasher.update(part.as_bytes());
149  }
150  format!("md5:{}", hex::encode(hasher.finalize()))
151}
152
153#[derive(Debug, Serialize)]
154struct SemanticQueryEnvelope<T> {
155  schema_version: u32,
156  command: &'static str,
157  revision: String,
158  data: T,
159  diagnostics: Vec<ContextDiagnostic>,
160  next: Vec<String>,
161}
162
163#[derive(Debug, Clone, Serialize)]
164struct ContextCallTypes {
165  parameters: Vec<serde_json::Value>,
166  rest: Option<serde_json::Value>,
167  returns: serde_json::Value,
168}
169
170#[derive(Debug, Clone, Serialize)]
171struct ContextMethod {
172  name: String,
173  origin: String,
174  status: &'static str,
175  parameter_types: Option<Vec<String>>,
176  rest_type: Option<String>,
177  return_type: Option<String>,
178  #[serde(skip_serializing_if = "Option::is_none")]
179  call_types: Option<ContextCallTypes>,
180  generics: Vec<String>,
181  bounds: Vec<String>,
182  features: Vec<String>,
183  definition: Option<String>,
184  detail: Option<String>,
185}
186
187fn context_method(
188  descriptor: runner::preprocess::StaticMethodDescriptor,
189  contract: runner::preprocess::StaticMethodContract,
190) -> ContextMethod {
191  let call_types = method_call_types(&contract);
192  ContextMethod {
193    name: descriptor.name,
194    origin: descriptor.origin,
195    status: contract.status,
196    parameter_types: contract
197      .arg_types
198      .map(|args| args.iter().map(|annotation| annotation.describe()).collect()),
199    rest_type: contract.rest_type.map(|annotation| annotation.describe()),
200    return_type: contract.return_type.map(|annotation| annotation.describe()),
201    call_types,
202    generics: contract
203      .generics
204      .into_iter()
205      .map(|name| match CalcitTypeAnnotation::TypeVar(Arc::from(name)).to_type_edn() {
206        cirru_edn::Edn::Symbol(source) => source.to_string(),
207        _ => unreachable!("a type variable projects to its source symbol"),
208      })
209      .collect(),
210    bounds: contract.bounds,
211    features: contract.features,
212    definition: contract.definition,
213    detail: contract.detail,
214  }
215}
216
217/// Export the already resolved contract as syntax nodes, not display strings.
218fn method_call_types(contract: &runner::preprocess::StaticMethodContract) -> Option<ContextCallTypes> {
219  if contract.status != "proven" {
220    return None;
221  }
222  let node = |annotation: &CalcitTypeAnnotation| {
223    canonical_schema_cirru(annotation, true)
224      .ok()
225      .flatten()
226      .map(|cirru| cirru_to_json(&cirru))
227  };
228  Some(ContextCallTypes {
229    parameters: contract
230      .arg_types
231      .as_ref()?
232      .iter()
233      .map(|annotation| node(annotation))
234      .collect::<Option<Vec<_>>>()?,
235    rest: match contract.rest_type.as_ref() {
236      Some(annotation) => Some(node(annotation)?),
237      None => None,
238    },
239    returns: node(contract.return_type.as_ref()?)?,
240  })
241}
242
243fn method_contract_fingerprint(methods: &Option<Vec<ContextMethod>>) -> Result<String, String> {
244  serde_json::to_string(methods).map_err(|error| format!("Failed to encode method contracts for revision: {error}"))
245}
246
247fn render_context_method(method: &ContextMethod) -> String {
248  let mut rendered = format!("- `{}` (`{}`): {}", method.name, method.origin, method.status);
249  if !method.generics.is_empty() {
250    let generics = method.generics.iter().map(|name| format!("'{name}")).collect::<Vec<_>>();
251    rendered.push_str(&format!(" for<{}>", generics.join(", ")));
252  }
253  if let (Some(args), Some(result)) = (&method.parameter_types, &method.return_type) {
254    let mut parameters = args.clone();
255    if let Some(rest) = &method.rest_type {
256      parameters.push(format!("...{rest}"));
257    }
258    rendered.push_str(&format!(" `({}) -> {result}`", parameters.join(", ")));
259  }
260  if !method.bounds.is_empty() {
261    rendered.push_str(&format!("; where {}", method.bounds.join(", ")));
262  }
263  if !method.features.is_empty() {
264    rendered.push_str(&format!("; features {}", method.features.join(", ")));
265  }
266  if let Some(definition) = &method.definition {
267    rendered.push_str(&format!("; `calcit query context '{definition}'`"));
268  }
269  if let Some(detail) = &method.detail {
270    rendered.push_str(&format!("; {detail}"));
271  }
272  rendered
273}
274
275fn render_type_query_methods(methods: &[ContextMethod]) -> String {
276  let mut out = String::new();
277  let _ = writeln!(&mut out, "Count: {}\n", methods.len());
278  for method in methods {
279    let _ = writeln!(&mut out, "{}", render_context_method(method));
280  }
281  out
282}
283
284#[derive(Debug, Serialize)]
285struct TypeQueryData {
286  target: String,
287  canonical_type: String,
288  resolved_from: &'static str,
289  methods: Option<Vec<ContextMethod>>,
290}
291
292#[derive(Debug, Clone, Serialize)]
293struct TypeAtEvidence {
294  kind: String,
295  detail: String,
296  path: Option<String>,
297}
298
299#[derive(Debug, Clone, Serialize)]
300struct TypeAtBinding {
301  name: String,
302  r#type: String,
303  path: Option<String>,
304}
305
306#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
307struct TypeAtLowering {
308  status: &'static str,
309  kind: &'static str,
310  source_head: Option<String>,
311  lowered_head: Option<String>,
312  detail: String,
313}
314
315#[derive(Debug, Serialize)]
316struct TypeAtData {
317  id: String,
318  path: String,
319  expression: String,
320  tree: serde_json::Value,
321  inferred_type: Option<String>,
322  expected_type: Option<String>,
323  expected_from: Option<String>,
324  confidence: &'static str,
325  dynamic_intent: Option<&'static str>,
326  evidence: Vec<TypeAtEvidence>,
327  bindings: Vec<TypeAtBinding>,
328  bindings_complete: bool,
329  static_methods: Option<Vec<ContextMethod>>,
330  lowering: TypeAtLowering,
331}
332
333#[derive(Debug, Clone, Serialize)]
334struct ContextCollection<T> {
335  total: usize,
336  returned: usize,
337  truncated: bool,
338  items: Vec<T>,
339}
340
341impl<T> ContextCollection<T> {
342  fn new(total: usize, items: Vec<T>) -> Self {
343    let returned = items.len();
344    Self {
345      total,
346      returned,
347      truncated: returned < total,
348      items,
349    }
350  }
351}
352
353#[derive(Debug, Clone, Serialize)]
354struct ContextCode {
355  root: &'static str,
356  nodes: usize,
357  cirru: String,
358  tree: Option<serde_json::Value>,
359  truncated: bool,
360}
361
362#[derive(Debug, Clone, Serialize)]
363struct ContextExample {
364  index: usize,
365  cirru: String,
366  tree: Option<serde_json::Value>,
367  truncated: bool,
368}
369
370#[derive(Debug, Clone, Serialize)]
371struct ContextTest {
372  name: String,
373  tags: Vec<String>,
374  cirru: String,
375  tree: Option<serde_json::Value>,
376  truncated: bool,
377}
378
379#[derive(Debug, Clone, Serialize)]
380struct ContextDependency {
381  id: String,
382  source: String,
383}
384
385#[derive(Debug, Clone, Serialize)]
386struct ContextUsage {
387  id: String,
388  source: String,
389  area: String,
390  paths: Vec<String>,
391}
392
393#[derive(Debug, Clone, Serialize)]
394struct ContextDocLink {
395  id: String,
396  path: String,
397  title: Option<String>,
398  summary: Option<String>,
399}
400
401#[derive(Debug, Clone, Serialize)]
402struct ContextDiagnostic {
403  code: String,
404  phase: &'static str,
405  severity: &'static str,
406  message: String,
407  path: Option<String>,
408  intent: Option<String>,
409  provenance: Vec<calcit_core::calcit::CalcitErrProvenance>,
410}
411
412#[derive(Debug, Serialize)]
413struct DefinitionContextData {
414  id: String,
415  uri: String,
416  source: String,
417  kind: String,
418  layer: &'static str,
419  coverage: String,
420  doc: Option<String>,
421  doc_truncated: bool,
422  tags: Vec<String>,
423  schema: Option<String>,
424  #[serde(skip_serializing_if = "Option::is_none")]
425  inferred_schema: Option<String>,
426  #[serde(skip_serializing_if = "Option::is_none")]
427  runtime_arity: Option<RuntimeCallArity>,
428  #[serde(skip_serializing_if = "Option::is_none")]
429  failure: Option<ProcFailureInfo>,
430  features: Vec<String>,
431  js_ffi: Option<JsFfiQueryInfo>,
432  code: ContextCode,
433  examples: ContextCollection<ContextExample>,
434  tests: ContextCollection<ContextTest>,
435  dependencies: ContextCollection<ContextDependency>,
436  usages: ContextCollection<ContextUsage>,
437  docs: ContextCollection<ContextDocLink>,
438  static_methods: Option<ContextCollection<ContextMethod>>,
439}
440
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
442struct RuntimeCallArity {
443  min: usize,
444  max: Option<usize>,
445}
446
447/// Expose authoritative Proc omission metadata without inventing nullable value types
448/// or inferring a wrapper's callable contract from its name or declared schema.
449fn core_runtime_call_arity(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<RuntimeCallArity> {
450  let arity = core_runtime_proc(namespace, definition, entry)?.arity()?;
451  Some(RuntimeCallArity {
452    min: arity.min,
453    max: arity.max,
454  })
455}
456
457/// The builtin Proc a core definition runs, either directly or as a one-leaf alias.
458fn core_runtime_proc(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<CalcitProc> {
459  if namespace != calcit_core::calcit::CORE_NS {
460    return None;
461  }
462  let proc_name = if crate::public_api_check::is_core_runtime_intrinsic(namespace, definition, entry) {
463    definition
464  } else if let Cirru::Leaf(value) = &entry.code {
465    value.as_ref()
466  } else {
467    return None;
468  };
469  proc_name.parse::<CalcitProc>().ok()
470}
471
472#[derive(Debug, Clone, Serialize)]
473struct ProcFailureInfo {
474  class: &'static str,
475  #[serde(skip_serializing_if = "Option::is_none")]
476  condition: Option<&'static str>,
477}
478
479/// Failure class of the builtin Proc behind a core definition (#1558).
480fn core_proc_failure(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<ProcFailureInfo> {
481  let failure = core_runtime_proc(namespace, definition, entry)?.failure();
482  Some(ProcFailureInfo {
483    class: failure.class_name(),
484    condition: failure.condition(),
485  })
486}
487
488fn render_proc_failure(failure: &ProcFailureInfo) -> String {
489  match failure.condition {
490    Some(condition) => format!("`{}` when {condition}", failure.class),
491    None => format!("`{}`", failure.class),
492  }
493}
494
495fn render_runtime_call_arity(arity: RuntimeCallArity) -> String {
496  match arity.max {
497    Some(max) if max == arity.min => format!("{}", arity.min),
498    Some(max) => format!("{}..={max}", arity.min),
499    None => format!("{}..", arity.min),
500  }
501}
502
503#[derive(Debug, Clone, Serialize)]
504struct JsFfiQueryInfo {
505  target: Option<String>,
506  owner_module: Option<String>,
507  owner_version: Option<String>,
508  module_root: Option<String>,
509  source_kind: Option<&'static str>,
510  source_file: Option<String>,
511  modules: BTreeMap<String, String>,
512  metadata_error: Option<String>,
513}
514
515fn special_builtin_dynamic_fn(arg_types: Vec<Arc<CalcitTypeAnnotation>>) -> Arc<CalcitTypeAnnotation> {
516  Arc::new(CalcitTypeAnnotation::from_function_parts(arg_types, DYNAMIC_TYPE.clone()))
517}
518
519fn parse_special_builtin_examples(snippets: &[&str]) -> Result<Vec<Cirru>, String> {
520  let mut examples = Vec::with_capacity(snippets.len());
521  for snippet in snippets {
522    let parsed = cirru_parser::parse(snippet).map_err(|e| format!("Failed to parse builtin example `{snippet}`: {e}"))?;
523    let Some(example) = parsed.into_iter().next() else {
524      return Err(format!("Builtin example is empty: {snippet}"));
525    };
526    examples.push(example);
527  }
528  Ok(examples)
529}
530
531fn lookup_special_builtin_query_meta(namespace: &str, definition: &str) -> Result<Option<SpecialBuiltinQueryMeta>, String> {
532  if namespace != calcit_core::calcit::CORE_NS {
533    return Ok(None);
534  }
535
536  let meta = match definition {
537    "to-calcit-data" => Some(SpecialBuiltinQueryMeta {
538      doc: "convert JS values recursively; optional second Bool noKeyword defaults to false (keyword text becomes Tag); true preserves String values and object keys; existing Calcit containers are unchanged",
539      schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone(), Arc::new(CalcitTypeAnnotation::Bool)]),
540      runtime_arity: Some(RuntimeCallArity { min: 1, max: Some(2) }),
541      examples: parse_special_builtin_examples(&[
542        "to-calcit-data $ js-array 1 ([] 2 3) (:: :quote $ [] 'a 'b)",
543        "to-calcit-data $ &js-object |a 1 |:b 2 :c ([] 3 4)",
544        "assert= ([] |:keyword) $ to-calcit-data (js-array |:keyword) true",
545        "assert= ([] :keyword) $ to-calcit-data (js-array |:keyword) false",
546        "assert= ([] :keyword) $ to-calcit-data $ js-array |:keyword",
547      ])?,
548      expr_preview: "builtin proc to-calcit-data (JS interop helper)",
549      cirru_note: "(builtin proc; runtime helper without snapshot source)",
550      semantic_tags: &["js-ffi"],
551    }),
552    "to-js-data" => Some(SpecialBuiltinQueryMeta {
553      doc: "convert Calcit data into JS-compatible data recursively; JS FFI keeps value and options dynamically typed",
554      schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone(), DYNAMIC_TYPE.clone()]),
555      runtime_arity: None,
556      examples: parse_special_builtin_examples(&[
557        "to-js-data $ [] 1 2 3",
558        "to-js-data $ &{} |a 1 :b ([] 2 3)",
559        "to-js-data ([] 1 2 3) $ {} (:js-array true)",
560      ])?,
561      expr_preview: "builtin proc to-js-data (JS interop helper)",
562      cirru_note: "(builtin proc; runtime helper without snapshot source)",
563      semantic_tags: &["js-ffi"],
564    }),
565    "to-cirru-edn" => Some(SpecialBuiltinQueryMeta {
566      doc: "convert Calcit data into Cirru EDN data",
567      schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone()]),
568      runtime_arity: None,
569      examples: vec![],
570      expr_preview: "builtin proc to-cirru-edn (data conversion helper)",
571      cirru_note: "(builtin proc; runtime helper without snapshot source)",
572      semantic_tags: &[],
573    }),
574    "extract-cirru-edn" => Some(SpecialBuiltinQueryMeta {
575      doc: "extract Cirru EDN data into regular Calcit values when possible",
576      schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone()]),
577      runtime_arity: None,
578      examples: vec![],
579      expr_preview: "builtin proc extract-cirru-edn (data conversion helper)",
580      cirru_note: "(builtin proc; runtime helper without snapshot source)",
581      semantic_tags: &[],
582    }),
583    "js-array" => Some(SpecialBuiltinQueryMeta {
584      doc: "build a JS array value in JS interop contexts",
585      schema: runner::preprocess::special_js_intrinsic_signature("js-array").expect("js-array intrinsic signature"),
586      runtime_arity: None,
587      examples: vec![],
588      expr_preview: "builtin proc js-array (JS interop helper)",
589      cirru_note: "(builtin proc; runtime helper without snapshot source)",
590      semantic_tags: &["js-ffi"],
591    }),
592    "&js-object" => Some(SpecialBuiltinQueryMeta {
593      doc: "build a plain JS object value in JS interop contexts",
594      schema: runner::preprocess::special_js_intrinsic_signature("&js-object").expect("&js-object intrinsic signature"),
595      runtime_arity: None,
596      examples: vec![],
597      expr_preview: "builtin proc &js-object (JS interop helper)",
598      cirru_note: "(builtin proc; runtime helper without snapshot source)",
599      semantic_tags: &["js-ffi"],
600    }),
601    _ => None,
602  };
603
604  Ok(meta)
605}
606
607fn query_schema_cirru(annotation: &CalcitTypeAnnotation, wrapped: bool) -> Result<Option<Cirru>, String> {
608  // Show the compact spelling stored in `:schema`; shapes without one keep the canonical EDN.
609  // Unwrapped callers (JSON data, reference coordinates) stay on the canonical shape.
610  if wrapped
611    && !matches!(annotation, CalcitTypeAnnotation::Dynamic)
612    && let Some(compact) = snapshot::compact_type_display(&query_schema_edn(annotation, wrapped))
613  {
614    return Ok(Some(compact));
615  }
616  canonical_schema_cirru(annotation, wrapped)
617}
618
619/// Schema stored on a project definition. An omitted schema shares the
620/// Dynamic singleton and has no display; a written `Dynamic` is a reviewed
621/// open contract and is shown as such.
622fn definition_schema_cirru(schema: &Arc<CalcitTypeAnnotation>, wrapped: bool) -> Result<Option<Cirru>, String> {
623  match schema.as_ref() {
624    CalcitTypeAnnotation::Dynamic if !snapshot::schema_annotation_is_missing(schema) => Ok(Some(Cirru::Leaf("Dynamic".into()))),
625    annotation => query_schema_cirru(annotation, wrapped),
626  }
627}
628
629fn query_schema_edn(annotation: &CalcitTypeAnnotation, wrapped: bool) -> cirru_edn::Edn {
630  match annotation {
631    CalcitTypeAnnotation::Fn(fn_annot) if wrapped => fn_annot.to_wrapped_schema_edn(),
632    CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.to_schema_edn(),
633    CalcitTypeAnnotation::Macro(signature) => signature.to_wrapped_schema_edn(),
634    other => other.to_type_edn(),
635  }
636}
637
638/// Canonical `:: 'Fn $ {} …` syntax, for machine-readable exports.
639fn canonical_schema_cirru(annotation: &CalcitTypeAnnotation, wrapped: bool) -> Result<Option<Cirru>, String> {
640  if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
641    return Ok(None);
642  }
643  let schema_edn = query_schema_edn(annotation, wrapped);
644  snapshot::schema_edn_to_cirru(&schema_edn).map(|cirru| {
645    let normalized = match cirru {
646      Cirru::List(items) if items.len() == 2 && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "do") => {
647        items[1].clone()
648      }
649      other => other,
650    };
651    Some(normalized)
652  })
653}
654
655fn normalize_single_schema_display(text: String) -> String {
656  let trimmed = text.trim();
657  trimmed.strip_prefix("do ").unwrap_or(trimmed).to_owned()
658}
659
660fn format_query_schema_oneline(cirru: &Cirru) -> Result<String, String> {
661  match cirru {
662    Cirru::Leaf(value) => Ok(value.to_string()),
663    Cirru::List(_) => cirru.format_one_liner().map(normalize_single_schema_display),
664  }
665}
666
667fn format_query_schema(annotation: &CalcitTypeAnnotation, wrapped: bool) -> String {
668  format_schema_display(query_schema_cirru(annotation, wrapped))
669}
670
671fn format_schema_display(schema: Result<Option<Cirru>, String>) -> String {
672  match schema {
673    Ok(Some(Cirru::Leaf(value))) => value.to_string(),
674    Ok(Some(cirru @ Cirru::List(_))) => cirru_parser::format(std::slice::from_ref(&cirru), true.into())
675      .map(normalize_single_schema_display)
676      .unwrap_or_else(|_| "(failed to format)".to_string()),
677    Ok(None) => "(none)".to_string(),
678    Err(error) => format!("(schema error: {error})"),
679  }
680}
681
682fn format_schema_query_json(
683  id: &str,
684  source: &str,
685  annotation: &CalcitTypeAnnotation,
686  revision: String,
687  runtime_arity: Option<RuntimeCallArity>,
688) -> Result<String, String> {
689  format_schema_cirru_query_json(id, source, query_schema_cirru(annotation, true)?, revision, runtime_arity)
690}
691
692/// Built-in checker rule lines for a calcit.core signature marked
693/// `(:open :intrinsic)` (#2649); `None` for every other definition.
694fn intrinsic_checker_rules(namespace: &str, definition: &str, schema: &CalcitTypeAnnotation) -> Option<&'static [&'static str]> {
695  if namespace != calcit_core::calcit::CORE_NS {
696    return None;
697  }
698  match schema {
699    CalcitTypeAnnotation::Fn(signature) if signature.open_reason.0 == Some(calcit_core::calcit::FnOpenReason::Intrinsic) => {
700      calcit_core::runner::preprocess::intrinsic_rule_summary(definition)
701    }
702    _ => None,
703  }
704}
705
706fn write_intrinsic_checker_rules(out: &mut String, rules: &[&str]) {
707  let _ = writeln!(
708    out,
709    "\n## Checker rules\n\nThe schema keeps the open shape the runtime accepts; the checker decides the types per receiver:\n"
710  );
711  for rule in rules {
712    let _ = writeln!(out, "- `{rule}`");
713  }
714}
715
716fn schema_cases_lines(schema: &CalcitTypeAnnotation) -> Result<Option<Vec<String>>, String> {
717  let CalcitTypeAnnotation::Fn(signature) = schema else {
718    return Ok(None);
719  };
720  if signature.cases.is_empty() {
721    return Ok(None);
722  }
723  let mut lines = Vec::with_capacity(signature.cases.len());
724  for case in signature.cases.iter() {
725    let case_annotation = CalcitTypeAnnotation::Fn(case.clone());
726    if let Some(cirru) = query_schema_cirru(&case_annotation, true)? {
727      lines.push(format_query_schema_oneline(&cirru)?);
728    }
729  }
730  Ok((!lines.is_empty()).then_some(lines))
731}
732
733fn write_schema_cases(out: &mut String, cases: &[String]) {
734  let _ = writeln!(out, "\n## Cases\n");
735  for case in cases {
736    let _ = writeln!(out, "- `{case}`");
737  }
738}
739
740fn format_schema_cirru_query_json(
741  id: &str,
742  source: &str,
743  schema: Option<Cirru>,
744  revision: String,
745  runtime_arity: Option<RuntimeCallArity>,
746) -> Result<String, String> {
747  let canonical_schema = schema.as_ref().map(format_query_schema_oneline).transpose()?;
748  let tree = schema.as_ref().map(cirru_to_json_value);
749  let mut envelope = serde_json::json!({
750    "schema_version": 1,
751    "command": "query.schema",
752    "revision": revision,
753    "data": {
754      "id": id,
755      "source": source,
756      "canonical_schema": canonical_schema,
757      "tree": tree,
758    },
759    "diagnostics": [],
760  });
761  if let Some(arity) = runtime_arity {
762    envelope["data"]["runtime_arity"] =
763      serde_json::to_value(arity).map_err(|error| format!("Failed to encode runtime arity: {error}"))?;
764  }
765  serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode schema query JSON: {error}"))
766}
767
768fn detailed_window(detail_offset: usize, total: usize) -> (usize, usize) {
769  if total == 0 {
770    return (0, 0);
771  }
772  let start = detail_offset.min(total.saturating_sub(1));
773  let end = (start + DETAILED_RESULTS_WINDOW).min(total);
774  (start, end)
775}
776
777fn print_detail_window_hint(total: usize, detail_offset: usize, subject: &str) {
778  if total > DETAILED_RESULTS_WINDOW {
779    let (start, end) = detailed_window(detail_offset, total);
780    println!("Detail window for {subject}: [{start}, {end}) (detail-offset={detail_offset}); other entries are compressed.");
781  }
782}
783
784fn in_detail_window(index: usize, total: usize, detail_offset: usize) -> bool {
785  if total <= DETAILED_RESULTS_WINDOW {
786    return true;
787  }
788  let (start, end) = detailed_window(detail_offset, total);
789  index >= start && index < end
790}
791
792fn preview_node_oneline(node: &Cirru, max_len: usize) -> (String, bool) {
793  let text = match node {
794    Cirru::Leaf(s) => s.to_string(),
795    _ => node.format_one_liner().unwrap_or_default(),
796  };
797  if text.is_empty() {
798    return ("(matched)".to_string(), false);
799  }
800  match char_prefix_if_truncated(&text, max_len) {
801    Some(prefix) => (prefix.to_owned(), true),
802    None => (text, false),
803  }
804}
805
806fn is_token_delimiter(ch: Option<char>) -> bool {
807  ch.is_none_or(|c| c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '$' | ','))
808}
809
810fn highlight_target_text(text: &str, target: Option<&str>, loose: bool) -> String {
811  let Some(target) = target else {
812    return text.to_string();
813  };
814  if target.is_empty() || !text.contains(target) {
815    return text.to_string();
816  }
817
818  if loose {
819    return text.replace(target, &format!("{}", target.bright_yellow().bold()));
820  }
821
822  let mut highlighted = String::with_capacity(text.len());
823  let mut last_index = 0;
824
825  for (idx, _) in text.match_indices(target) {
826    let prev_char = text[..idx].chars().next_back();
827    let next_char = text[idx + target.len()..].chars().next();
828    if is_token_delimiter(prev_char) && is_token_delimiter(next_char) {
829      highlighted.push_str(&text[last_index..idx]);
830      highlighted.push_str(&format!("{}", target.bright_yellow().bold()));
831      last_index = idx + target.len();
832    }
833  }
834
835  if last_index == 0 {
836    text.to_string()
837  } else {
838    highlighted.push_str(&text[last_index..]);
839    highlighted
840  }
841}
842
843fn path_parent(path: &[usize]) -> Option<Vec<usize>> {
844  if path.is_empty() {
845    None
846  } else {
847    Some(path[..path.len() - 1].to_vec())
848  }
849}
850
851fn get_node_at_path(code: &Cirru, path: &[usize]) -> Option<Cirru> {
852  if path.is_empty() {
853    return Some(code.clone());
854  }
855  let mut current = code;
856  for &idx in path {
857    match current {
858      Cirru::List(items) => current = items.get(idx)?,
859      Cirru::Leaf(_) => return None,
860    }
861  }
862  Some(current.clone())
863}
864
865fn count_nodes_limited(node: &Cirru, limit: usize) -> usize {
866  fn walk(node: &Cirru, acc: &mut usize, limit: usize) {
867    if *acc >= limit {
868      return;
869    }
870    *acc += 1;
871    if let Cirru::List(items) = node {
872      for item in items {
873        if *acc >= limit {
874          break;
875        }
876        walk(item, acc, limit);
877      }
878    }
879  }
880  let mut acc = 0;
881  walk(node, &mut acc, limit);
882  acc
883}
884
885fn can_show_parent_preview(expr_path: &[usize], parent_node: &Cirru) -> bool {
886  if expr_path.len() > 8 {
887    return false;
888  }
889  if let Cirru::List(items) = parent_node
890    && items.len() > 8
891  {
892    return false;
893  }
894  count_nodes_limited(parent_node, 40) < 40
895}
896
897fn expression_and_parent_preview(
898  code: &Cirru,
899  match_path: &[usize],
900  matched_node: &Cirru,
901  highlight_target: Option<&str>,
902  loose: bool,
903) -> ((String, bool), Vec<(String, bool)>) {
904  let expr_path = if matches!(matched_node, Cirru::Leaf(_)) {
905    path_parent(match_path).unwrap_or_else(|| match_path.to_vec())
906  } else {
907    match_path.to_vec()
908  };
909
910  let expr_node = get_node_at_path(code, &expr_path).unwrap_or_else(|| matched_node.clone());
911  let (expr_text, expr_truncated) = preview_node_oneline(&expr_node, 110);
912  let expr_preview = (highlight_target_text(&expr_text, highlight_target, loose), expr_truncated);
913
914  let mut parent_previews: Vec<(String, bool)> = Vec::new();
915  let mut current_path = expr_path;
916
917  for _ in 0..2 {
918    let Some(parent_path) = path_parent(&current_path) else {
919      break;
920    };
921    let Some(parent_node) = get_node_at_path(code, &parent_path) else {
922      break;
923    };
924
925    if can_show_parent_preview(&parent_path, &parent_node) {
926      let (preview_text, preview_truncated) = preview_node_oneline(&parent_node, 110);
927      parent_previews.push((highlight_target_text(&preview_text, highlight_target, loose), preview_truncated));
928    }
929
930    current_path = parent_path;
931  }
932
933  (expr_preview, parent_previews)
934}
935
936/// Parse "namespace/definition" format into (namespace, definition)
937/// Splits at the FIRST '/' so operator definitions like '/' and '/=' are handled correctly.
938fn parse_target(target: &str) -> Result<(&str, &str), String> {
939  target
940    .split_once('/')
941    .ok_or_else(|| format!("Invalid target format: '{target}'. Expected 'namespace/definition' (e.g. 'app.core/main')"))
942}
943
944fn resolve_search_cursor_references(
945  input_path: &str,
946  filter: &mut Option<String>,
947  start_path: &mut Option<String>,
948) -> Result<(), String> {
949  if filter.as_deref() == Some("@cursor") || start_path.as_deref() == Some("@cursor") {
950    let (cursor_target, cursor_path) = resolve_active_cursor_reference(input_path)?;
951    if let Some(filter_target) = filter.as_deref()
952      && filter_target != "@cursor"
953      && filter_target != cursor_target
954    {
955      return Err(format!(
956        "Cursor-scoped search targets '{cursor_target}', but --filter targets '{filter_target}'. Omit --filter or use --filter @cursor."
957      ));
958    }
959    *filter = Some(cursor_target);
960    if start_path.as_deref() == Some("@cursor") {
961      *start_path = Some(cursor_path);
962    }
963  }
964  Ok(())
965}
966
967fn resolve_query_cursor_references(cmd: &mut QueryCommand, input_path: &str) -> Result<(), String> {
968  match &mut cmd.subcommand {
969    QuerySubcommand::Def(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
970    QuerySubcommand::Usages(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
971    QuerySubcommand::Search(opts) => {
972      resolve_search_cursor_references(input_path, &mut opts.filter, &mut opts.start_path)?;
973    }
974    QuerySubcommand::SearchExpr(opts) => {
975      resolve_search_cursor_references(input_path, &mut opts.filter, &mut opts.start_path)?;
976    }
977    QuerySubcommand::Schema(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
978    QuerySubcommand::Type(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
979    QuerySubcommand::TypeAt(opts) => {
980      if opts.target == "@cursor" && opts.path == "@cursor" {
981        (opts.target, opts.path) = resolve_active_cursor_reference(input_path)?;
982      } else {
983        opts.target = resolve_cursor_target_argument(input_path, &opts.target)?;
984        opts.path = resolve_cursor_path_argument(input_path, &opts.target, &opts.path)?;
985      }
986    }
987    QuerySubcommand::Context(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
988    QuerySubcommand::Ns(_)
989    | QuerySubcommand::Defs(_)
990    | QuerySubcommand::Config(_)
991    | QuerySubcommand::Error(_)
992    | QuerySubcommand::Find(_) => {}
993  }
994  Ok(())
995}
996
997fn structured_query_request(cmd: &QueryCommand) -> Option<(QueryRenderFormat, &'static str, &str)> {
998  let (raw_format, command, target) = match &cmd.subcommand {
999    QuerySubcommand::Type(opts) => (opts.format.as_str(), "query.type", opts.target.as_str()),
1000    QuerySubcommand::TypeAt(opts) => (opts.format.as_str(), "query.type-at", opts.target.as_str()),
1001    QuerySubcommand::Context(opts) => (opts.format.as_str(), "query.context", opts.target.as_str()),
1002    QuerySubcommand::Def(opts) => (opts.format.as_str(), "query.def", opts.target.as_str()),
1003    QuerySubcommand::Defs(opts) => (opts.format.as_str(), "query.defs", opts.namespace.as_str()),
1004    QuerySubcommand::Search(opts) => (opts.format.as_str(), "query.search", opts.pattern.as_str()),
1005    QuerySubcommand::SearchExpr(opts) => (opts.format.as_str(), "query.search-expr", opts.pattern.as_str()),
1006    _ => return None,
1007  };
1008  match parse_query_render_format(raw_format).ok()? {
1009    QueryRenderFormat::Human => None,
1010    format => Some((format, command, target)),
1011  }
1012}
1013
1014fn query_failure_code(command: &str, error: &str) -> &'static str {
1015  let legacy_tag = format!("[{}]", snapshot::LEGACY_TYPE_SYNTAX_CODE);
1016  if error.starts_with(&legacy_tag) || (error.starts_with("Failed to load Snapshot ") && error.contains(&legacy_tag)) {
1017    snapshot::LEGACY_TYPE_SYNTAX_CODE
1018  } else if command == "query.type" && (error.starts_with("Unknown builtin type") || error.contains("Failed to parse type")) {
1019    "E_QUERY_INVALID_TYPE"
1020  } else if error.starts_with("Path index") || error.starts_with("Invalid path") || error.starts_with("Invalid start path") {
1021    "E_QUERY_INVALID_PATH"
1022  } else if error.contains("not found") || error.contains("does not exist") {
1023    "E_QUERY_TARGET_NOT_FOUND"
1024  } else if error.contains("preprocess") || error.contains("compile") {
1025    "E_QUERY_PREPROCESS"
1026  } else {
1027    "E_QUERY_FAILED"
1028  }
1029}
1030
1031fn query_failure_envelope(command: &str, target: &str, error: &str) -> serde_json::Value {
1032  serde_json::json!({
1033    "schema_version": if command == "query.type-at" { TYPE_AT_SCHEMA_VERSION } else { 1 },
1034    "command": command,
1035    "revision": null,
1036    "data": null,
1037    "diagnostics": [{
1038      "code": query_failure_code(command, error),
1039      "phase": "query",
1040      "severity": "error",
1041      "message": error,
1042      "path": null,
1043      "intent": null,
1044      "provenance": [],
1045      "target": target,
1046    }],
1047    "next": [],
1048  })
1049}
1050
1051pub fn handle_query_command(cmd: &QueryCommand, input_path: &str, entry: Option<&str>) -> Result<(), String> {
1052  let result = handle_query_command_inner(cmd, input_path, entry);
1053  if let Err(error) = &result
1054    && let Some((format, command, target)) = structured_query_request(cmd)
1055  {
1056    let envelope = query_failure_envelope(command, target, error);
1057    emit_query_structured(&envelope, format, "query failure")?;
1058  }
1059  result
1060}
1061
1062/// Reject an unknown global `--entry` before any view runs, so views that only
1063/// read the project Snapshot (or never load dependencies) do not silently ignore it.
1064fn validate_query_entry(input_path: &str, entry: Option<&str>) -> Result<(), String> {
1065  if entry.is_none() {
1066    return Ok(());
1067  }
1068  load_main_snapshot(input_path)?.select_entry(entry)
1069}
1070
1071fn handle_query_command_inner(cmd: &QueryCommand, input_path: &str, entry: Option<&str>) -> Result<(), String> {
1072  let mut resolved = cmd.clone();
1073  resolve_query_cursor_references(&mut resolved, input_path)?;
1074  validate_query_entry(input_path, entry)?;
1075  match &resolved.subcommand {
1076    QuerySubcommand::Ns(opts) => match (opts.format.as_str(), opts.namespace.as_deref()) {
1077      ("cirru", Some(namespace)) => handle_ns_cirru_view(input_path, namespace, entry),
1078      ("cirru", None) => Err("`query ns --format cirru` needs a namespace: `query ns <namespace> --format cirru`".to_owned()),
1079      (raw, namespace) => {
1080        let format = StructuredOutputFormat::parse(raw, "query ns")
1081          .map_err(|_| format!("Unsupported query ns format '{raw}'. Expected human, edn, json, or cirru."))?;
1082        handle_ns(input_path, namespace, opts.deps, format, entry)
1083      }
1084    },
1085    QuerySubcommand::Defs(opts) => handle_defs(input_path, opts, entry),
1086    QuerySubcommand::Config(opts) => handle_config(input_path, opts),
1087    QuerySubcommand::Error(_) => handle_error(input_path),
1088    QuerySubcommand::Def(opts) => {
1089      let (ns, def) = parse_target(&opts.target)?;
1090      handle_def(input_path, ns, def, opts, entry)
1091    }
1092    QuerySubcommand::Find(opts) => {
1093      if opts.exact {
1094        handle_find(input_path, &opts.symbol, opts.deps, opts.detail_offset, entry)
1095      } else {
1096        handle_fuzzy_search(input_path, &opts.symbol, opts.deps, opts.limit, opts.detail_offset, entry)
1097      }
1098    }
1099    QuerySubcommand::Usages(opts) => {
1100      let (ns, def) = parse_target(&opts.target)?;
1101      handle_usages(input_path, ns, def, opts.deps, opts.detail_offset, entry)
1102    }
1103    QuerySubcommand::Search(opts) => {
1104      let common_opts = SearchCommonOpts {
1105        filter: opts.filter.as_deref(),
1106        loose: !opts.exact,
1107        regex: opts.regex,
1108        max_depth: opts.max_depth,
1109        entry: opts.entry.as_deref().or(entry),
1110        source: SearchSource::parse(&opts.source)?,
1111        detail_offset: opts.detail_offset,
1112        parent_path: opts.parent_path,
1113        format: parse_query_render_format(&opts.format)?,
1114        set_cursor: opts.set_cursor,
1115        compact_output: false,
1116      };
1117      handle_search_leaf(input_path, &opts.pattern, opts.start_path.as_deref(), &common_opts)
1118    }
1119    QuerySubcommand::SearchExpr(opts) => {
1120      let common_opts = SearchCommonOpts {
1121        filter: opts.filter.as_deref(),
1122        loose: !opts.exact,
1123        regex: false,
1124        max_depth: opts.max_depth,
1125        entry: opts.entry.as_deref().or(entry),
1126        source: SearchSource::All,
1127        detail_offset: opts.detail_offset,
1128        parent_path: false,
1129        format: parse_query_render_format(&opts.format)?,
1130        set_cursor: opts.set_cursor,
1131        compact_output: false,
1132      };
1133      handle_search_expr(input_path, &opts.pattern, opts.json, opts.start_path.as_deref(), &common_opts)
1134    }
1135    QuerySubcommand::Schema(opts) => {
1136      let (ns, def) = parse_target(&opts.target)?;
1137      let format = StructuredOutputFormat::parse(&opts.format, "query schema")?;
1138      handle_schema(input_path, ns, def, format, entry)
1139    }
1140    QuerySubcommand::Type(opts) => handle_type(input_path, opts, entry),
1141    QuerySubcommand::TypeAt(opts) => handle_type_at(input_path, opts, entry),
1142    QuerySubcommand::Context(opts) => handle_context(input_path, opts, entry),
1143  }
1144}
1145
1146pub fn prepare_program_for_type_query(snapshot: &snapshot::Snapshot) -> Result<(), String> {
1147  program::clear_runtime_caches_for_reload(Arc::from("query.type"), Arc::from("query.type"), true)?;
1148  {
1149    let mut program_data = program::PROGRAM_CODE_DATA
1150      .write()
1151      .map_err(|_| "Failed to open program data".to_owned())?;
1152    *program_data = program::extract_program_data(snapshot)?;
1153  }
1154
1155  let warnings = RefCell::<Vec<LocatedWarning>>::new(vec![]);
1156  runner::preprocess::ensure_ns_def_compiled(
1157    calcit_core::calcit::CORE_NS,
1158    calcit_core::calcit::BUILTIN_IMPLS_ENTRY,
1159    &warnings,
1160    &CallStackList::default(),
1161  )
1162  .map_err(|error| error.msg)
1163}
1164
1165fn parse_type_annotation_query(target: &str) -> Result<Arc<CalcitTypeAnnotation>, String> {
1166  const LEGACY_SIMPLE_TYPES: &[&str] = &[
1167    "bool",
1168    "number",
1169    "string",
1170    "symbol",
1171    "tag",
1172    "list",
1173    "map",
1174    "set",
1175    "tuple",
1176    "fn",
1177    "ref",
1178    "buffer",
1179    "cirru-quote",
1180    "unit",
1181    "nil",
1182    "js-object",
1183    "dynamic",
1184  ];
1185
1186  let trimmed = target.trim();
1187  if trimmed.is_empty() {
1188    return Err("Type query cannot be empty".to_owned());
1189  }
1190  if matches!(trimmed.trim_start_matches('\''), "any" | ":any") {
1191    return Err(format!(
1192      "[{}] `{trimmed}` is retired; `:any` is no longer a valid type alias. Use `Dynamic` only for genuinely dynamic boundaries, or use `:generics`/TypeVar or trait `:where` for polymorphism.",
1193      snapshot::LEGACY_TYPE_SYNTAX_CODE,
1194    ));
1195  }
1196  if trimmed.starts_with('(') {
1197    return Err(format!(
1198      "Type annotation `{target}` has an extra outer parenthesis layer. Use Cirru directly, for example `List Number`."
1199    ));
1200  }
1201  if !trimmed.chars().any(char::is_whitespace) {
1202    let is_quoted_symbol = trimmed.starts_with('\'');
1203    let name = trimmed.strip_prefix(':').or_else(|| trimmed.strip_prefix('\'')).unwrap_or(trimmed);
1204    let is_legacy_type_name = LEGACY_SIMPLE_TYPES.contains(&name);
1205    let is_builtin_type_symbol = (is_quoted_symbol || !trimmed.starts_with(':'))
1206      && !name.starts_with(':')
1207      && !name.starts_with('\'')
1208      && CalcitTypeAnnotation::canonical_type_symbol_name(name).is_some()
1209      // Constructors that need a payload have no bare meaning.
1210      && !matches!(name, "Optional" | "JsNullish" | "Variadic" | "Dyn");
1211    if !is_legacy_type_name && !is_builtin_type_symbol {
1212      return Err(format!(
1213        "Unknown builtin type `{target}`. Use a builtin type name such as `Number`, a type expression such as `List Number`, or `namespace/definition`."
1214      ));
1215    }
1216    return Ok(Arc::new(CalcitTypeAnnotation::from_tag_name(name)));
1217  }
1218
1219  let nodes = cirru_parser::parse(trimmed).map_err(|error| format!("Failed to parse type annotation `{target}`: {error}"))?;
1220  if nodes.len() != 1 {
1221    return Err(format!("Type annotation must contain exactly one expression, got {}", nodes.len()));
1222  }
1223  // A bare compact type such as `List Number` reads the same as `quote $ List Number` in code.
1224  let node = match &nodes[0] {
1225    // Qualified heads such as `calcit.core/Option` are type names too.
1226    Cirru::List(items)
1227      if matches!(items.first(), Some(Cirru::Leaf(head))
1228        if head.rsplit('/').next().is_some_and(|name| name.starts_with(|c: char| c.is_ascii_uppercase()))) =>
1229    {
1230      Cirru::List(vec![Cirru::leaf("quote"), nodes[0].clone()])
1231    }
1232    other => other.clone(),
1233  };
1234  let form = code_to_calcit(&node, "query.type", "target", vec![])?;
1235  if snapshot::find_legacy_any_in_type(&node).is_some() {
1236    return Err(format!(
1237      "[{}] `{target}` uses retired `:any` type syntax; write `Dynamic` only for genuinely dynamic boundaries, or use `:generics`/TypeVar or trait `:where` for polymorphism.",
1238      snapshot::LEGACY_TYPE_SYNTAX_CODE,
1239    ));
1240  }
1241  if let Some(error) = calcit_core::calcit::compact_type_syntax_error(&form) {
1242    return Err(format!("Invalid type expression `{target}`: {error}"));
1243  }
1244  Ok(CalcitTypeAnnotation::parse_type_annotation_form(&form))
1245}
1246
1247#[cfg(test)]
1248#[allow(clippy::items_after_test_module)]
1249mod type_query_tests {
1250  use super::*;
1251  use crate::cli_handlers::test_support::TestProject;
1252
1253  #[test]
1254  fn untyped_signatures_keep_parameters_but_not_values() {
1255    let signature = |source: &str| {
1256      let code = cirru_parser::parse(source).expect("parse").remove(0);
1257      definition_signature(&snapshot::CodeEntry::from_code(code))
1258    };
1259    assert_eq!(signature("defn helper (x y) (+ x y)"), "(untyped) defn helper $ x y");
1260    assert_eq!(signature("defcomp comp-item (item) (div)"), "(untyped) defcomp comp-item $ item");
1261    assert_eq!(signature("defref *store ({} (:count 0))"), "(untyped) defref *store");
1262    assert_eq!(signature("def config ([] 1 2)"), "(untyped) def config");
1263  }
1264
1265  #[test]
1266  fn runtime_call_arity_uses_core_proc_values_not_schema_or_spelling_guesses() {
1267    let snapshot = load_core_snapshot().expect("core snapshot");
1268    let core = &snapshot.files["calcit.core"];
1269    for (name, min, max) in [("read-dir", 1, 2), ("read-file", 1, 1), ("trim", 1, 2), ("range", 1, 3)] {
1270      let entry = &core.defs[name];
1271      let arity = core_runtime_call_arity("calcit.core", name, entry).expect("registered runtime Proc");
1272      assert_eq!(arity, RuntimeCallArity { min, max: Some(max) });
1273      assert_eq!(serde_json::to_value(arity).unwrap(), serde_json::json!({ "min": min, "max": max }));
1274      assert!(
1275        format_json_value_as_edn(&serde_json::to_value(arity).unwrap())
1276          .unwrap()
1277          .contains(":min")
1278      );
1279      assert!(core_runtime_call_arity("app.main", name, entry).is_none());
1280    }
1281    assert!(core_runtime_call_arity("calcit.core", "to-string", &core.defs["to-string"]).is_none());
1282    let mut renamed = core.defs["read-dir"].clone();
1283    renamed.schema = DYNAMIC_TYPE.clone();
1284    assert_eq!(
1285      core_runtime_call_arity("calcit.core", "unrelated-name", &renamed),
1286      Some(RuntimeCallArity { min: 1, max: Some(2) })
1287    );
1288    renamed.code = Cirru::Leaf("&runtime-implementation".into());
1289    renamed.tags.clear();
1290    assert!(core_runtime_call_arity("calcit.core", "read-dir", &renamed).is_none());
1291    renamed.code = Cirru::List(vec![Cirru::Leaf("&read-dir".into())]);
1292    assert!(
1293      core_runtime_call_arity("calcit.core", "read-dir", &renamed).is_none(),
1294      "a call expression is not a Proc value"
1295    );
1296    assert_eq!(render_runtime_call_arity(RuntimeCallArity { min: 1, max: Some(2) }), "1..=2");
1297    assert_eq!(render_runtime_call_arity(RuntimeCallArity { min: 1, max: None }), "1..");
1298  }
1299
1300  #[test]
1301  fn definition_ffi_json_is_complete_and_round_trips() {
1302    use cirru_edn::{Edn, EdnMapView};
1303    let mut names = EdnMapView::default();
1304    for index in 0..300 {
1305      names.insert(Edn::tag(format!("member-{index}")), Edn::str(format!("宿主\\\"\n{index}")));
1306    }
1307    let mut ffi = EdnMapView::default();
1308    ffi.insert(Edn::tag("names"), names.into());
1309    let ffi: Edn = ffi.into();
1310    let mut entry = snapshot::CodeEntry::from_code(vec!["def", "example", "nil"].into());
1311    entry.ffi = Some(ffi.clone());
1312    let legacy = code_entry_to_json(&entry).unwrap();
1313    let full = legacy["ffi"].as_str().unwrap();
1314    assert!(full.len() > 5000);
1315    assert_eq!(cirru_edn::parse(full).unwrap(), ffi);
1316    assert_ne!(format_edn_display(&ffi), full);
1317    let structured = serde_json::to_value(&ffi).unwrap();
1318    assert_eq!(structured[":names"].as_object().unwrap().len(), 300);
1319    assert_eq!(structured[":names"][":member-299"], "宿主\\\"\n299");
1320    let encoded = format_def_query_json(structured.clone(), Some(snapshot::definition_revision(&entry).unwrap())).unwrap();
1321    let decoded: serde_json::Value = serde_json::from_str(&encoded).unwrap();
1322    assert_eq!(decoded["data"], structured);
1323    assert_eq!(decoded["command"], "query.def");
1324    entry.ffi = None;
1325    assert!(code_entry_to_json(&entry).unwrap()["ffi"].is_null());
1326  }
1327
1328  fn on_cli_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
1329    std::thread::Builder::new()
1330      .name("calcit-query-test".into())
1331      // Core preprocessing and context rendering are recursive; mirror the
1332      // CLI worker instead of relying on Rust's smaller test-thread stack.
1333      .stack_size(16 * 1024 * 1024)
1334      .spawn(f)
1335      .expect("query test thread should start")
1336      .join()
1337      .expect("query test thread should finish")
1338  }
1339
1340  fn prepare_program_for_type_query_on_cli_stack(snapshot: snapshot::Snapshot) {
1341    on_cli_stack(move || prepare_program_for_type_query(&snapshot)).expect("static type metadata should prepare");
1342  }
1343
1344  #[test]
1345  fn helper_analysis_does_not_leak_strict_compilation_cache() {
1346    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1347    on_cli_stack(|| {
1348      let snapshot = load_snapshot_for_static_analysis(
1349        concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test-helper-inference.cirru"),
1350        None,
1351      )
1352      .expect("helper fixture");
1353      let strict = runner::preprocess::is_strict_types_enabled();
1354      let effective =
1355        crate::type_coverage::with_proven_helper_contracts(&snapshot, Some("app.main"), None, false).expect("helper analysis");
1356      assert!(matches!(
1357        effective.files["app.main"].defs["helper-count"].schema.as_ref(),
1358        CalcitTypeAnnotation::Fn(_)
1359      ));
1360      assert_eq!(runner::preprocess::is_strict_types_enabled(), strict);
1361      assert!(program::lookup_compiled_def("app.main", "helper-count").is_none());
1362      assert!(program::lookup_compiled_def(calcit_core::calcit::CORE_NS, calcit_core::calcit::BUILTIN_IMPLS_ENTRY).is_none());
1363    });
1364  }
1365
1366  #[test]
1367  fn parses_simple_type_tag_without_treating_it_as_a_call() {
1368    let annotation = parse_type_annotation_query(":number").expect("number type should parse");
1369    assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::Number));
1370  }
1371
1372  #[test]
1373  fn parses_canonical_builtin_type_symbol_without_treating_it_as_a_type_variable() {
1374    let annotation = parse_type_annotation_query("'String").expect("String type symbol should parse");
1375    assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::String));
1376  }
1377
1378  #[test]
1379  fn unknown_builtin_type_suggests_canonical_symbols() {
1380    let annotation = parse_type_annotation_query("String").expect("bare builtin name reads like the compact syntax");
1381    assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::String));
1382    let error = parse_type_annotation_query("Banana").expect_err("unknown bare name should be rejected");
1383    assert_eq!(
1384      error,
1385      "Unknown builtin type `Banana`. Use a builtin type name such as `Number`, a type expression such as `List Number`, or `namespace/definition`."
1386    );
1387  }
1388
1389  #[test]
1390  fn parses_bare_compact_type_expressions() {
1391    let annotation = parse_type_annotation_query("Map String (List Number)").expect("compact map type should parse");
1392    assert_eq!(
1393      format_type_query_annotation(annotation.as_ref()).expect("map should format"),
1394      "Map String $ List Number"
1395    );
1396    let error = parse_type_annotation_query("Fn Number").expect_err("Fn without a return clause should be rejected");
1397    assert!(error.contains("return clause"), "unexpected error: {error}");
1398    let error = parse_type_annotation_query("List Number String").expect_err("surplus type arguments should be rejected");
1399    assert!(error.contains("takes 1 type argument"), "unexpected error: {error}");
1400    let annotation = parse_type_annotation_query("calcit.core/Option Number").expect("qualified compact head should parse");
1401    assert_eq!(
1402      format_type_query_annotation(annotation.as_ref()).expect("option should format"),
1403      "calcit.core/Option Number"
1404    );
1405    for name in ["Optional", "'Optional", "JsNullish", "Variadic"] {
1406      assert!(parse_type_annotation_query(name).is_err(), "{name} needs a payload");
1407    }
1408  }
1409
1410  #[test]
1411  fn rejects_excess_type_symbol_prefixes() {
1412    assert!(parse_type_annotation_query("''String").is_err());
1413    assert!(parse_type_annotation_query("':String").is_err());
1414  }
1415
1416  #[test]
1417  fn rejects_retired_any_type_query() {
1418    for target in [":any", "any", "'any", "List :any"] {
1419      let error = parse_type_annotation_query(target).expect_err(&format!("{target} must be rejected"));
1420      assert!(error.contains("E_LEGACY_TYPE_SYNTAX"), "{target}: {error}");
1421      let envelope = query_failure_envelope("query.type", target, &error);
1422      assert_eq!(envelope["diagnostics"][0]["code"], "E_LEGACY_TYPE_SYNTAX", "{target}: {error}");
1423    }
1424    for target in ["Dynamic", ":dynamic", "'Dynamic"] {
1425      let annotation = parse_type_annotation_query(target).expect("Dynamic should parse");
1426      assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic));
1427    }
1428    let boxed = parse_type_annotation_query("Any").expect("Any should parse");
1429    assert!(matches!(boxed.as_ref(), CalcitTypeAnnotation::Any));
1430  }
1431
1432  #[test]
1433  fn context_query_failure_preserves_legacy_type_syntax_code_on_snapshot_load() {
1434    let project = TestProject::from_fixture();
1435    fs::write(
1436      &project.path,
1437      r#"{} (:package |mini)
1438  :version |0.0.0
1439  :entries $ {}
1440    :default $ {} (:mode :native) (:init-fn |mini/main!) (:reload-fn |mini/main!)
1441      :modules $ []
1442  :files $ {}
1443    |mini $ %{} :FileEntry
1444      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)
1445      :defs $ {}
1446        |main! $ %{} :CodeEntry (:doc |)
1447          :code $ quote (def main! 1)
1448          :examples $ []
1449          :schema :any
1450"#,
1451    )
1452    .expect("write fixture");
1453    let error = handle_context(
1454      project.path.to_str().expect("utf-8 fixture path"),
1455      &QueryContextCommand {
1456        target: "mini/main!".to_owned(),
1457        budget: 2400,
1458        format: "json".to_owned(),
1459        deps: false,
1460        dependency_limit: 12,
1461        usage_limit: 8,
1462        example_limit: 3,
1463        test_limit: 3,
1464        include_core: false,
1465      },
1466      None,
1467    )
1468    .expect_err("snapshot with :schema :any must fail");
1469    let envelope = query_failure_envelope("query.context", "mini/main!", &error);
1470    assert_eq!(envelope["diagnostics"][0]["code"], "E_LEGACY_TYPE_SYNTAX", "{error}");
1471  }
1472
1473  #[test]
1474  fn parses_compound_type_with_cirru_structure() {
1475    let annotation = parse_type_annotation_query(":: :list :number").expect("compound list type should parse");
1476    assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::List(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Number)));
1477
1478    let annotation = parse_type_annotation_query(":: 'List 'Number").expect("canonical compound list type should parse");
1479    assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::List(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Number)));
1480  }
1481
1482  #[test]
1483  fn rejects_extra_outer_parenthesis_layer() {
1484    let error = parse_type_annotation_query("(:: :list :number)").expect_err("extra call layer should be rejected");
1485    assert!(error.contains("extra outer parenthesis"));
1486  }
1487
1488  #[test]
1489  fn renders_type_annotations_without_edn_top_level_wrapper() {
1490    assert_eq!(
1491      format_type_query_annotation(&CalcitTypeAnnotation::Number).expect("number should format"),
1492      "Number"
1493    );
1494    let list_type = CalcitTypeAnnotation::List(Arc::new(CalcitTypeAnnotation::Number));
1495    assert_eq!(format_type_query_annotation(&list_type).expect("list should format"), "List Number");
1496    assert_eq!(
1497      format_query_schema(&CalcitTypeAnnotation::Ref(DYNAMIC_TYPE.clone(), Default::default()), true),
1498      "Ref"
1499    );
1500  }
1501
1502  #[test]
1503  fn schema_json_is_a_versioned_machine_readable_envelope() {
1504    let annotation = CalcitTypeAnnotation::Ref(Arc::new(CalcitTypeAnnotation::Bool), Default::default());
1505    let output = format_schema_query_json("app.main/*enabled?", "local", &annotation, "revision-1".to_owned(), None)
1506      .expect("schema JSON should format");
1507    let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
1508
1509    assert_eq!(value["schema_version"], 1);
1510    assert_eq!(value["command"], "query.schema");
1511    assert_eq!(value["data"]["id"], "app.main/*enabled?");
1512    assert_eq!(value["data"]["canonical_schema"], "Ref Bool");
1513    assert_eq!(value["data"]["tree"], serde_json::json!(["Ref", "Bool"]));
1514
1515    let broad_ref = CalcitTypeAnnotation::Ref(DYNAMIC_TYPE.clone(), Default::default());
1516    let output = format_schema_query_json("app.main/*cache", "local", &broad_ref, "revision-2".to_owned(), None)
1517      .expect("broad ref JSON should format");
1518    let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
1519    assert_eq!(value["data"]["canonical_schema"], "Ref");
1520    assert_eq!(value["data"]["tree"], "Ref");
1521  }
1522
1523  #[test]
1524  fn strict_macro_schema_queries_preserve_phase_contracts() {
1525    let schema = cirru_parser::parse(
1526      ":: 'Macro\n  {} (:required $ [] 'SyntaxList)\n    :rest 'Syntax\n    :expansion $ :: 'Expr 'Dynamic\n    :capabilities $ #{}",
1527    )
1528    .expect("strict macro schema syntax")
1529    .into_iter()
1530    .next()
1531    .expect("schema node");
1532    let annotation = snapshot::parse_schema_annotation_for_write(&schema).expect("strict macro schema");
1533
1534    let displayed = format_query_schema(annotation.as_ref(), true);
1535    assert_eq!(displayed, "Macro SyntaxList (& Syntax)\n  -> $ Expr Dynamic");
1536    assert_eq!(
1537      context_schema(annotation.as_ref()).expect("context schema"),
1538      Some(displayed.trim().to_owned())
1539    );
1540
1541    let output = format_schema_query_json(
1542      "app.main/with-bindings",
1543      "project",
1544      annotation.as_ref(),
1545      "revision-1".to_owned(),
1546      None,
1547    )
1548    .expect("macro schema JSON");
1549    let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
1550    assert_eq!(value["data"]["tree"][0], "Macro");
1551  }
1552
1553  #[test]
1554  fn examples_render_leaf_nodes_without_formatter_failure() {
1555    assert_eq!(format_example_node(&Cirru::Leaf("|literal".into())), "|literal");
1556    assert_eq!(
1557      format_example_node(&Cirru::List(vec![Cirru::Leaf("inc".into()), Cirru::Leaf("1".into())])),
1558      "inc 1"
1559    );
1560  }
1561
1562  #[test]
1563  fn search_results_share_cursor_indices_and_can_select_one() {
1564    let fixture = TestProject::from_fixture();
1565    let snapshot_path = fixture.snapshot_string();
1566    let tail_path = format!("@{}.1", fixture.main_tail);
1567
1568    let results = vec![(
1569      "app.main".to_string(),
1570      "main!".to_string(),
1571      vec![
1572        (vec![fixture.main_tail, 0], Cirru::leaf("do")),
1573        (vec![fixture.main_tail, 1], Cirru::leaf("true")),
1574      ],
1575    )];
1576    let saved_query = CursorLastQuery {
1577      command: "search".to_string(),
1578      pattern: "true".to_string(),
1579      filter: Some("app.main/main!".to_string()),
1580      exact: true,
1581      regex: false,
1582      max_depth: 0,
1583      start_path: None,
1584      entry: None,
1585      source: "project".to_string(),
1586      pattern_is_json: false,
1587      selected_index: 1,
1588      snapshot_revision: snapshot_content_revision(&snapshot_path).expect("snapshot revision should compute"),
1589    };
1590    maybe_set_cursor_from_search_results(&snapshot_path, &results, 1, saved_query.clone())
1591      .expect("second search result should become cursor");
1592    assert_eq!(
1593      crate::cli_handlers::cursor::resolve_cursor_path_argument(&snapshot_path, "app.main/main!", "@cursor")
1594        .expect("query-selected cursor should resolve"),
1595      tail_path.as_str()
1596    );
1597
1598    let mut filter = None;
1599    let mut start_path = Some("@cursor".to_string());
1600    resolve_search_cursor_references(&snapshot_path, &mut filter, &mut start_path)
1601      .expect("cursor-scoped search should infer target and path");
1602    assert_eq!(filter.as_deref(), Some("app.main/main!"));
1603    assert_eq!(start_path.as_deref(), Some(tail_path.as_str()));
1604
1605    let mut type_at = QueryCommand {
1606      subcommand: QuerySubcommand::TypeAt(QueryTypeAtCommand {
1607        target: "@cursor".to_string(),
1608        path: "@cursor".to_string(),
1609        format: "json".to_string(),
1610      }),
1611    };
1612    resolve_query_cursor_references(&mut type_at, &snapshot_path).expect("type-at should resolve cursor target and path");
1613    let QuerySubcommand::TypeAt(type_at) = type_at.subcommand else {
1614      panic!("type-at command should remain type-at")
1615    };
1616    assert_eq!(type_at.target, "app.main/main!");
1617    assert_eq!(type_at.path, tail_path);
1618
1619    let mut mismatched_filter = Some("app.other/demo".to_string());
1620    let mut cursor_start = Some("@cursor".to_string());
1621    let error = resolve_search_cursor_references(&snapshot_path, &mut mismatched_filter, &mut cursor_start)
1622      .expect_err("cursor search should reject mismatched target");
1623    assert!(error.contains("Cursor-scoped search targets"), "error: {error}");
1624
1625    let error = maybe_set_cursor_from_search_results(&snapshot_path, &results, 2, saved_query)
1626      .expect_err("out-of-range search cursor index should fail");
1627    assert!(error.contains("returned 2 match"), "error: {error}");
1628
1629    let snapshot = load_main_snapshot(&snapshot_path).expect("query cursor fixture should load");
1630    let options = SearchCommonOpts {
1631      filter: Some("app.main/main!"),
1632      loose: false,
1633      regex: false,
1634      max_depth: 0,
1635      entry: None,
1636      source: SearchSource::Project,
1637      detail_offset: 0,
1638      parent_path: false,
1639      format: QueryRenderFormat::Json,
1640      set_cursor: None,
1641      compact_output: false,
1642    };
1643    let sources = snapshot_search_sources(&snapshot, SearchSource::Project, None);
1644    let catalog = SearchCatalog { snapshot, sources };
1645    let output =
1646      format_search_results_json("query.search", "true", false, None, &options, &catalog, &results).expect("search JSON should format");
1647    let value: serde_json::Value = serde_json::from_str(&output).expect("search output should be valid JSON");
1648    assert_eq!(value["data"]["filters"]["source"], "project");
1649    assert_eq!(value["data"]["definitions"][0]["source"], "project");
1650    assert_eq!(value["data"]["definitions"][0]["origin"]["package"], "app");
1651    assert_eq!(value["data"]["definitions"][0]["matches"][0]["cursor_index"], 0);
1652    assert_eq!(value["data"]["definitions"][0]["matches"][0]["node_kind"], "call");
1653    assert_eq!(value["data"]["definitions"][0]["matches"][1]["cursor_index"], 1);
1654    assert_eq!(value["data"]["definitions"][0]["matches"][1]["node_kind"], "leaf");
1655  }
1656
1657  #[test]
1658  fn number_type_query_uses_static_dispatch_metadata() {
1659    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1660    let snapshot = load_core_snapshot().expect("core snapshot should load");
1661    prepare_program_for_type_query_on_cli_stack(snapshot);
1662
1663    let methods = runner::preprocess::static_method_descriptors(&CalcitTypeAnnotation::Number)
1664      .expect("number method metadata should resolve")
1665      .into_iter()
1666      .map(|method| method.name)
1667      .collect::<Vec<_>>();
1668
1669    assert_eq!(
1670      methods,
1671      vec![
1672        ".ceil",
1673        ".compare",
1674        ".display-by",
1675        ".empty",
1676        ".floor",
1677        ".format",
1678        ".fract",
1679        ".inc",
1680        ".integer?",
1681        ".negate",
1682        ".pow",
1683        ".rem",
1684        ".round",
1685        ".sqrt",
1686        ".debug",
1687        ".eq?",
1688        ".hash",
1689        ".add",
1690        ".multiply",
1691        ".to-string",
1692      ]
1693    );
1694
1695    let integer = runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::Number)
1696      .expect("number method contracts should resolve")
1697      .into_iter()
1698      .find(|(method, _)| method.name == ".integer?")
1699      .map(|(method, contract)| context_method(method, contract))
1700      .expect("integer predicate should be discoverable");
1701    assert_eq!(integer.status, "proven");
1702    assert_eq!(integer.parameter_types, Some(vec![]));
1703    assert_eq!(integer.return_type.as_deref(), Some("bool"));
1704    assert_eq!(integer.definition.as_deref(), Some("calcit.core/integer?"));
1705    let retired = runner::preprocess::static_method_contract(&CalcitTypeAnnotation::Number, ".round?");
1706    assert_ne!(retired.status, "proven", "the retired `.round?` alias is no longer a Number method");
1707  }
1708
1709  #[test]
1710  fn originless_enum_methods_are_not_reported_as_strict_callable() {
1711    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1712    let snapshot = load_core_snapshot().expect("core snapshot should load");
1713    prepare_program_for_type_query_on_cli_stack(snapshot);
1714
1715    let contracts =
1716      runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::AnonymousEnum).expect("enum methods should resolve");
1717    let status_of = |name: &str| {
1718      contracts
1719        .iter()
1720        .find(|(method, _)| method.name == name)
1721        .map(|(_, contract)| contract.clone())
1722        .unwrap_or_else(|| panic!("enum method {name} should be discoverable"))
1723    };
1724    // Strict dispatch through `&core-enum-methods` fails with E_ORIGINLESS_METHOD_DISPATCH (#2441).
1725    let assoc = status_of(".assoc");
1726    assert_eq!(assoc.status, "open", "{assoc:?}");
1727    let detail = assoc
1728      .detail
1729      .as_deref()
1730      .expect("originless method should explain the strict rejection");
1731    assert!(detail.contains("E_ORIGINLESS_METHOD_DISPATCH"), "{detail}");
1732    assert!(detail.contains("`calcit.core/assoc`"), "{detail}");
1733    assert_eq!(
1734      runner::preprocess::static_method_contract(&CalcitTypeAnnotation::AnonymousEnum, ".assoc").status,
1735      "open"
1736    );
1737    // A same-named core function is only suggested when it accepts the receiver.
1738    assert!(!runner::preprocess::core_function_accepts_receiver(
1739      "trim",
1740      &CalcitTypeAnnotation::AnonymousEnum
1741    ));
1742    assert!(runner::preprocess::core_function_accepts_receiver(
1743      "trim",
1744      &CalcitTypeAnnotation::String
1745    ));
1746    // Nominal trait methods on the same receiver stay proven.
1747    assert_eq!(status_of(".count").status, "proven");
1748  }
1749
1750  #[test]
1751  fn tuple_method_query_matches_trait_bound_checking() {
1752    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1753    let snapshot = load_core_snapshot().expect("core snapshot should load");
1754    prepare_program_for_type_query_on_cli_stack(snapshot);
1755
1756    // #2558: Tuple does not satisfy `Add`, so `.add` must not claim `Self = Tuple`.
1757    let homogeneous = parse_type_annotation_query("Tuple Number Number Number").expect("tuple should parse");
1758    let add = runner::preprocess::static_method_contract(&homogeneous, ".add");
1759    assert_eq!(add.status, "proven", "{add:?}");
1760    let list_number = CalcitTypeAnnotation::List(Arc::new(CalcitTypeAnnotation::Number));
1761    assert_eq!(add.return_type.as_deref(), Some(&list_number), "{add:?}");
1762    assert!(
1763      add
1764        .arg_types
1765        .as_ref()
1766        .is_some_and(|args| args.iter().all(|arg| arg.as_ref() == &list_number)),
1767      "{add:?}"
1768    );
1769    assert!(add.detail.as_deref().is_some_and(|detail| detail.contains("`Add`")), "{add:?}");
1770
1771    let heterogeneous = parse_type_annotation_query("Tuple Number String").expect("tuple should parse");
1772    let add = runner::preprocess::static_method_contract(&heterogeneous, ".add");
1773    assert_eq!(add.status, "open", "{add:?}");
1774
1775    // Traits a tuple does satisfy keep their tuple-typed view.
1776    assert_eq!(runner::preprocess::static_method_contract(&homogeneous, ".count").status, "proven");
1777  }
1778
1779  #[test]
1780  fn predicate_method_query_distinguishes_index_key_and_value_origins() {
1781    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1782    let snapshot = load_core_snapshot().expect("core snapshot should load");
1783    prepare_program_for_type_query_on_cli_stack(snapshot);
1784
1785    let list = parse_type_annotation_query(":: 'List 'Number").expect("typed list should parse");
1786    let string = CalcitTypeAnnotation::String;
1787    for (receiver, definition) in [
1788      (list.as_ref(), "calcit.core/&list:contains?"),
1789      (&string, "calcit.core/&str:contains?"),
1790    ] {
1791      let contract = runner::preprocess::static_method_contract(receiver, ".contains-index?");
1792      assert_eq!(contract.status, "proven", "{contract:?}");
1793      assert_eq!(contract.definition.as_deref(), Some(definition));
1794      assert_eq!(contract.arg_types.unwrap()[0].describe(), "number");
1795      assert_eq!(contract.return_type.unwrap().describe(), "bool");
1796    }
1797
1798    let map = parse_type_annotation_query(":: 'Map 'String 'String").expect("same-type map should parse");
1799    for (method, definition) in [
1800      (".contains-key?", "calcit.core/&map:contains?"),
1801      (".contains-value?", "calcit.core/&map:includes?"),
1802    ] {
1803      let contract = runner::preprocess::static_method_contract(map.as_ref(), method);
1804      assert_eq!(contract.status, "proven", "{contract:?}");
1805      assert_eq!(contract.definition.as_deref(), Some(definition));
1806      assert_eq!(contract.arg_types.unwrap()[0].describe(), "string");
1807      assert_eq!(contract.return_type.unwrap().describe(), "bool");
1808    }
1809  }
1810
1811  #[test]
1812  fn indexed_sequence_methods_expose_proven_agent_contracts() {
1813    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1814    let snapshot = load_core_snapshot().expect("core snapshot should load");
1815    prepare_program_for_type_query_on_cli_stack(snapshot);
1816
1817    // List positional lookup is `.get`; the `.nth` alias was retired from List in 0.29.0.
1818    for (receiver, member, index_method) in [
1819      (
1820        parse_type_annotation_query(":: 'List 'Number").expect("typed list"),
1821        "number",
1822        ".get",
1823      ),
1824      (parse_type_annotation_query("'String").expect("string"), "string", ".nth"),
1825    ] {
1826      for method in [".first", ".last", index_method] {
1827        let contract = runner::preprocess::static_method_contract(receiver.as_ref(), method);
1828        assert_eq!(contract.status, "proven", "{method}: {contract:?}");
1829        assert_eq!(
1830          contract.return_type.unwrap().describe(),
1831          format!("type calcit.core/Option<{member}>")
1832        );
1833        let args = contract.arg_types.expect("proven method parameters");
1834        assert_eq!(args.len(), usize::from(method == index_method));
1835        if method == index_method {
1836          assert_eq!(args[0].describe(), "number");
1837        }
1838      }
1839    }
1840  }
1841
1842  #[test]
1843  fn structured_method_call_types_preserve_specialized_container_and_callback_nodes() {
1844    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1845    let snapshot = load_core_snapshot().expect("core snapshot should load");
1846    prepare_program_for_type_query_on_cli_stack(snapshot);
1847    let receiver = parse_type_annotation_query(":: 'List 'Number").expect("list type");
1848    let get = runner::preprocess::static_method_contract(receiver.as_ref(), ".get");
1849    let nodes = method_call_types(&get).expect("proven positional lookup should export nodes");
1850    assert_eq!(nodes.parameters, vec![serde_json::json!("'Number")]);
1851    assert_eq!(nodes.returns, serde_json::json!(["::", "'calcit.core/Option", "'Number"]));
1852    assert!(nodes.rest.is_none());
1853
1854    let fold = runner::preprocess::static_method_contract(receiver.as_ref(), ".fold");
1855    let nodes = method_call_types(&fold).expect("proven callback should export syntax nodes");
1856    assert_eq!(nodes.parameters[0], serde_json::json!("'U"));
1857    assert_eq!(nodes.parameters[1][0], "::");
1858    assert_eq!(nodes.parameters[1][1], "'Fn");
1859    assert_eq!(nodes.returns, serde_json::json!("'U"));
1860    let open = runner::preprocess::static_method_contract(receiver.as_ref(), ".each");
1861    assert_eq!(open.status, "open");
1862    assert_eq!(
1863      open.arg_types.as_ref().unwrap()[0].describe(),
1864      "fn(number) -> dynamic (:features :pass)"
1865    );
1866    assert_eq!(open.return_type.as_ref().unwrap().describe(), "unit");
1867    assert!(open.rest_type.is_none());
1868    assert_eq!(open.definition.as_deref(), Some("calcit.core/each"));
1869    assert!(
1870      method_call_types(&open).is_none(),
1871      "unproven calls must not fabricate syntax evidence"
1872    );
1873  }
1874
1875  #[test]
1876  fn parse_method_queries_keep_open_results_open_and_prove_cirru_rows() {
1877    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1878    let snapshot = load_core_snapshot().expect("core snapshot should load");
1879    prepare_program_for_type_query_on_cli_stack(snapshot);
1880    let methods = runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::String)
1881      .expect("String methods")
1882      .into_iter()
1883      .map(|(descriptor, contract)| context_method(descriptor, contract))
1884      .collect::<Vec<_>>();
1885    for (name, result) in [
1886      (".parse-json", "type calcit.core/Result<dynamic, string>"),
1887      (".parse-cirru-edn", "type calcit.core/Result<dynamic, string>"),
1888    ] {
1889      let method = methods.iter().find(|method| method.name == name).expect("parse method");
1890      assert_eq!(method.status, "open");
1891      assert_eq!(method.parameter_types, Some(vec![]));
1892      assert_eq!(method.return_type.as_deref(), Some(result));
1893      assert!(method.call_types.is_none(), "declared open types do not prove a closed call");
1894      assert!(render_context_method(method).contains(&format!("() -> {result}")));
1895    }
1896    // Since 0.35.0 the Cirru rows are `List CirruNode` (#2556), so the result is closed.
1897    let rows = methods
1898      .iter()
1899      .find(|method| method.name == ".parse-cirru-list")
1900      .expect("parse method");
1901    assert_eq!(rows.status, "proven");
1902    assert!(
1903      rows.return_type.as_deref().is_some_and(|result| result.contains("CirruNode")),
1904      "{:?}",
1905      rows.return_type
1906    );
1907    assert_eq!(rows.parameter_types, Some(vec![]));
1908    assert!(rows.call_types.is_some(), "proven rows must export call types");
1909    let missing = runner::preprocess::static_method_contract(&CalcitTypeAnnotation::String, ".missing-method");
1910    assert_eq!(missing.status, "open");
1911    assert!(missing.arg_types.is_none());
1912    assert!(missing.return_type.is_none());
1913    assert!(method_call_types(&missing).is_none());
1914  }
1915
1916  #[test]
1917  fn method_query_reuses_bound_collection_contracts_and_keeps_open_schemas_explicit() {
1918    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
1919    let snapshot = load_core_snapshot().expect("core snapshot should load");
1920    prepare_program_for_type_query_on_cli_stack(snapshot.clone());
1921
1922    let list = parse_type_annotation_query(":: 'List 'Number").expect("typed list should parse");
1923    let list_get = runner::preprocess::static_method_contracts(list.as_ref())
1924      .expect("list methods should resolve")
1925      .into_iter()
1926      .find(|(method, _)| method.name == ".get")
1927      .map(|(method, contract)| context_method(method, contract))
1928      .expect("list get should exist");
1929    assert_eq!(list_get.status, "proven");
1930    assert_eq!(list_get.parameter_types, Some(vec!["number".to_owned()]));
1931    assert_eq!(list_get.return_type.as_deref(), Some("type calcit.core/Option<number>"));
1932    assert_eq!(list_get.definition.as_deref(), Some("calcit.core/get"));
1933    assert!(render_context_method(&list_get).contains("(number) -> type calcit.core/Option<number>"));
1934    let list_concat = runner::preprocess::static_method_contract(list.as_ref(), ".concat");
1935    assert_eq!(list_concat.status, "proven", "the first variadic argument is the method receiver");
1936    assert!(list_concat.arg_types.unwrap().is_empty());
1937    assert_eq!(list_concat.rest_type.unwrap().describe(), "list<number>");
1938    assert_eq!(list_concat.return_type.unwrap().describe(), "list<number>");
1939    assert_eq!(list_concat.definition.as_deref(), Some("calcit.core/&list:concat"));
1940    let list_append = runner::preprocess::static_method_contract(list.as_ref(), ".append");
1941    assert_eq!(
1942      list_append.status, "proven",
1943      "core definition schema should survive method dispatch: {list_append:?}"
1944    );
1945    assert_eq!(list_append.arg_types.unwrap()[0].describe(), "number");
1946    assert_eq!(list_append.return_type.unwrap().describe(), "list<number>");
1947    assert_eq!(list_append.definition.as_deref(), Some("calcit.core/append"));
1948    let open_list = parse_type_annotation_query(":: 'List 'Dynamic").expect("open list should parse");
1949    let open_append = runner::preprocess::static_method_contract(open_list.as_ref(), ".append");
1950    assert_eq!(open_append.status, "open", "an explicitly dynamic element still needs narrowing");
1951    assert_eq!(open_append.arg_types.unwrap()[0].describe(), "dynamic");
1952    assert_eq!(open_append.return_type.unwrap().describe(), "list");
1953    let open_concat = runner::preprocess::static_method_contract(open_list.as_ref(), ".concat");
1954    assert_eq!(open_concat.status, "open");
1955    assert!(open_concat.arg_types.as_ref().unwrap().is_empty());
1956    assert_eq!(open_concat.rest_type.as_ref().unwrap().describe(), "list");
1957    assert_eq!(open_concat.return_type.as_ref().unwrap().describe(), "list");
1958    assert!(method_call_types(&open_concat).is_none());
1959    let rendered_concat = context_method(
1960      runner::preprocess::StaticMethodDescriptor {
1961        name: ".concat".to_owned(),
1962        origin: "test".to_owned(),
1963      },
1964      open_concat,
1965    );
1966    assert!(render_context_method(&rendered_concat).contains("(...list) -> list"));
1967    let original_fingerprint = method_contract_fingerprint(&Some(vec![list_get.clone()])).expect("method serialization");
1968    let mut changed = list_get;
1969    changed.return_type = Some("type calcit.core/Option<string>".to_owned());
1970    let changed_fingerprint = method_contract_fingerprint(&Some(vec![changed])).expect("method serialization");
1971    assert_ne!(
1972      original_fingerprint, changed_fingerprint,
1973      "a changed callable contract must change the query revision"
1974    );
1975
1976    let map = parse_type_annotation_query(":: 'Map 'String 'Number").expect("typed map should parse");
1977    let map_get = runner::preprocess::static_method_contract(map.as_ref(), ".get");
1978    assert_eq!(map_get.status, "proven");
1979    assert_eq!(map_get.arg_types.unwrap()[0].describe(), "string");
1980    assert_eq!(map_get.return_type.unwrap().describe(), "type calcit.core/Option<number>");
1981
1982    let option = parse_type_annotation_query(":: 'Option 'Number").expect("typed Option should parse");
1983    let unwrap_or = runner::preprocess::static_method_contract(option.as_ref(), ".unwrap-or");
1984    assert_eq!(unwrap_or.status, "proven");
1985    assert_eq!(unwrap_or.arg_types.unwrap()[0].describe(), "number");
1986    assert_eq!(unwrap_or.return_type.unwrap().describe(), "number");
1987    assert!(unwrap_or.generics.is_empty(), "receiver-bound generic must not appear unbound");
1988
1989    let open_option = parse_type_annotation_query(":: 'Option 'Dynamic").expect("open Option should parse");
1990    let open_unwrap_or = runner::preprocess::static_method_contract(open_option.as_ref(), ".unwrap-or");
1991    assert_eq!(
1992      open_unwrap_or.status, "open",
1993      "receiver-bound Dynamic must not become a precise contract"
1994    );
1995    assert_eq!(open_unwrap_or.arg_types.unwrap()[0].describe(), "dynamic");
1996    assert_eq!(open_unwrap_or.return_type.unwrap().describe(), "dynamic");
1997    let open_and_then = runner::preprocess::static_method_contract(open_option.as_ref(), ".and-then");
1998    assert_eq!(open_and_then.status, "open", "nested Dynamic callback input must remain open");
1999    let some = runner::preprocess::static_method_contract(open_option.as_ref(), ".some?");
2000    assert_eq!(some.status, "proven", "presence check does not expose the Dynamic payload");
2001    assert_eq!(some.return_type.unwrap().describe(), "bool");
2002
2003    let option_map = runner::preprocess::static_method_contract(option.as_ref(), ".map");
2004    assert_eq!(
2005      option_map.status, "proven",
2006      "the selected implementation supplies its generic callback relation"
2007    );
2008    assert_eq!(
2009      option_map.arg_types.as_ref().unwrap()[0].describe(),
2010      "fn(number) -> 'U (:features :pass)"
2011    );
2012    assert_eq!(option_map.return_type.as_ref().unwrap().describe(), "type calcit.core/Option<'U>");
2013    assert_eq!(option_map.generics, vec!["U"]);
2014    let nodes = method_call_types(&option_map).expect("generic output should retain callable syntax evidence");
2015    assert_eq!(nodes.returns, serde_json::json!(["::", "'calcit.core/Option", "'U"]));
2016    let open_map = runner::preprocess::static_method_contract(open_option.as_ref(), ".map");
2017    assert_eq!(open_map.status, "open", "an open receiver payload still needs call-site proof");
2018    assert!(method_call_types(&open_map).is_none());
2019
2020    let result = parse_type_annotation_query(":: 'Result 'Number 'String").expect("typed Result should parse");
2021    let result_map = runner::preprocess::static_method_contract(result.as_ref(), ".map");
2022    assert_eq!(
2023      result_map.generics,
2024      vec!["ResultMapOutput"],
2025      "specialized output variables must be discoverable"
2026    );
2027    let map_err = runner::preprocess::static_method_contract(result.as_ref(), ".map-err");
2028    assert_eq!(map_err.status, "proven");
2029    let rendered = render_context_method(&context_method(
2030      runner::preprocess::StaticMethodDescriptor {
2031        name: ".map-err".to_owned(),
2032        origin: "calcit.core/ResultOps".to_owned(),
2033      },
2034      map_err.clone(),
2035    ));
2036    assert!(rendered.contains("for<'F>"));
2037    assert_eq!(map_err.arg_types.unwrap()[0].describe(), "fn(string) -> 'F");
2038    assert_eq!(map_err.return_type.unwrap().describe(), "type Result<number, 'F>");
2039    assert_eq!(map_err.generics, vec!["F"]);
2040
2041    let (fs_path, source) =
2042      on_cli_stack(move || resolve_type_query_target(&snapshot, "calcit.core/FsPath")).expect("core FsPath type should resolve");
2043    assert_eq!(source, "resolved core nominal definition");
2044    let read_text = on_cli_stack(move || runner::preprocess::static_method_contract(fs_path.as_ref(), ".read-text"));
2045    assert_eq!(read_text.status, "proven");
2046    assert!(read_text.arg_types.unwrap().is_empty());
2047    assert_eq!(read_text.return_type.unwrap().describe(), "type Result<string, string>");
2048    assert_eq!(read_text.definition.as_deref(), Some("calcit.core/fs-path:read-text"));
2049  }
2050
2051  #[test]
2052  fn method_query_reads_source_external_object_trait_without_project_initialization() {
2053    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2054    let snapshot =
2055      load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test-js.cirru"), None).expect("JS fixture should load");
2056    prepare_program_for_type_query_on_cli_stack(snapshot.clone());
2057
2058    let (trait_type, source) =
2059      on_cli_stack(move || resolve_type_query_target(&snapshot, "test-js.main/TestDate")).expect("external trait should resolve");
2060    assert_eq!(source, "source trait definition");
2061    let method = on_cli_stack(move || runner::preprocess::static_method_contract(trait_type.as_ref(), ".now"));
2062    assert_eq!(method.status, "proven");
2063    assert!(method.arg_types.unwrap().is_empty());
2064    assert_eq!(method.return_type.unwrap().describe(), "number");
2065  }
2066
2067  #[test]
2068  fn query_format_and_unicode_truncation_are_deterministic() {
2069    assert_eq!(parse_query_render_format("human"), Ok(QueryRenderFormat::Human));
2070    assert_eq!(parse_query_render_format("json"), Ok(QueryRenderFormat::Json));
2071    assert_eq!(parse_query_render_format("edn"), Ok(QueryRenderFormat::Edn));
2072    assert_eq!(truncate_chars("你好 Calcit", 2), ("你好…".to_owned(), true));
2073    assert_eq!(truncate_chars("你好", 2), ("你好".to_owned(), false));
2074  }
2075
2076  #[test]
2077  fn js_ffi_query_exposes_dependency_owner_and_source_without_executing_js() {
2078    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2079    let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/js-ffi-consumer.cirru");
2080    let snapshot = load_snapshot(input, None).expect("JS FFI consumer should load");
2081    let file = snapshot.files.get("app.main").expect("dependency namespace");
2082    let inline = file
2083      .defs
2084      .get("plus-one")
2085      .and_then(|entry| entry.ffi.as_ref())
2086      .expect("inline metadata");
2087    let inline_info = js_ffi_query_info(input, &snapshot, "app.main", inline).expect("inline query info");
2088    assert_eq!(inline_info.target.as_deref(), Some("node"));
2089    assert_eq!(inline_info.owner_module.as_deref(), Some("app"));
2090    assert_eq!(inline_info.source_kind, Some("inline"));
2091    assert!(render_js_ffi_info(&inline_info, Some("(x)=>x+1")).contains("```javascript\n(x)=>x+1"));
2092
2093    let file_ffi = file
2094      .defs
2095      .get("base-name")
2096      .and_then(|entry| entry.ffi.as_ref())
2097      .expect("file metadata");
2098    let file_info = js_ffi_query_info(input, &snapshot, "app.main", file_ffi).expect("file query info");
2099    assert_eq!(file_info.source_kind, Some("file"));
2100    assert_eq!(file_info.source_file.as_deref(), Some("js-ffi-assets/base-name.js"));
2101    assert_eq!(file_info.modules.get("path").map(String::as_str), Some("node:path"));
2102    assert!(file_info.module_root.as_deref().is_some_and(|root| root.ends_with("js-ffi-module")));
2103  }
2104
2105  fn context_test_options(target: &str) -> QueryContextCommand {
2106    QueryContextCommand {
2107      target: target.to_owned(),
2108      budget: 2400,
2109      format: "json".to_owned(),
2110      deps: false,
2111      dependency_limit: 12,
2112      usage_limit: 8,
2113      example_limit: 3,
2114      test_limit: 3,
2115      include_core: false,
2116    }
2117  }
2118
2119  #[test]
2120  fn context_examples_render_symbol_leaf_without_failing_collection() {
2121    let examples = vec![
2122      Cirru::Leaf("ConsoleHost".into()),
2123      Cirru::List(vec![Cirru::Leaf("identity".into()), Cirru::Leaf("1".into())]),
2124    ];
2125    let collection = build_context_examples(&examples, 2, 1200).expect("leaf and list examples should render");
2126    assert_eq!(collection.total, 2);
2127    assert_eq!(collection.items[0].cirru, "ConsoleHost");
2128    assert_eq!(collection.items[0].tree, Some(serde_json::json!("ConsoleHost")));
2129    assert_eq!(collection.items[1].cirru, "identity 1");
2130  }
2131
2132  #[test]
2133  fn special_builtin_context_preserves_examples_and_intent() {
2134    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2135    let snapshot = load_core_snapshot().expect("core snapshot should load");
2136    let envelope = on_cli_stack(move || {
2137      let meta = lookup_special_builtin_query_meta("calcit.core", "to-js-data")
2138        .expect("metadata lookup should work")
2139        .expect("to-js-data metadata should exist");
2140      build_special_builtin_context(
2141        &snapshot,
2142        "calcit.core",
2143        "to-js-data",
2144        meta,
2145        &context_test_options("calcit.core/to-js-data"),
2146      )
2147      .expect("context should build")
2148    });
2149
2150    assert_eq!(envelope.command, "query.context");
2151    assert_eq!(envelope.data.coverage, "intentional-dynamic");
2152    assert_eq!(envelope.data.examples.total, 3);
2153    assert_eq!(
2154      envelope.data.examples.items[2]
2155        .tree
2156        .as_ref()
2157        .and_then(|tree| tree.as_array())
2158        .map(Vec::len),
2159      Some(3)
2160    );
2161    assert!(
2162      envelope
2163        .diagnostics
2164        .iter()
2165        .any(|diagnostic| diagnostic.code == "I_DYNAMIC_TYPE_INTENTIONAL")
2166    );
2167  }
2168
2169  #[test]
2170  fn namespace_source_uses_bundled_core_identity() {
2171    for package in ["calcit.std", "calcit-test", "app"] {
2172      let mut snapshot = snapshot::Snapshot {
2173        package: package.to_owned(),
2174        ..Default::default()
2175      };
2176      let namespace = format!("{package}.main");
2177      snapshot.files.insert(namespace.clone(), snapshot::gen_meta_ns(&namespace, "test"));
2178      assert_eq!(namespace_source(&snapshot, package), "project");
2179      assert_eq!(namespace_source(&snapshot, &format!("{package}.main")), "project");
2180      assert_eq!(namespace_source(&snapshot, &format!("{package}-other.main")), "dependency");
2181      for namespace in [
2182        "calcit.core",
2183        "calcit.internal",
2184        "calcit.internal.helpers",
2185        "calcit.test",
2186        "calcit.gen",
2187      ] {
2188        assert_eq!(namespace_source(&snapshot, namespace), "core");
2189      }
2190      if package != "calcit.std" {
2191        assert_eq!(namespace_source(&snapshot, "calcit.std.time"), "dependency");
2192      }
2193      let owner = js_ffi_owner(
2194        concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru"),
2195        &snapshot,
2196        &namespace,
2197      )
2198      .expect("project JS FFI owner");
2199      assert_eq!(owner.module, package);
2200    }
2201  }
2202
2203  #[test]
2204  fn regular_context_carries_snapshot_revision_and_tree_location() {
2205    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2206    let snapshot = load_core_snapshot().expect("core snapshot should load");
2207    let (envelope, expected_revision) = on_cli_stack(move || {
2208      let entry = snapshot
2209        .files
2210        .get("calcit.core")
2211        .and_then(|file| file.defs.get("map"))
2212        .expect("core map should exist");
2213      let expected_revision = snapshot::definition_revision(entry).expect("revision should compute");
2214      let envelope = build_regular_context(&snapshot, "calcit.core", "map", entry, &context_test_options("calcit.core/map"))
2215        .expect("context should build");
2216      (envelope, expected_revision)
2217    });
2218
2219    assert_eq!(envelope.data.id, "calcit.core/map");
2220    assert_eq!(envelope.data.source, "core");
2221    assert_eq!(envelope.data.code.root, "code");
2222    assert!(envelope.data.code.nodes > 0);
2223    assert_eq!(envelope.revision, expected_revision);
2224  }
2225
2226  #[test]
2227  fn project_function_schema_argument_resolves_source_backed_struct() {
2228    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2229    let snapshot =
2230      load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru"), None).expect("test snapshot should load");
2231    prepare_program_for_type_query_on_cli_stack(snapshot.clone());
2232    let schema = program::lookup_def_schema("test-struct.main", "sum-point");
2233    let CalcitTypeAnnotation::Fn(annotation) = schema.as_ref() else {
2234      panic!("sum-point should have a function schema");
2235    };
2236    let argument_type = annotation.arg_types.first().expect("sum-point argument type");
2237    // The schema writes the short name `Point2D` (#2683); it resolves in the
2238    // declaring namespace, as preprocessing does.
2239    let struct_def =
2240      calcit_core::calcit::with_type_annotation_warning_context("test-struct.main/sum-point", || argument_type.resolve_to_struct())
2241        .expect("source-backed Point2D should resolve");
2242
2243    assert_eq!(struct_def.name.ref_str(), "Point2D");
2244    assert_eq!(struct_def.index_of("x"), Some(0));
2245    assert!(matches!(
2246      struct_def.field_types.first().map(AsRef::as_ref),
2247      Some(CalcitTypeAnnotation::Number)
2248    ));
2249    let result_type = CalcitTypeAnnotation::TypeRef(Arc::from("test-enum.main/Result0"), Arc::new(vec![]));
2250    assert!(result_type.resolve_to_enum().is_some(), "source-backed Result0 should resolve");
2251    assert!(
2252      result_type.is_compatible_with(&CalcitTypeAnnotation::AnonymousEnum),
2253      "a source-backed enum reference should satisfy enum operations"
2254    );
2255    let person_symbol =
2256      code_to_calcit(&Cirru::Leaf(Arc::from("Person")), "test-struct.main", "test-struct", vec![]).expect("Person symbol should parse");
2257    let person_type = runner::preprocess::infer_static_type_from_expr(&person_symbol).expect("Person type should infer statically");
2258    assert!(
2259      matches!(person_type.as_ref(), CalcitTypeAnnotation::StructDef(definition)
2260        if definition.definition_ref.as_deref() == Some("test-struct.main/Person")),
2261      "definition expressions should retain definition identity rather than instance evidence: {person_type}"
2262    );
2263    let (queried_person_type, source) =
2264      resolve_type_query_target(&snapshot, "test-struct.main/Person").expect("type query should infer defstruct type");
2265    assert_eq!(source, "definition inference");
2266    assert!(
2267      matches!(queried_person_type.as_ref(), CalcitTypeAnnotation::TypeRef(name, _) if name.as_ref() == "test-struct.main/Person"),
2268      "query type should expose the source-backed struct type: {queried_person_type}"
2269    );
2270
2271    let warnings = RefCell::new(vec![]);
2272    runner::preprocess::compile_source_def_for_snapshot("test-struct.main", "sum-point", &warnings, &CallStackList::default())
2273      .expect("sum-point should preprocess");
2274    let compiled = program::lookup_compiled_def("test-struct.main", "sum-point").expect("compiled sum-point");
2275    let sum_point_source = &snapshot.files["test-struct.main"].defs["sum-point"].code;
2276    let target = find_preprocessed_node_at_path(
2277      &compiled.preprocessed_code,
2278      sum_point_source,
2279      "test-struct.main",
2280      "sum-point",
2281      &[3, 1],
2282      true,
2283    )
2284    .expect("field access expression should retain a source path");
2285    let Calcit::List(field_access) = target else {
2286      panic!("field access should remain a call");
2287    };
2288    assert!(
2289      matches!(field_access.first(), Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructNth))),
2290      "typed tag access should specialize to struct nth, got {target}"
2291    );
2292    let source = parse_query_test_expression(":x p");
2293    let lowering = type_at_lowering(&source, Some(target));
2294    assert_eq!(lowering.status, "specialized");
2295    assert_eq!(lowering.kind, "nominal-struct-field");
2296    assert_eq!(lowering.source_head.as_deref(), Some(":x"));
2297    assert_eq!(lowering.lowered_head.as_deref(), Some("&struct:nth"));
2298  }
2299
2300  #[test]
2301  fn type_at_path_parser_accepts_semantic_code_prefixes() {
2302    assert_eq!(parse_type_at_path("code@3.2"), Ok(vec![3, 2]));
2303    assert_eq!(parse_type_at_path("@3.2"), Ok(vec![3, 2]));
2304    assert_eq!(parse_type_at_path("3.2"), Ok(vec![3, 2]));
2305  }
2306
2307  #[test]
2308  fn context_diagnostic_always_serializes_provenance_array() {
2309    let diagnostic = ContextDiagnostic {
2310      code: "W_TYPE_AT_UNRESOLVED".to_owned(),
2311      phase: "type-inference",
2312      severity: "warning",
2313      message: "unresolved".to_owned(),
2314      path: Some("code@1".to_owned()),
2315      intent: None,
2316      provenance: vec![],
2317    };
2318    let value = serde_json::to_value(&diagnostic).expect("diagnostic should serialize");
2319    assert_eq!(
2320      value["provenance"],
2321      serde_json::json!([]),
2322      "the documented contract requires an always-present provenance array"
2323    );
2324  }
2325
2326  fn parse_query_test_expression(source: &str) -> Calcit {
2327    let mut nodes = cirru_parser::parse(source).expect("test expression should parse");
2328    assert_eq!(nodes.len(), 1);
2329    code_to_calcit(&nodes.remove(0), "tests.type-at", "demo", vec![]).expect("test expression should convert")
2330  }
2331
2332  #[test]
2333  fn type_at_lowering_distinguishes_typed_specialization_from_direct_primitives() {
2334    let source = parse_query_test_expression("count xs");
2335    let processed = Calcit::from(vec![Calcit::Proc(calcit_core::CalcitProc::NativeListCount), Calcit::Number(1.0)]);
2336    assert_eq!(
2337      type_at_lowering(&source, Some(&processed)),
2338      TypeAtLowering {
2339        status: "specialized",
2340        kind: "typed-polymorphic-call",
2341        source_head: Some("count".to_owned()),
2342        lowered_head: Some("&list:count".to_owned()),
2343        detail:
2344          "Static receiver type selected a collection-specific primitive or core implementation, removing generic runtime dispatch."
2345            .to_owned(),
2346      }
2347    );
2348
2349    let direct = Calcit::from(vec![Calcit::Proc(calcit_core::CalcitProc::NativeListCount), Calcit::Number(1.0)]);
2350    let lowering = type_at_lowering(&direct, Some(&direct));
2351    assert_eq!(lowering.status, "unchanged");
2352    assert_eq!(lowering.kind, "core-expression");
2353  }
2354
2355  #[test]
2356  fn type_at_lowering_exposes_dynamic_method_dispatch() {
2357    let source = parse_query_test_expression(".show value");
2358    let lowering = type_at_lowering(&source, Some(&source));
2359    assert_eq!(lowering.status, "dynamic");
2360    assert_eq!(lowering.kind, "dynamic-method-dispatch");
2361    assert_eq!(lowering.source_head.as_deref(), Some(".show"));
2362    assert_eq!(lowering.lowered_head.as_deref(), Some(".show"));
2363  }
2364
2365  #[test]
2366  fn type_at_lowering_recognizes_postfix_method_heads() {
2367    let source = parse_query_test_expression("value .show");
2368    let lowering = type_at_lowering(&source, Some(&source));
2369    assert_eq!(lowering.status, "dynamic");
2370    assert_eq!(lowering.kind, "dynamic-method-dispatch");
2371    assert_eq!(lowering.source_head.as_deref(), Some(".show"));
2372    assert_eq!(lowering.lowered_head.as_deref(), Some(".show"));
2373  }
2374
2375  #[test]
2376  fn definition_return_schema_does_not_leak_into_nested_functions() {
2377    let mut nodes = cirru_parser::parse("fn ()\n  fn () 1").expect("test function should parse");
2378    let mut entry = snapshot::CodeEntry::from_code(nodes.remove(0));
2379    entry.schema = Arc::new(CalcitTypeAnnotation::from_function_parts(
2380      vec![],
2381      Arc::new(CalcitTypeAnnotation::String),
2382    ));
2383
2384    let root_expected = expected_type_at_path(&entry, None, "tests.type-at", "demo", &[2])
2385      .expect("root body should inherit the definition return schema");
2386    assert!(matches!(root_expected.0.as_ref(), CalcitTypeAnnotation::String));
2387    assert!(
2388      expected_type_at_path(&entry, None, "tests.type-at", "demo", &[2, 2]).is_none(),
2389      "nested fn body must use its own context rather than the enclosing definition schema"
2390    );
2391  }
2392
2393  #[test]
2394  fn definition_return_schema_propagates_into_if_branches() {
2395    let mut nodes = cirru_parser::parse("fn ()\n  if true (Option :none) (Option :none)").expect("test function should parse");
2396    let mut entry = snapshot::CodeEntry::from_code(nodes.remove(0));
2397    let option_number = Arc::new(CalcitTypeAnnotation::TypeRef(
2398      Arc::from("calcit.core/Option"),
2399      Arc::new(vec![Arc::new(CalcitTypeAnnotation::Number)]),
2400    ));
2401    entry.schema = Arc::new(CalcitTypeAnnotation::from_function_parts(vec![], option_number.clone()));
2402
2403    for path in [&[2, 2][..], &[2, 3][..]] {
2404      let (expected, source) = expected_type_at_path(&entry, None, "tests.type-at", "demo", path)
2405        .expect("each if result branch should inherit the definition return schema");
2406      assert_eq!(expected, option_number);
2407      assert_eq!(source, "if branch inherited from definition return schema");
2408    }
2409  }
2410
2411  #[test]
2412  fn type_at_does_not_borrow_global_schema_for_unresolved_shadowed_symbol() {
2413    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
2414    let snapshot = load_core_snapshot().expect("core snapshot should load");
2415    prepare_program_for_type_query_on_cli_stack(snapshot);
2416    assert!(
2417      !matches!(
2418        program::lookup_def_schema(calcit_core::calcit::CORE_NS, "count").as_ref(),
2419        CalcitTypeAnnotation::Dynamic
2420      ),
2421      "the regression requires a real same-named global schema"
2422    );
2423    let source = Calcit::Symbol {
2424      sym: Arc::from("count"),
2425      info: Arc::new(calcit_core::calcit::CalcitSymbolInfo {
2426        at_ns: Arc::from("tests.type-at"),
2427        at_def: Arc::from("demo"),
2428      }),
2429      location: None,
2430    };
2431
2432    assert!(
2433      infer_type_at_target(&source, None).is_none(),
2434      "a core function of the same name cannot prove an unresolved local symbol"
2435    );
2436    assert!(
2437      infer_type_at_target(&source, Some(&source)).is_none(),
2438      "an unlowered symbol is still not lexical binding evidence"
2439    );
2440
2441    let local = Calcit::Local(calcit_core::calcit::CalcitLocal {
2442      idx: 0,
2443      sym: Arc::from("count"),
2444      info: Arc::new(calcit_core::calcit::CalcitSymbolInfo {
2445        at_ns: Arc::from("tests.type-at"),
2446        at_def: Arc::from("demo"),
2447      }),
2448      location: None,
2449      type_info: Arc::new(CalcitTypeAnnotation::String),
2450    });
2451    let inferred = infer_type_at_target(&source, Some(&local)).expect("resolved local should retain its lexical type");
2452    assert!(matches!(inferred.as_ref(), CalcitTypeAnnotation::String));
2453  }
2454
2455  #[test]
2456  fn type_at_reports_expected_type_mismatches_without_rejecting_optional_values() {
2457    let mismatch = type_at_expected_mismatch_diagnostic(
2458      &CalcitTypeAnnotation::Number,
2459      &CalcitTypeAnnotation::String,
2460      "callable parameter",
2461      "code@3.1",
2462    )
2463    .expect("number should not satisfy string");
2464    assert_eq!(mismatch.code, "W_TYPE_AT_EXPECTED_MISMATCH");
2465    assert_eq!(mismatch.path.as_deref(), Some("code@3.1"));
2466
2467    assert!(
2468      type_at_expected_mismatch_diagnostic(
2469        &CalcitTypeAnnotation::Number,
2470        &CalcitTypeAnnotation::Nullable(
2471          Arc::new(CalcitTypeAnnotation::Number),
2472          calcit_core::calcit::NullableOrigin::Inferred
2473        ),
2474        "return schema",
2475        "code@3",
2476      )
2477      .is_none(),
2478      "a concrete number satisfies optional<number>"
2479    );
2480  }
2481}
2482
2483fn definition_type_query_target(target: &str) -> Option<(&str, &str)> {
2484  let (namespace, definition) = target.split_once('/')?;
2485  if namespace.is_empty() || definition.is_empty() || target.chars().any(char::is_whitespace) {
2486    None
2487  } else {
2488    Some((namespace, definition))
2489  }
2490}
2491
2492fn resolve_type_query_target(snapshot: &snapshot::Snapshot, target: &str) -> Result<(Arc<CalcitTypeAnnotation>, &'static str), String> {
2493  if let Some((namespace, definition)) = definition_type_query_target(target) {
2494    let file = snapshot
2495      .files
2496      .get(namespace)
2497      .ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
2498    if !file.defs.contains_key(definition) {
2499      return Err(format!("Definition `{target}` not found"));
2500    }
2501
2502    if let Some(trait_type) = runner::preprocess::resolve_source_trait_instance_type(namespace, definition) {
2503      return Ok((trait_type, "source trait definition"));
2504    }
2505
2506    let annotation = program::lookup_def_schema(namespace, definition);
2507    let is_data_definition_marker = matches!(
2508      annotation.as_ref(),
2509      CalcitTypeAnnotation::Custom(value)
2510        if matches!(value.as_ref(), Calcit::Tag(tag) if matches!(tag.ref_str(), "struct-def" | "enum-def"))
2511    );
2512    if !matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic) && !is_data_definition_marker {
2513      return Ok((annotation, "definition schema"));
2514    }
2515
2516    if is_data_definition_marker && let Some(inferred) = runner::preprocess::resolve_core_nominal_instance_type(namespace, definition) {
2517      return Ok((inferred, "resolved core nominal definition"));
2518    }
2519
2520    let symbol = code_to_calcit(&Cirru::Leaf(Arc::from(definition)), namespace, "&query:type", vec![])?;
2521    if let Some(inferred) = runner::preprocess::infer_static_type_from_expr(&symbol)
2522      && !matches!(inferred.as_ref(), CalcitTypeAnnotation::Dynamic)
2523    {
2524      // A named type query describes instances; expression inference keeps
2525      // the imported definition object distinct from those instances.
2526      if matches!(
2527        inferred.as_ref(),
2528        CalcitTypeAnnotation::StructDef(_) | CalcitTypeAnnotation::EnumDef(_)
2529      ) {
2530        return Ok((
2531          Arc::new(CalcitTypeAnnotation::TypeRef(Arc::from(target), Arc::new(vec![]))),
2532          "definition inference",
2533        ));
2534      }
2535      return Ok((inferred, "definition inference"));
2536    }
2537
2538    return Err(format!(
2539      "Definition `{target}` has neither an explicit schema nor an inferable static type. Add a schema or query a concrete type annotation such as `'Number`."
2540    ));
2541  }
2542
2543  Ok((parse_type_annotation_query(target)?, "type annotation"))
2544}
2545
2546pub fn format_type_query_annotation(annotation: &CalcitTypeAnnotation) -> Result<String, String> {
2547  let edn = annotation.to_type_edn();
2548  match snapshot::compact_type_display(&edn) {
2549    Some(Cirru::Leaf(name)) => return Ok(name.to_string()),
2550    Some(compact) => {
2551      return cirru_parser::format(std::slice::from_ref(&compact), true.into())
2552        .map(normalize_single_schema_display)
2553        .map_err(|error| format!("Failed to format resolved type: {error}"));
2554    }
2555    None => {}
2556  }
2557  cirru_edn::format(&edn, true)
2558    .map(|text| {
2559      let rendered = text.trim();
2560      rendered.strip_prefix("do ").unwrap_or(rendered).to_owned()
2561    })
2562    .map_err(|error| format!("Failed to format resolved type: {error}"))
2563}
2564
2565fn handle_type(input_path: &str, opts: &QueryTypeCommand, entry: Option<&str>) -> Result<(), String> {
2566  let format = parse_query_render_format(&opts.format)?;
2567  let snapshot = match definition_type_query_target(&opts.target) {
2568    Some((namespace, _)) if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" => load_core_snapshot()?,
2569    Some(_) => load_snapshot_with_entry(input_path, entry)?,
2570    None => load_core_snapshot()?,
2571  };
2572  prepare_program_for_type_query(&snapshot)?;
2573  let (annotation, source) = resolve_type_query_target(&snapshot, &opts.target)?;
2574  let rendered_type = format_type_query_annotation(annotation.as_ref())?;
2575  let methods = runner::preprocess::static_method_contracts(annotation.as_ref()).map(|items| {
2576    items
2577      .into_iter()
2578      .map(|(method, contract)| context_method(method, contract))
2579      .collect::<Vec<_>>()
2580  });
2581  let method_fingerprint = method_contract_fingerprint(&methods)?;
2582  let source_revision = definition_type_query_target(&opts.target)
2583    .and_then(|(namespace, definition)| snapshot.files.get(namespace).and_then(|file| file.defs.get(definition)))
2584    .map(snapshot::definition_revision)
2585    .transpose()?
2586    .unwrap_or_default();
2587  let revision = semantic_revision(&[&rendered_type, &method_fingerprint, &source_revision]);
2588
2589  let data = TypeQueryData {
2590    target: opts.target.clone(),
2591    canonical_type: rendered_type,
2592    resolved_from: source,
2593    methods,
2594  };
2595  let diagnostics = vec![];
2596
2597  if format != QueryRenderFormat::Human {
2598    let envelope = SemanticQueryEnvelope {
2599      schema_version: 1,
2600      command: "query.type",
2601      revision,
2602      data,
2603      diagnostics,
2604      next: vec![],
2605    };
2606    return emit_query_structured(&envelope, format, "type query result");
2607  }
2608
2609  println!("# Type\n\n- Resolved from: `{}`\n- Revision: `{revision}`\n", data.resolved_from);
2610  print!("{}", markdown_fenced_block("cirru", &data.canonical_type));
2611
2612  println!("\n## Methods\n");
2613  println!(
2614    "Call a method on a typed receiver. Each entry shows its origin, proof status and available type contract. A definition path is its implementation reference, not a second recommended call form. `open` or `ambiguous` does not prove a typed call; use `query def` for constructors and `docs read api-roles.md` for API roles.\n"
2615  );
2616  match data.methods {
2617    Some(methods) if methods.is_empty() => {
2618      println!("_No methods registered for this type._");
2619    }
2620    Some(methods) => {
2621      print!("{}", render_type_query_methods(&methods));
2622    }
2623    None => {
2624      println!("_This type has no statically resolvable method metadata._");
2625    }
2626  }
2627
2628  Ok(())
2629}
2630
2631fn parse_type_at_path(raw: &str) -> Result<Vec<usize>, String> {
2632  let path = raw.strip_prefix("code").unwrap_or(raw);
2633  parse_path(path)
2634}
2635
2636fn semantic_code_path(path: &[usize]) -> String {
2637  if path.is_empty() {
2638    "code".to_owned()
2639  } else {
2640    format!("code@{}", path.iter().map(usize::to_string).collect::<Vec<_>>().join("."))
2641  }
2642}
2643
2644pub fn format_cirru_expression(node: &Cirru) -> String {
2645  match node {
2646    Cirru::Leaf(value) => cirru_parser::generate_leaf(value),
2647    Cirru::List(_) => cirru_parser::format(std::slice::from_ref(node), true.into())
2648      .map(|text| text.trim().to_owned())
2649      .unwrap_or_else(|_| format!("{node:?}")),
2650  }
2651}
2652
2653fn calcit_direct_source_path(node: &Calcit, namespace: &str, definition: &str) -> Option<Vec<usize>> {
2654  let location = node.get_location()?;
2655  if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
2656    return None;
2657  }
2658  Some(location.coord.iter().map(|idx| *idx as usize).collect())
2659}
2660
2661/// Recover the source path represented by a preprocessed expression. Imports, procs and literals
2662/// do not carry locations, so list paths are derived from the nearest direct child that does.
2663/// Reader shorthand such as `'T` or `@x` expands one leaf into a two-item list whose located
2664/// child keeps the leaf's own coordinate, so that list takes the coordinate unchanged.
2665fn calcit_expression_source_path(node: &Calcit, source: &Cirru, namespace: &str, definition: &str) -> Option<Vec<usize>> {
2666  if let Some(path) = calcit_direct_source_path(node, namespace, definition) {
2667    return Some(path);
2668  }
2669  let Calcit::List(items) = node else {
2670    return None;
2671  };
2672  for (index, child) in items.iter().enumerate() {
2673    if let Some(mut child_path) = calcit_expression_source_path(child, source, namespace, definition) {
2674      let reader_expansion = items.len() == 2
2675        && index == 1
2676        && calcit_direct_source_path(child, namespace, definition).is_some()
2677        && source_leaf_expands_to_list(source, &child_path, namespace, definition);
2678      if !reader_expansion {
2679        child_path.pop();
2680      }
2681      return Some(child_path);
2682    }
2683  }
2684  None
2685}
2686
2687fn source_leaf_expands_to_list(source: &Cirru, path: &[usize], namespace: &str, definition: &str) -> bool {
2688  matches!(navigate_to_path(source, path), Ok(leaf @ Cirru::Leaf(_))
2689    if matches!(code_to_calcit(&leaf, namespace, definition, vec![]), Ok(Calcit::List(_))))
2690}
2691
2692pub(super) fn find_preprocessed_node_at_path<'a>(
2693  node: &'a Calcit,
2694  source: &Cirru,
2695  namespace: &str,
2696  definition: &str,
2697  target_path: &[usize],
2698  target_is_list: bool,
2699) -> Option<&'a Calcit> {
2700  let shape_matches = matches!(node, Calcit::List(_)) == target_is_list;
2701  if shape_matches
2702    && calcit_expression_source_path(node, source, namespace, definition)
2703      .as_deref()
2704      .is_some_and(|path| path == target_path)
2705  {
2706    return Some(node);
2707  }
2708
2709  if let Calcit::List(items) = node {
2710    for child in items.iter() {
2711      if let Some(found) = find_preprocessed_node_at_path(child, source, namespace, definition, target_path, target_is_list) {
2712        return Some(found);
2713      }
2714    }
2715  }
2716  None
2717}
2718
2719#[derive(Debug, Clone)]
2720struct StaticCallableSignature {
2721  arg_types: Vec<Arc<CalcitTypeAnnotation>>,
2722  rest_type: Option<Arc<CalcitTypeAnnotation>>,
2723}
2724
2725impl StaticCallableSignature {
2726  fn from_fn_annotation(annotation: &CalcitFnTypeAnnotation) -> Self {
2727    Self {
2728      arg_types: annotation.arg_types.clone(),
2729      rest_type: annotation.rest_type.clone(),
2730    }
2731  }
2732
2733  fn expected_arg(&self, index: usize) -> Option<Arc<CalcitTypeAnnotation>> {
2734    if let Some(value) = self.arg_types.get(index) {
2735      return match value.as_ref() {
2736        CalcitTypeAnnotation::Variadic(inner) => Some(inner.clone()),
2737        _ => Some(value.clone()),
2738      };
2739    }
2740    self.rest_type.clone().or_else(|| {
2741      self.arg_types.last().and_then(|value| match value.as_ref() {
2742        CalcitTypeAnnotation::Variadic(inner) => Some(inner.clone()),
2743        _ => None,
2744      })
2745    })
2746  }
2747}
2748
2749fn callable_signature_from_head(head: &Calcit) -> Option<StaticCallableSignature> {
2750  match head {
2751    Calcit::Proc(proc) => {
2752      let signature = proc.get_type_signature()?;
2753      Some(StaticCallableSignature {
2754        arg_types: signature.arg_types.clone(),
2755        rest_type: None,
2756      })
2757    }
2758    Calcit::Fn { info, .. } => Some(StaticCallableSignature {
2759      arg_types: info.arg_types.clone(),
2760      rest_type: info.rest_type.clone(),
2761    }),
2762    Calcit::Local(local) => local
2763      .type_info
2764      .resolve_to_fn()
2765      .map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
2766    Calcit::Import(import) => program::lookup_def_schema(&import.ns, &import.def)
2767      .resolve_to_fn()
2768      .map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
2769    Calcit::Symbol { sym, info, .. } => program::lookup_def_schema(&info.at_ns, sym)
2770      .resolve_to_fn()
2771      .map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
2772    _ => None,
2773  }
2774}
2775
2776/// Infer the type required by the target's parent context and describe the
2777/// source of that expectation for diagnostics.
2778fn expected_type_at_path(
2779  entry: &snapshot::CodeEntry,
2780  processed_root: Option<&Calcit>,
2781  namespace: &str,
2782  definition: &str,
2783  target_path: &[usize],
2784) -> Option<(Arc<CalcitTypeAnnotation>, String)> {
2785  let (&target_index, parent_path) = target_path.split_last()?;
2786  let parent_node = navigate_to_path(&entry.code, parent_path).ok()?;
2787  let Cirru::List(parent_items) = parent_node else {
2788    return None;
2789  };
2790  let head_name = parent_items.first().and_then(|head| match head {
2791    Cirru::Leaf(name) => Some(name.as_ref()),
2792    Cirru::List(_) => None,
2793  });
2794
2795  if parent_path.is_empty()
2796    && matches!(head_name, Some("defn" | "fn"))
2797    && target_index == parent_items.len().saturating_sub(1)
2798    && let CalcitTypeAnnotation::Fn(annotation) = entry.schema.as_ref()
2799  {
2800    return Some((annotation.return_type.clone(), "definition return schema".to_owned()));
2801  }
2802  if matches!(head_name, Some("if" | "&if")) && target_index == 1 {
2803    return Some((Arc::new(CalcitTypeAnnotation::Bool), "if condition".to_owned()));
2804  }
2805  if matches!(head_name, Some("if" | "&if")) && matches!(target_index, 2 | 3) {
2806    return expected_type_at_path(entry, processed_root, namespace, definition, parent_path)
2807      .map(|(expected, source)| (expected, format!("if branch inherited from {source}")));
2808  }
2809
2810  let processed_parent = processed_root.and_then(|root| {
2811    find_preprocessed_node_at_path(root, &entry.code, namespace, definition, parent_path, true).and_then(|node| match node {
2812      Calcit::List(items) => Some(items),
2813      _ => None,
2814    })
2815  })?;
2816
2817  if matches!(
2818    processed_parent.first(),
2819    Some(Calcit::Syntax(calcit_core::CalcitSyntax::AssertType, _))
2820  ) && target_index == 1
2821    && let Some(type_form) = processed_parent.get(2)
2822  {
2823    return Some((
2824      CalcitTypeAnnotation::parse_type_annotation_form(type_form),
2825      "assert-type annotation".to_owned(),
2826    ));
2827  }
2828
2829  let signature = callable_signature_from_head(processed_parent.first()?)?;
2830  let arg_index = target_index.checked_sub(1)?;
2831  signature
2832    .expected_arg(arg_index)
2833    .map(|expected| (expected, "callable parameter".to_owned()))
2834}
2835
2836/// Prefer processed static evidence. Unresolved source symbols cannot borrow
2837/// a same-named global schema.
2838pub(super) fn infer_type_at_target(source: &Calcit, processed: Option<&Calcit>) -> Option<Arc<CalcitTypeAnnotation>> {
2839  if let Calcit::Symbol { .. } = source {
2840    // A source symbol has no lexical resolution. A same-named definition is
2841    // not evidence when preprocessing failed or could not correlate the node.
2842    return processed
2843      .filter(|node| !matches!(node, Calcit::Symbol { .. }))
2844      .and_then(runner::preprocess::infer_static_type_from_expr);
2845  }
2846  processed
2847    .and_then(runner::preprocess::infer_static_type_from_expr)
2848    .or_else(|| runner::preprocess::infer_static_type_from_expr(source))
2849}
2850
2851/// Reuse type-at's lexical evidence for a read-only source inventory. A lowered
2852/// child is not evidence for a source call; calls need a unique compiler trace.
2853pub fn source_expression_type_at(
2854  root: &Cirru,
2855  source: &Cirru,
2856  namespace: &str,
2857  definition: &str,
2858  path: &[usize],
2859  evidence: &[runner::preprocess::SourceExpressionEvidence],
2860) -> Option<Arc<CalcitTypeAnnotation>> {
2861  if let Some(expression) = runner::preprocess::unique_source_expression_at_path(evidence, namespace, definition, path) {
2862    return expression.inferred_type.clone();
2863  }
2864  if matches!(source, Cirru::List(_)) {
2865    return None;
2866  }
2867  let source = code_to_calcit(
2868    source,
2869    namespace,
2870    definition,
2871    path.iter().map(|index| u16::try_from(*index)).collect::<Result<Vec<_>, _>>().ok()?,
2872  )
2873  .ok()?;
2874  if matches!(source, Calcit::List(_)) {
2875    return None;
2876  }
2877  let compiled = program::lookup_compiled_def(namespace, definition);
2878  let processed = compiled
2879    .as_ref()
2880    .and_then(|compiled| find_preprocessed_node_at_path(&compiled.preprocessed_code, root, namespace, definition, path, false));
2881  infer_type_at_target(&source, processed)
2882}
2883
2884fn type_at_evidence(node: &Calcit, path: &str, used_preprocessed: bool) -> TypeAtEvidence {
2885  let kind = match node {
2886    Calcit::Number(_) | Calcit::Str(_) | Calcit::Bool(_) | Calcit::Nil | Calcit::Tag(_) => "literal",
2887    Calcit::Local(_) => "local-binding",
2888    Calcit::Import(_) | Calcit::Symbol { .. } => "definition-schema",
2889    Calcit::Proc(_) => "proc-signature",
2890    Calcit::Fn { .. } => "function-schema",
2891    Calcit::List(items) => match items.first() {
2892      Some(Calcit::Proc(calcit_core::CalcitProc::List | calcit_core::CalcitProc::Set | calcit_core::CalcitProc::NativeMap)) => {
2893        "collection-literal"
2894      }
2895      Some(Calcit::Proc(_)) => "proc-return",
2896      Some(Calcit::Import(_) | Calcit::Symbol { .. }) => "definition-return",
2897      Some(Calcit::Local(_)) => "local-function-return",
2898      Some(Calcit::Method(_, _)) => "method-dispatch",
2899      Some(Calcit::Syntax(_, _)) => "syntax-rule",
2900      _ => "expression-synthesis",
2901    },
2902    _ => "value-shape",
2903  };
2904  TypeAtEvidence {
2905    kind: kind.to_owned(),
2906    detail: if used_preprocessed {
2907      "inferred from preprocessed code and lexical type metadata".to_owned()
2908    } else {
2909      "inferred from the selected source subtree; lexical bindings were unavailable".to_owned()
2910    },
2911    path: Some(path.to_owned()),
2912  }
2913}
2914
2915/// Find the definition the compiler resolved for one source symbol. Lexically
2916/// bound names never produce a resolved usage, and a source leaf that a macro
2917/// resolved to different definitions stays unresolved.
2918fn type_at_definition_reference(namespace: &str, definition: &str, path: &[usize]) -> Option<runner::preprocess::ResolvedSourceUsage> {
2919  let usages =
2920    runner::preprocess::trace_definition_source_usages(namespace, definition, &RefCell::new(vec![]), &CallStackList::default()).ok()?;
2921  let mut matching = usages.into_iter().filter(|usage| {
2922    usage.location.as_ref().is_some_and(|location| {
2923      location.ns.as_ref() == namespace
2924        && location.def.as_ref() == definition
2925        && location.coord.iter().map(|index| usize::from(*index)).eq(path.iter().copied())
2926    })
2927  });
2928  let selected = matching.next()?;
2929  matching
2930    .all(|usage| usage.target_ns == selected.target_ns && usage.target_def == selected.target_def)
2931    .then_some(selected)
2932}
2933
2934fn type_at_definition_reference_evidence(reference: &runner::preprocess::ResolvedSourceUsage, path: &str) -> TypeAtEvidence {
2935  let macro_origin = if reference.macro_origin.is_empty() {
2936    String::new()
2937  } else {
2938    format!(" inside the expansion of {}", reference.macro_origin.join(" -> "))
2939  };
2940  TypeAtEvidence {
2941    kind: "definition-schema".to_owned(),
2942    detail: format!(
2943      "declared contract of `{}/{}`, which the compiler resolved at this source path{macro_origin}; it describes the definition, not a call-site instantiation proof",
2944      reference.target_ns, reference.target_def
2945    ),
2946    path: Some(path.to_owned()),
2947  }
2948}
2949
2950fn type_at_call_head(node: &Calcit) -> Option<&Calcit> {
2951  match node {
2952    Calcit::List(items) => match (items.first(), items.get(1)) {
2953      (Some(head @ Calcit::Method(..)), _) => Some(head),
2954      (_, Some(head @ Calcit::Method(..))) => Some(head),
2955      (head, _) => head,
2956    },
2957    _ => None,
2958  }
2959}
2960
2961fn type_at_head_label(head: &Calcit) -> Option<String> {
2962  match head {
2963    Calcit::Proc(proc) => Some(proc.to_string()),
2964    Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
2965    Calcit::Symbol { sym, .. } | Calcit::Local(calcit_core::calcit::CalcitLocal { sym, .. }) => Some(sym.to_string()),
2966    Calcit::Method(..) => Some(head.turn_string()),
2967    Calcit::Tag(tag) => Some(format!(":{tag}")),
2968    Calcit::Syntax(syntax, _) => Some(syntax.to_string()),
2969    Calcit::StructDef(definition) => Some(definition.name.to_string()),
2970    Calcit::EnumDef(definition) => Some(definition.name().to_string()),
2971    Calcit::Fn { info, .. } => Some(info.name.to_string()),
2972    Calcit::Registered(name) => Some(name.to_string()),
2973    _ => None,
2974  }
2975}
2976
2977fn type_at_source_method(node: &Calcit) -> Option<String> {
2978  let Calcit::List(items) = node else {
2979    return None;
2980  };
2981  items.iter().take(2).find_map(|item| match item {
2982    Calcit::Method(name, calcit_core::calcit::MethodKind::Invoke(_)) => Some(format!(".{name}")),
2983    _ => None,
2984  })
2985}
2986
2987fn is_typed_collection_target(head: &Calcit) -> bool {
2988  match head {
2989    Calcit::Proc(proc) => {
2990      let name = proc.as_ref();
2991      name.starts_with("&list:")
2992        || name.starts_with("&map:")
2993        || name.starts_with("&set:")
2994        || name.starts_with("&str:")
2995        || name.starts_with("&enum:")
2996    }
2997    Calcit::Import(import) if import.ns.as_ref() == calcit_core::calcit::CORE_NS => {
2998      let name = import.def.as_ref();
2999      name.starts_with("&list:") || name.starts_with("&map:") || name.starts_with("&set:")
3000    }
3001    _ => false,
3002  }
3003}
3004
3005fn type_at_lowering(source: &Calcit, processed: Option<&Calcit>) -> TypeAtLowering {
3006  let source_head = type_at_call_head(source).and_then(type_at_head_label);
3007  let Some(processed) = processed else {
3008    return TypeAtLowering {
3009      status: "unavailable",
3010      kind: "preprocess-unavailable",
3011      source_head,
3012      lowered_head: None,
3013      detail: "No source-correlated preprocessed node was produced; inspect diagnostics before relying on runtime dispatch.".to_owned(),
3014    };
3015  };
3016  let processed_head = type_at_call_head(processed);
3017  let lowered_head = processed_head.and_then(type_at_head_label);
3018  let source_method = type_at_source_method(source);
3019
3020  let (status, kind, detail) = match processed_head {
3021    Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructNth)) => (
3022      "specialized",
3023      "nominal-struct-field",
3024      "The typed Struct field access was validated and lowered to indexed field access.",
3025    ),
3026    Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructGet)) => (
3027      "specialized",
3028      "struct-field",
3029      "The Struct field access was lowered to the core Struct primitive; indexed access needs a resolved nominal field layout.",
3030    ),
3031    Some(Calcit::Proc(calcit_core::CalcitProc::NativeStruct)) => (
3032      "specialized",
3033      "nominal-struct-constructor",
3034      "The Struct constructor was checked against its nominal definition and lowered to the core constructor primitive.",
3035    ),
3036    Some(Calcit::Proc(calcit_core::CalcitProc::NativeNamedEnumNew)) => (
3037      "specialized",
3038      "nominal-enum-constructor",
3039      "The Enum variant and payload were checked against the nominal definition and lowered to the core constructor primitive.",
3040    ),
3041    Some(Calcit::Proc(calcit_core::CalcitProc::NativeEnum)) => (
3042      "specialized",
3043      "anonymous-enum-constructor",
3044      "The anonymous Enum constructor was lowered to the core constructor primitive.",
3045    ),
3046    Some(head) if is_typed_collection_target(head) && source_head != lowered_head => (
3047      "specialized",
3048      "typed-polymorphic-call",
3049      "Static receiver type selected a collection-specific primitive or core implementation, removing generic runtime dispatch.",
3050    ),
3051    Some(Calcit::Method(
3052      _,
3053      calcit_core::calcit::MethodKind::ExternalAccess(_)
3054      | calcit_core::calcit::MethodKind::ExternalGet(_)
3055      | calcit_core::calcit::MethodKind::ExternalSet(_)
3056      | calcit_core::calcit::MethodKind::ExternalInvoke(_),
3057    )) => (
3058      "specialized",
3059      "typed-external-operation",
3060      "Static external-object type selected a backend-native property or method operation.",
3061    ),
3062    Some(Calcit::Method(_, calcit_core::calcit::MethodKind::Invoke(receiver)))
3063      if matches!(receiver.as_ref(), CalcitTypeAnnotation::Dynamic) =>
3064    {
3065      (
3066        "dynamic",
3067        "dynamic-method-dispatch",
3068        "The receiver type is still Dynamic, so the method cannot be lowered to a direct callable.",
3069      )
3070    }
3071    Some(Calcit::Method(_, calcit_core::calcit::MethodKind::Invoke(_))) => (
3072      "dynamic",
3073      "typed-method-dispatch",
3074      "The receiver type is known, but this method remains on the explicit dispatch path because no stable direct callable was selected.",
3075    ),
3076    Some(_) if source_method.is_some() && source_head != lowered_head => (
3077      "specialized",
3078      "static-method-call",
3079      "The typed method was resolved during preprocessing and lowered to a direct callable.",
3080    ),
3081    Some(_) if source_head != lowered_head => (
3082      "resolved",
3083      "static-call-resolution",
3084      "Preprocessing resolved the callable head, but no type-directed specialization was identified.",
3085    ),
3086    Some(_) => (
3087      "unchanged",
3088      "core-expression",
3089      "The expression already uses its final callable shape; no additional type-directed lowering was needed.",
3090    ),
3091    None if source_method.is_some() => (
3092      "specialized",
3093      "static-method-call",
3094      "The typed method was resolved and folded into a non-call expression during preprocessing.",
3095    ),
3096    None => (
3097      "resolved",
3098      "preprocessed-value",
3099      "Preprocessing produced a value rather than a callable expression.",
3100    ),
3101  };
3102
3103  TypeAtLowering {
3104    status,
3105    kind,
3106    source_head: source_method.or(source_head),
3107    lowered_head,
3108    detail: detail.to_owned(),
3109  }
3110}
3111
3112fn collect_type_at_bindings(node: &Calcit, values: &mut BTreeMap<String, (Arc<CalcitTypeAnnotation>, Option<String>)>) {
3113  match node {
3114    Calcit::Local(local) => {
3115      let path = local
3116        .location
3117        .as_ref()
3118        .map(|coord| semantic_code_path(&coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>()));
3119      let should_replace = values
3120        .get(local.sym.as_ref())
3121        .is_none_or(|(current, _)| matches!(current.as_ref(), CalcitTypeAnnotation::Dynamic));
3122      if should_replace {
3123        values.insert(local.sym.to_string(), (local.type_info.clone(), path));
3124      }
3125    }
3126    Calcit::List(items) => {
3127      for child in items.iter() {
3128        collect_type_at_bindings(child, values);
3129      }
3130    }
3131    _ => {}
3132  }
3133}
3134
3135fn format_type_at_bindings(processed_root: Option<&Calcit>, target: Option<&Calcit>) -> Result<Vec<TypeAtBinding>, String> {
3136  let mut values: BTreeMap<String, (Arc<CalcitTypeAnnotation>, Option<String>)> = BTreeMap::new();
3137  if let Some(Calcit::List(root_items)) = processed_root
3138    && let Some(Calcit::List(params)) = root_items.get(2)
3139  {
3140    collect_type_at_bindings(&Calcit::List(params.clone()), &mut values);
3141  }
3142  if let Some(target) = target {
3143    collect_type_at_bindings(target, &mut values);
3144  }
3145
3146  values
3147    .into_iter()
3148    .map(|(name, (annotation, path))| {
3149      Ok(TypeAtBinding {
3150        name,
3151        r#type: format_type_query_annotation(annotation.as_ref())?,
3152        path,
3153      })
3154    })
3155    .collect()
3156}
3157
3158pub fn type_at_confidence(annotation: Option<&CalcitTypeAnnotation>) -> &'static str {
3159  let Some(annotation) = annotation else {
3160    return "unknown";
3161  };
3162  if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
3163    return "unknown";
3164  }
3165  let rendered = annotation.to_brief_string();
3166  if rendered.contains("dynamic") || matches!(annotation, CalcitTypeAnnotation::DynFn | CalcitTypeAnnotation::Custom(_)) {
3167    "partial"
3168  } else if annotation.contains_type_var() {
3169    "generic"
3170  } else {
3171    "exact"
3172  }
3173}
3174
3175fn warning_matches_type_at(warning: &LocatedWarning, namespace: &str, definition: &str, path: &[usize]) -> bool {
3176  let location = warning.location();
3177  if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
3178    return false;
3179  }
3180  let warning_path = location.coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>();
3181  warning_path.starts_with(path) || path.starts_with(&warning_path)
3182}
3183
3184fn warning_to_context_diagnostic(warning: &LocatedWarning) -> ContextDiagnostic {
3185  ContextDiagnostic {
3186    code: warning.code().unwrap_or("W_PREPROCESS").to_owned(),
3187    phase: "type-check",
3188    severity: "warning",
3189    message: warning.message().to_owned(),
3190    path: Some(semantic_code_path(
3191      &warning.location().coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>(),
3192    )),
3193    intent: None,
3194    provenance: vec![],
3195  }
3196}
3197
3198fn type_at_expected_mismatch_diagnostic(
3199  actual: &CalcitTypeAnnotation,
3200  required: &CalcitTypeAnnotation,
3201  source: &str,
3202  path: &str,
3203) -> Option<ContextDiagnostic> {
3204  if actual.is_compatible_with(required) {
3205    return None;
3206  }
3207  Some(ContextDiagnostic {
3208    code: "W_TYPE_AT_EXPECTED_MISMATCH".to_owned(),
3209    phase: "type-check",
3210    severity: "warning",
3211    message: format!(
3212      "Inferred type `{}` does not satisfy expected type `{}` from {source}",
3213      actual.to_brief_string(),
3214      required.to_brief_string()
3215    ),
3216    path: Some(path.to_owned()),
3217    intent: None,
3218    provenance: vec![],
3219  })
3220}
3221
3222fn render_type_at_human(envelope: &SemanticQueryEnvelope<TypeAtData>) -> String {
3223  let data = &envelope.data;
3224  let mut out = String::new();
3225  let _ = writeln!(&mut out, "# Type at `{}`\n", data.id);
3226  let _ = writeln!(&mut out, "- Path: `{}`", data.path);
3227  let _ = writeln!(&mut out, "- Revision: `{}`", envelope.revision);
3228  let _ = writeln!(
3229    &mut out,
3230    "- Inferred type: `{}`",
3231    data.inferred_type.as_deref().unwrap_or("unknown")
3232  );
3233  if let Some(expected) = &data.expected_type {
3234    let _ = writeln!(
3235      &mut out,
3236      "- Expected type: `{}` ({})",
3237      expected,
3238      data.expected_from.as_deref().unwrap_or("static context")
3239    );
3240  }
3241  let _ = writeln!(&mut out, "- Confidence: `{}`", data.confidence);
3242  if let Some(intent) = data.dynamic_intent {
3243    let _ = writeln!(&mut out, "- Dynamic intent: `{intent}`");
3244  }
3245  let _ = writeln!(&mut out, "\n## Expression\n");
3246  out.push_str(&markdown_fenced_block("cirru", &data.expression));
3247  let _ = writeln!(
3248    &mut out,
3249    "\n## Lowering\n\n- Status: `{}`\n- Kind: `{}`",
3250    data.lowering.status, data.lowering.kind
3251  );
3252  let source_head = data.lowering.source_head.as_deref().unwrap_or("value");
3253  let lowered_head = data.lowering.lowered_head.as_deref().unwrap_or("value");
3254  let _ = writeln!(&mut out, "- Heads: `{source_head}` → `{lowered_head}`\n\n{}", data.lowering.detail);
3255  let _ = writeln!(&mut out, "\n## Evidence\n");
3256  for evidence in &data.evidence {
3257    let _ = writeln!(&mut out, "- `{}`: {}", evidence.kind, evidence.detail);
3258  }
3259  let _ = writeln!(
3260    &mut out,
3261    "\n## Bindings\n\n{} referenced/top-level binding(s); not a complete scope dump.",
3262    data.bindings.len()
3263  );
3264  for binding in &data.bindings {
3265    let location = binding.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
3266    let _ = writeln!(&mut out, "- `{}`: `{}`{}", binding.name, binding.r#type, location);
3267  }
3268  let _ = writeln!(&mut out, "\n## Static methods\n");
3269  match &data.static_methods {
3270    Some(methods) => {
3271      for method in methods {
3272        let _ = writeln!(&mut out, "{}", render_context_method(method));
3273      }
3274    }
3275    None => {
3276      let _ = writeln!(&mut out, "_Unknown._");
3277    }
3278  }
3279  let _ = writeln!(&mut out, "\n## Diagnostics\n\nCount: {}.", envelope.diagnostics.len());
3280  for diagnostic in &envelope.diagnostics {
3281    let location = diagnostic.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
3282    let _ = writeln!(
3283      &mut out,
3284      "- **{}** `{}`{}: {}",
3285      diagnostic.severity, diagnostic.code, location, diagnostic.message
3286    );
3287  }
3288  if !envelope.next.is_empty() {
3289    let _ = writeln!(&mut out, "\n## Next\n");
3290    for command in &envelope.next {
3291      let _ = writeln!(&mut out, "- `{command}`");
3292    }
3293  }
3294  out
3295}
3296
3297fn handle_type_at(input_path: &str, opts: &QueryTypeAtCommand, selected_entry: Option<&str>) -> Result<(), String> {
3298  let format = parse_query_render_format(&opts.format)?;
3299  let target_path = parse_type_at_path(&opts.path)?;
3300  let (namespace, requested_definition) = parse_target(&opts.target)?;
3301  let resolved_input = Path::new(input_path);
3302  calcit_core::validate_snapshot_path(resolved_input)?;
3303  let snapshot = if resolved_input.exists() {
3304    load_snapshot_with_entry(input_path, selected_entry)?
3305  } else if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
3306    load_core_snapshot()?
3307  } else {
3308    return Err(format!("{} does not exist", resolved_input.display()));
3309  };
3310  let file = snapshot
3311    .files
3312    .get(namespace)
3313    .ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
3314  let lookup = resolve_definition_lookup(namespace, requested_definition, file.defs.keys().map(String::as_str), true)?;
3315  if let Some(warning) = lookup.warning.as_deref() {
3316    print_cli_warning_block(warning);
3317  }
3318  let definition = lookup.resolved;
3319  let entry = file.defs.get(&definition).expect("resolved definition exists");
3320  let target_node = navigate_to_path(&entry.code, &target_path)?;
3321  let semantic_path = semantic_code_path(&target_path);
3322  let expression = format_cirru_expression(&target_node);
3323  let source_revision = snapshot::definition_revision(entry)?;
3324
3325  prepare_program_for_type_query(&snapshot)?;
3326  let warnings = RefCell::<Vec<LocatedWarning>>::new(vec![]);
3327  let compile_error =
3328    runner::preprocess::compile_source_def_for_snapshot(namespace, &definition, &warnings, &CallStackList::default()).err();
3329  let compiled = program::lookup_compiled_def(namespace, &definition);
3330  let processed_root = compiled.as_ref().map(|compiled| &compiled.preprocessed_code);
3331  let source_target = code_to_calcit(
3332    &target_node,
3333    namespace,
3334    &definition,
3335    target_path
3336      .iter()
3337      .map(|idx| u16::try_from(*idx).map_err(|_| format!("Path index {idx} exceeds Snapshot coordinate range")))
3338      .collect::<Result<Vec<_>, _>>()?,
3339  )?;
3340  let reader_expanded = matches!(target_node, Cirru::Leaf(_)) && matches!(source_target, Calcit::List(_));
3341  let source_method_call = matches!(&source_target, Calcit::List(items) if matches!(items.first(), Some(Calcit::Method(..))));
3342  let located_target = processed_root.and_then(|root| {
3343    find_preprocessed_node_at_path(
3344      root,
3345      &entry.code,
3346      namespace,
3347      &definition,
3348      &target_path,
3349      matches!(target_node, Cirru::List(_)),
3350    )
3351  });
3352  // Lowering can leave a child carrying the original call's coordinates.
3353  // A different call head is not proof that this child is the source call.
3354  let changed_call_head = matches!(
3355    type_at_call_head(&source_target),
3356    Some(Calcit::Symbol { .. } | Calcit::Import(_) | Calcit::Proc(_) | Calcit::Syntax(..) | Calcit::Tag(_))
3357  ) && matches!(target_node, Cirru::List(_))
3358    && located_target.is_some_and(|target| {
3359      type_at_call_head(&source_target).and_then(type_at_head_label) != type_at_call_head(target).and_then(type_at_head_label)
3360    });
3361  let generic_receiver = located_target
3362    .and_then(|target| infer_type_at_target(&source_target, Some(target)))
3363    .is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::TypeVar(_)));
3364  let needs_source_trace = reader_expanded || source_method_call || changed_call_head || generic_receiver;
3365  let traced = if compile_error.is_none() && (needs_source_trace || (located_target.is_none() && matches!(target_node, Cirru::List(_))))
3366  {
3367    runner::preprocess::trace_snapshot_source_expressions(
3368      &entry.code,
3369      namespace,
3370      &definition,
3371      &RefCell::new(vec![]),
3372      &CallStackList::default(),
3373    )
3374    .unwrap_or_default()
3375  } else {
3376    vec![]
3377  };
3378  let traced_target = runner::preprocess::unique_source_expression_at_path(&traced, namespace, &definition, &target_path);
3379  let processed_target = if needs_source_trace {
3380    traced_target.map(|item| &item.processed)
3381  } else {
3382    located_target.or_else(|| traced_target.map(|item| &item.processed))
3383  };
3384  let inference_target = processed_target.unwrap_or(&source_target);
3385  let inferred = traced_target
3386    .and_then(|item| item.inferred_type.clone())
3387    .or_else(|| infer_type_at_target(&source_target, processed_target));
3388  // Compiled imports carry no source coordinates, so a referenced definition
3389  // is recovered from the compiler's own resolution at this source leaf.
3390  let definition_reference = if inferred.is_none() && matches!(source_target, Calcit::Symbol { .. }) {
3391    type_at_definition_reference(namespace, &definition, &target_path)
3392  } else {
3393    None
3394  };
3395  let inferred = inferred.or_else(|| {
3396    definition_reference
3397      .as_ref()
3398      .and_then(|reference| runner::preprocess::infer_static_definition_type(&reference.target_ns, &reference.target_def))
3399  });
3400  let expected = expected_type_at_path(entry, processed_root, namespace, &definition, &target_path);
3401  let inferred_rendered = inferred
3402    .as_ref()
3403    .map(|annotation| format_type_query_annotation(annotation.as_ref()))
3404    .transpose()?;
3405  let (expected_rendered, expected_from) = match expected.as_ref() {
3406    Some((annotation, source)) => (Some(format_type_query_annotation(annotation.as_ref())?), Some(source.clone())),
3407    None => (None, None),
3408  };
3409  let methods = inferred.as_ref().and_then(|annotation| {
3410    traced_target
3411      .and_then(runner::preprocess::SourceExpressionEvidence::static_method_contracts)
3412      .or_else(|| runner::preprocess::static_method_contracts(annotation.as_ref()))
3413      .map(|items| {
3414        items
3415          .into_iter()
3416          .map(|(method, contract)| context_method(method, contract))
3417          .collect::<Vec<_>>()
3418      })
3419  });
3420  let method_fingerprint = method_contract_fingerprint(&methods)?;
3421  let revision = semantic_revision(&[&source_revision, &method_fingerprint]);
3422
3423  let fn_features = context_features(entry.schema.as_ref());
3424  let dynamic_intent = if inferred
3425    .as_ref()
3426    .is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic))
3427    && fn_features.iter().any(|feature| feature == "js-ffi")
3428  {
3429    Some("intentional-js-ffi")
3430  } else if inferred
3431    .as_ref()
3432    .is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic))
3433  {
3434    Some("unresolved")
3435  } else {
3436    None
3437  };
3438
3439  let mut diagnostics = warnings
3440    .borrow()
3441    .iter()
3442    .filter(|warning| warning_matches_type_at(warning, namespace, &definition, &target_path))
3443    .map(warning_to_context_diagnostic)
3444    .collect::<Vec<_>>();
3445  if let Some(error) = compile_error {
3446    diagnostics.push(ContextDiagnostic {
3447      code: error
3448        .code
3449        .clone()
3450        .unwrap_or_else(|| format!("E_{}", error.kind.to_string().to_uppercase())),
3451      phase: "preprocess",
3452      severity: "error",
3453      message: error.msg,
3454      path: error
3455        .location
3456        .as_ref()
3457        .map(|location| semantic_code_path(&location.coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>())),
3458      intent: None,
3459      provenance: *error.provenance,
3460    });
3461  }
3462  if inferred.is_none() {
3463    diagnostics.push(ContextDiagnostic {
3464      code: "W_TYPE_AT_UNRESOLVED".to_owned(),
3465      phase: "type-inference",
3466      severity: "warning",
3467      message: "Static inference could not determine a type for this expression without executing the program".to_owned(),
3468      path: Some(semantic_path.clone()),
3469      intent: dynamic_intent.map(str::to_owned),
3470      provenance: vec![],
3471    });
3472  }
3473  if let (Some(actual), Some((required, source))) = (inferred.as_ref(), expected.as_ref())
3474    && let Some(diagnostic) = type_at_expected_mismatch_diagnostic(actual.as_ref(), required.as_ref(), source, &semantic_path)
3475  {
3476    diagnostics.push(diagnostic);
3477  }
3478
3479  let mut evidence = vec![match definition_reference.as_ref() {
3480    Some(reference) => type_at_definition_reference_evidence(reference, &semantic_path),
3481    None => type_at_evidence(inference_target, &semantic_path, processed_target.is_some()),
3482  }];
3483  if let Some(source) = &expected_from {
3484    evidence.push(TypeAtEvidence {
3485      kind: "expected-context".to_owned(),
3486      detail: source.clone(),
3487      path: target_path
3488        .split_last()
3489        .map(|(_, parent)| semantic_code_path(parent))
3490        .or_else(|| Some("code".to_owned())),
3491    });
3492  }
3493  let bindings = format_type_at_bindings(processed_root, processed_target)?;
3494  let confidence = type_at_confidence(inferred.as_deref());
3495  let lowering = type_at_lowering(&source_target, processed_target);
3496  let data = TypeAtData {
3497    id: format!("{namespace}/{definition}"),
3498    path: semantic_path,
3499    expression,
3500    tree: cirru_to_json_value(&target_node),
3501    inferred_type: inferred_rendered,
3502    expected_type: expected_rendered,
3503    expected_from,
3504    confidence,
3505    dynamic_intent,
3506    evidence,
3507    bindings,
3508    bindings_complete: false,
3509    static_methods: methods,
3510    lowering,
3511  };
3512  let command_prefix = format!("calcit {}", shell_quote(input_path));
3513  let quoted_target = shell_quote(&format!("{namespace}/{definition}"));
3514  let tree_path = if target_path.is_empty() {
3515    String::new()
3516  } else {
3517    format!(" --path {}", shell_quote(&format_path(&target_path)))
3518  };
3519  let mut next = vec![format!("{command_prefix} tree show {quoted_target}{tree_path}")];
3520  if let Some(reference) = definition_reference.as_ref() {
3521    next.push(format!(
3522      "{command_prefix} query def {}",
3523      shell_quote(&format!("{}/{}", reference.target_ns, reference.target_def))
3524    ));
3525  }
3526  if confidence != "exact" {
3527    next.push(format!("{command_prefix} query schema {quoted_target}"));
3528    next.push(format!(
3529      "{command_prefix} analyze weak-types --ns {} --intent unresolved --format edn",
3530      shell_quote(namespace)
3531    ));
3532  }
3533  let envelope = SemanticQueryEnvelope {
3534    schema_version: TYPE_AT_SCHEMA_VERSION,
3535    command: "query.type-at",
3536    revision,
3537    data,
3538    diagnostics,
3539    next,
3540  };
3541
3542  match format {
3543    QueryRenderFormat::Human => print!("{}", render_type_at_human(&envelope)),
3544    QueryRenderFormat::Edn | QueryRenderFormat::Json => emit_query_structured(&envelope, format, "type-at result")?,
3545  }
3546  Ok(())
3547}
3548
3549fn char_prefix_if_truncated(text: &str, max_chars: usize) -> Option<&str> {
3550  text.char_indices().nth(max_chars).map(|(byte_index, _)| &text[..byte_index])
3551}
3552
3553fn truncate_chars(text: &str, max_chars: usize) -> (String, bool) {
3554  match char_prefix_if_truncated(text, max_chars) {
3555    Some(prefix) => (format!("{prefix}…"), true),
3556    None => (text.to_owned(), false),
3557  }
3558}
3559
3560fn truncate_chars_with_dots(text: &str, max_chars: usize) -> String {
3561  match char_prefix_if_truncated(text, max_chars) {
3562    Some(prefix) => format!("{prefix}..."),
3563    None => text.to_owned(),
3564  }
3565}
3566
3567fn count_cirru_nodes(node: &Cirru) -> usize {
3568  match node {
3569    Cirru::Leaf(_) => 1,
3570    Cirru::List(items) => 1 + items.iter().map(count_cirru_nodes).sum::<usize>(),
3571  }
3572}
3573
3574fn namespace_source(snapshot: &snapshot::Snapshot, namespace: &str) -> String {
3575  if calcit_core::calcit::is_bundled_core_ns(namespace) {
3576    "core".to_owned()
3577  } else if namespace == snapshot.package || namespace.starts_with(&format!("{}.", snapshot.package)) {
3578    "project".to_owned()
3579  } else {
3580    "dependency".to_owned()
3581  }
3582}
3583
3584fn js_ffi_owner(input_path: &str, snapshot: &snapshot::Snapshot, namespace: &str) -> Option<calcit_core::JsNamespaceSource> {
3585  let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
3586  if snapshot.files.contains_key(namespace) && namespace_source(snapshot, namespace) == "project" {
3587    return Some(calcit_core::JsNamespaceSource {
3588      module: snapshot.package.clone(),
3589      version: calcit_core::module_manifest_version(base_dir)
3590        .ok()
3591        .flatten()
3592        .unwrap_or_else(|| snapshot.version.clone()),
3593      root: base_dir.to_path_buf(),
3594    });
3595  }
3596  let module_folder = calcit_core::project_module_folder(base_dir);
3597  for module_path in &snapshot.active_entry().ok()?.modules {
3598    if let Ok(loaded) = load_module_with_sources_silent(module_path, base_dir, &module_folder)
3599      && let Some(owner) = loaded.namespace_sources.get(namespace)
3600    {
3601      return Some(owner.clone());
3602    }
3603  }
3604  None
3605}
3606
3607fn js_ffi_query_info(input_path: &str, snapshot: &snapshot::Snapshot, namespace: &str, ffi: &cirru_edn::Edn) -> Option<JsFfiQueryInfo> {
3608  snapshot::ffi_metadata_value(ffi, "js")?;
3609  let owner = js_ffi_owner(input_path, snapshot, namespace);
3610  let target = snapshot::parse_ffi_target(ffi)
3611    .ok()
3612    .flatten()
3613    .map(|target| target.as_str().to_owned());
3614  let (source_kind, source_file, modules, metadata_error) = match parse_js_source(ffi) {
3615    Ok(Some(source)) => {
3616      let (kind, file) = match source.source {
3617        JsFfiSource::Inline(_) => (Some("inline"), None),
3618        JsFfiSource::File { path } => (Some("file"), Some(path)),
3619      };
3620      (kind, file, source.modules.into_iter().collect(), None)
3621    }
3622    Ok(None) => (None, None, BTreeMap::new(), None),
3623    Err(error) => (None, None, BTreeMap::new(), Some(error)),
3624  };
3625  Some(JsFfiQueryInfo {
3626    target,
3627    owner_module: owner.as_ref().map(|source| source.module.clone()),
3628    owner_version: owner.as_ref().map(|source| source.version.clone()),
3629    module_root: owner.map(|source| source.root.canonicalize().unwrap_or(source.root).to_string_lossy().into_owned()),
3630    source_kind,
3631    source_file,
3632    modules,
3633    metadata_error,
3634  })
3635}
3636
3637fn render_js_ffi_info(info: &JsFfiQueryInfo, inline_source: Option<&str>) -> String {
3638  let mut out = String::new();
3639  let _ = writeln!(&mut out, "## JavaScript implementation\n");
3640  let _ = writeln!(&mut out, "- Target: `{}`", info.target.as_deref().unwrap_or("unknown"));
3641  let _ = writeln!(&mut out, "- Owner module: `{}`", info.owner_module.as_deref().unwrap_or("unknown"));
3642  let _ = writeln!(
3643    &mut out,
3644    "- Owner version: `{}`",
3645    info.owner_version.as_deref().unwrap_or("unknown")
3646  );
3647  if let Some(root) = &info.module_root {
3648    let _ = writeln!(&mut out, "- Module root: `{root}`");
3649  }
3650  if let Some(kind) = info.source_kind {
3651    let _ = writeln!(&mut out, "- Source kind: `{kind}`");
3652  }
3653  if let Some(file) = &info.source_file {
3654    let _ = writeln!(&mut out, "- Source file: `{file}` (relative to module root)");
3655  }
3656  if !info.modules.is_empty() {
3657    let _ = writeln!(&mut out, "- External modules:");
3658    for (alias, specifier) in &info.modules {
3659      let _ = writeln!(&mut out, "  - `{alias}` → `{specifier}`");
3660    }
3661  }
3662  if let Some(error) = &info.metadata_error {
3663    let _ = writeln!(&mut out, "- Metadata error: {error}");
3664  }
3665  let _ = writeln!(
3666    &mut out,
3667    "- Contract: the Fn schema is declared by the module author; it does not prove the JavaScript implementation."
3668  );
3669  if let Some(source) = inline_source {
3670    let _ = writeln!(&mut out, "\n### Inline JavaScript\n");
3671    out.push_str(&markdown_fenced_block("javascript", source));
3672  }
3673  out
3674}
3675
3676fn context_schema(annotation: &CalcitTypeAnnotation) -> Result<Option<String>, String> {
3677  match annotation {
3678    CalcitTypeAnnotation::Dynamic => Ok(None),
3679    CalcitTypeAnnotation::Fn(_) | CalcitTypeAnnotation::Macro(_) => Ok(Some(format_query_schema(annotation, true).trim().to_owned())),
3680    _ => Ok(Some(format_type_query_annotation(annotation)?)),
3681  }
3682}
3683
3684/// Like `context_schema`, but a written `Dynamic` stays visible.
3685fn definition_context_schema(schema: &Arc<CalcitTypeAnnotation>) -> Result<Option<String>, String> {
3686  match schema.as_ref() {
3687    CalcitTypeAnnotation::Dynamic if !snapshot::schema_annotation_is_missing(schema) => Ok(Some("Dynamic".to_owned())),
3688    annotation => context_schema(annotation),
3689  }
3690}
3691
3692fn context_features(annotation: &CalcitTypeAnnotation) -> Vec<String> {
3693  let mut features = match annotation {
3694    CalcitTypeAnnotation::Fn(fn_annot) => fn_annot
3695      .features
3696      .iter()
3697      .map(|feature| feature.ref_str().to_owned())
3698      .collect::<Vec<_>>(),
3699    CalcitTypeAnnotation::Macro(signature) => signature
3700      .features
3701      .iter()
3702      .map(|feature| feature.ref_str().to_owned())
3703      .collect::<Vec<_>>(),
3704    _ => vec![],
3705  };
3706  features.sort();
3707  features
3708}
3709
3710fn build_context_code(node: &Cirru, max_chars: usize) -> Result<ContextCode, String> {
3711  let nodes = count_cirru_nodes(node);
3712  let rendered = match node {
3713    Cirru::Leaf(value) => value.to_string(),
3714    Cirru::List(_) => cirru_parser::format(std::slice::from_ref(node), true.into())
3715      .map_err(|error| format!("Failed to format definition code: {error}"))?,
3716  };
3717  let (cirru, truncated) = truncate_chars(rendered.trim(), max_chars);
3718  let tree = if !truncated && nodes <= 180 {
3719    Some(cirru_to_json(node))
3720  } else {
3721    None
3722  };
3723  Ok(ContextCode {
3724    root: "code",
3725    nodes,
3726    cirru,
3727    tree,
3728    truncated,
3729  })
3730}
3731
3732fn build_context_examples(examples: &[Cirru], limit: usize, budget: usize) -> Result<ContextCollection<ContextExample>, String> {
3733  let returned_count = examples.len().min(limit);
3734  let per_example_budget = budget
3735    .checked_div(returned_count)
3736    .map(|value| value.clamp(120, 1200))
3737    .unwrap_or_default();
3738  let mut items = Vec::with_capacity(returned_count);
3739
3740  for (index, example) in examples.iter().take(returned_count).enumerate() {
3741    let nodes = count_cirru_nodes(example);
3742    let rendered = match example {
3743      Cirru::Leaf(value) => value.to_string(),
3744      Cirru::List(_) => cirru_parser::format(std::slice::from_ref(example), true.into())
3745        .map_err(|error| format!("Failed to format definition example {index}: {error}"))?,
3746    };
3747    let (cirru, truncated) = truncate_chars(rendered.trim(), per_example_budget);
3748    items.push(ContextExample {
3749      index,
3750      cirru,
3751      tree: if !truncated && nodes <= 100 {
3752        Some(cirru_to_json(example))
3753      } else {
3754        None
3755      },
3756      truncated,
3757    });
3758  }
3759
3760  Ok(ContextCollection::new(examples.len(), items))
3761}
3762
3763fn build_context_tests(tests: &[snapshot::TestEntry], limit: usize, budget: usize) -> Result<ContextCollection<ContextTest>, String> {
3764  let returned_count = tests.len().min(limit);
3765  let per_test_budget = budget
3766    .checked_div(returned_count)
3767    .map(|value| value.clamp(120, 1200))
3768    .unwrap_or_default();
3769  let mut items = Vec::with_capacity(returned_count);
3770  for test in tests.iter().take(returned_count) {
3771    let nodes = count_cirru_nodes(&test.code);
3772    let rendered = cirru_parser::format(std::slice::from_ref(&test.code), true.into())
3773      .map_err(|error| format!("Failed to format definition test `{}`: {error}", test.name))?;
3774    let (cirru, truncated) = truncate_chars(rendered.trim(), per_test_budget);
3775    let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
3776    tags.sort();
3777    items.push(ContextTest {
3778      name: test.name.clone(),
3779      tags,
3780      cirru,
3781      tree: if !truncated && nodes <= 100 {
3782        Some(cirru_to_json(&test.code))
3783      } else {
3784        None
3785      },
3786      truncated,
3787    });
3788  }
3789  Ok(ContextCollection::new(tests.len(), items))
3790}
3791
3792/// Core macros and syntax such as `fn`, `let` and `if` appear in almost every
3793/// definition, so the default context leaves them out.
3794fn is_core_syntax_dependency(id: &str, source: &str) -> bool {
3795  if source != "core" {
3796    return false;
3797  }
3798  let Some(name) = id.strip_prefix(&format!("{}/", calcit_core::calcit::CORE_NS)) else {
3799    return false;
3800  };
3801  calcit_core::calcit::CalcitSyntax::is_valid(name)
3802    || program::lookup_def_code(calcit_core::calcit::CORE_NS, name).is_some_and(|code| {
3803      matches!(&code, Calcit::List(items) if matches!(
3804        items.first(),
3805        Some(Calcit::Syntax(calcit_core::calcit::CalcitSyntax::Defmacro, _))
3806      ) || matches!(items.first(), Some(Calcit::Symbol { sym, .. }) if sym.as_ref() == "defmacro"))
3807    })
3808}
3809
3810fn collect_direct_dependencies(
3811  snapshot: &snapshot::Snapshot,
3812  namespace: &str,
3813  definition: &str,
3814) -> Result<Vec<(String, String)>, String> {
3815  let mut analyzer = CallTreeAnalyzer::new(CallTreeConfig {
3816    include_core: true,
3817    max_depth: 1,
3818    show_unused: false,
3819    package_name: Some(snapshot.package.clone()),
3820    ns_prefix: None,
3821  });
3822  let result = analyzer.analyze(namespace, definition)?;
3823  let mut dependencies = result
3824    .tree
3825    .calls
3826    .into_iter()
3827    .map(|node| (node.fqn, node.source))
3828    .collect::<Vec<_>>();
3829  dependencies.sort();
3830  dependencies.dedup_by(|left, right| left.0 == right.0);
3831  Ok(dependencies)
3832}
3833
3834fn context_usages(
3835  snapshot: &snapshot::Snapshot,
3836  namespace: &str,
3837  definition: &str,
3838  include_deps: bool,
3839  limit: usize,
3840) -> Result<ContextCollection<ContextUsage>, String> {
3841  let mut usages = collect_usages_from_snapshot(snapshot, namespace, definition, true)?
3842    .into_iter()
3843    .filter_map(|(usage_ns, usage_def, _context, coords, area)| {
3844      let source = namespace_source(snapshot, &usage_ns);
3845      if !include_deps && source != "project" {
3846        return None;
3847      }
3848      Some(ContextUsage {
3849        id: format!("{usage_ns}/{usage_def}"),
3850        source,
3851        area: area.to_owned(),
3852        paths: coords.iter().map(|path| format!("{area}{}", format_path(path))).collect(),
3853      })
3854    })
3855    .collect::<Vec<_>>();
3856  usages.sort_by(|left, right| (&left.id, &left.area).cmp(&(&right.id, &right.area)));
3857  let total = usages.len();
3858  usages.truncate(limit);
3859  Ok(ContextCollection::new(total, usages))
3860}
3861
3862fn context_docs(definition: &str, diagnostics: &mut Vec<ContextDiagnostic>) -> ContextCollection<ContextDocLink> {
3863  match super::docs::lookup_definition_docs(definition) {
3864    Ok(lookup) => {
3865      for (path, err) in lookup.unreadable_files {
3866        diagnostics.push(ContextDiagnostic {
3867          code: "I_DOC_INDEX_UNAVAILABLE".to_owned(),
3868          phase: "documentation",
3869          severity: "info",
3870          message: format!("Failed to read documentation file '{path}': {err}"),
3871          path: Some(path),
3872          intent: None,
3873          provenance: vec![],
3874        });
3875      }
3876      let total = lookup.links.len();
3877      let items = lookup
3878        .links
3879        .into_iter()
3880        .take(6)
3881        .map(|link| ContextDocLink {
3882          id: link.id,
3883          path: link.path,
3884          title: link.title,
3885          summary: link.summary,
3886        })
3887        .collect();
3888      ContextCollection::new(total, items)
3889    }
3890    Err(error) => {
3891      diagnostics.push(ContextDiagnostic {
3892        code: "I_DOC_INDEX_UNAVAILABLE".to_owned(),
3893        phase: "documentation",
3894        severity: "info",
3895        message: error.lines().next().unwrap_or(&error).to_owned(),
3896        path: None,
3897        intent: None,
3898        provenance: vec![],
3899      });
3900      ContextCollection::new(0, vec![])
3901    }
3902  }
3903}
3904
3905/// Static methods of the receiver type for `query context`, leaving out the generic Fn methods unless `include_core`.
3906fn context_methods(annotation: &CalcitTypeAnnotation, budget: usize, include_core: bool) -> Option<ContextCollection<ContextMethod>> {
3907  let mut methods = runner::preprocess::static_method_contracts(annotation)?;
3908  if !include_core {
3909    // Every function shares the generic Fn methods; they say nothing about this definition.
3910    methods.retain(|(descriptor, _)| !descriptor.origin.ends_with("/&core-fn-methods"));
3911  }
3912  let total = methods.len();
3913  let limit = (budget / 240).clamp(4, 80);
3914  let items = methods
3915    .into_iter()
3916    .take(limit)
3917    .map(|(method, contract)| context_method(method, contract))
3918    .collect::<Vec<_>>();
3919  Some(ContextCollection::new(total, items))
3920}
3921
3922fn weak_type_diagnostics(entry: &snapshot::CodeEntry, budget: usize) -> Vec<ContextDiagnostic> {
3923  let Some(row) =
3924    crate::type_coverage::analyze_weak_types_entry("context", "target", entry, &crate::type_coverage::WeakTypeKind::all())
3925  else {
3926    return vec![];
3927  };
3928
3929  let limit = (budget / 220).clamp(4, 24);
3930  let total = row.occurrences.len();
3931  let mut diagnostics = row
3932    .occurrences
3933    .into_iter()
3934    .take(limit)
3935    .map(|occurrence| {
3936      let intentional = matches!(
3937        occurrence.intent,
3938        crate::type_coverage::WeakTypeIntent::IntentionalJsFfi
3939          | crate::type_coverage::WeakTypeIntent::IntentionalMacroSyntax
3940          | crate::type_coverage::WeakTypeIntent::IntentionalTypeSlotDynamic
3941          | crate::type_coverage::WeakTypeIntent::IntentionalDecode
3942          | crate::type_coverage::WeakTypeIntent::IntentionalOpen
3943      );
3944      ContextDiagnostic {
3945        code: if intentional {
3946          "I_DYNAMIC_TYPE_INTENTIONAL".to_owned()
3947        } else {
3948          "W_DYNAMIC_TYPE_UNRESOLVED".to_owned()
3949        },
3950        phase: "static-analysis",
3951        severity: if intentional { "info" } else { "warning" },
3952        message: format!("{} ({})", occurrence.kind.as_str(), occurrence.detail),
3953        path: Some(occurrence.path),
3954        intent: Some(occurrence.intent.as_str().to_owned()),
3955        provenance: vec![],
3956      }
3957    })
3958    .collect::<Vec<_>>();
3959  if diagnostics.len() < total {
3960    diagnostics.push(ContextDiagnostic {
3961      code: "I_DIAGNOSTICS_TRUNCATED".to_owned(),
3962      phase: "static-analysis",
3963      severity: "info",
3964      message: format!(
3965        "{} additional weak-type diagnostic(s) omitted by the context budget",
3966        total - diagnostics.len()
3967      ),
3968      path: None,
3969      intent: None,
3970      provenance: vec![],
3971    });
3972  }
3973  diagnostics
3974}
3975
3976fn build_regular_context(
3977  snapshot: &snapshot::Snapshot,
3978  namespace: &str,
3979  definition: &str,
3980  entry: &snapshot::CodeEntry,
3981  opts: &QueryContextCommand,
3982) -> Result<SemanticQueryEnvelope<DefinitionContextData>, String> {
3983  let mut revision = snapshot::definition_revision(entry)?;
3984  let mut coverage = crate::type_coverage::analyze_code_entry(namespace, definition, entry);
3985  let intentional_ffi = context_features(entry.schema.as_ref()).iter().any(|feature| feature == "js-ffi");
3986  let mut diagnostics = weak_type_diagnostics(entry, opts.budget);
3987  if matches!(&entry.code, Cirru::Leaf(_)) {
3988    diagnostics.push(ContextDiagnostic {
3989      code: "I_SOURCE_BODY_UNAVAILABLE".to_owned(),
3990      phase: "source",
3991      severity: "info",
3992      message: "definition has a leaf placeholder rather than a source body".to_owned(),
3993      path: Some("code".to_owned()),
3994      intent: None,
3995      provenance: vec![],
3996    });
3997  }
3998  if coverage.level == crate::type_coverage::CoverageLevel::None && !intentional_ffi {
3999    diagnostics.insert(
4000      0,
4001      ContextDiagnostic {
4002        code: "W_TYPE_COVERAGE_NONE".to_owned(),
4003        phase: "static-analysis",
4004        severity: "warning",
4005        message: "definition has no trusted static type coverage".to_owned(),
4006        path: Some("schema".to_owned()),
4007        intent: None,
4008        provenance: vec![],
4009      },
4010    );
4011  }
4012  for issue in &coverage.schema_issues {
4013    diagnostics.push(ContextDiagnostic {
4014      code: "W_SCHEMA_MISMATCH".to_owned(),
4015      phase: "static-analysis",
4016      severity: "warning",
4017      message: issue.clone(),
4018      path: Some("schema".to_owned()),
4019      intent: None,
4020      provenance: vec![],
4021    });
4022  }
4023
4024  let metadata_ready = prepare_program_for_type_query(snapshot);
4025  let inferred_schema = if metadata_ready.is_ok() && snapshot::schema_annotation_is_missing(&entry.schema) {
4026    let warnings = RefCell::new(vec![]);
4027    let result = runner::preprocess::compile_source_def_for_snapshot(namespace, definition, &warnings, &CallStackList::default());
4028    diagnostics.extend(warnings.borrow().iter().map(warning_to_context_diagnostic));
4029    if let Err(error) = &result {
4030      diagnostics.push(ContextDiagnostic {
4031        code: error.code.clone().unwrap_or_else(|| "E_PREPROCESS".to_owned()),
4032        phase: "preprocess",
4033        severity: "error",
4034        message: error.msg.clone(),
4035        path: Some("code".to_owned()),
4036        intent: None,
4037        provenance: error.provenance.as_ref().clone(),
4038      });
4039    }
4040    if result.is_ok() && warnings.borrow().is_empty() {
4041      program::lookup_compiled_def(namespace, definition)
4042        .and_then(|compiled| runner::preprocess::infer_static_type_from_expr(&compiled.preprocessed_code))
4043        .filter(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Fn(_)))
4044    } else {
4045      None
4046    }
4047  } else {
4048    None
4049  };
4050  if let Some(schema) = &inferred_schema {
4051    let mut effective = entry.clone();
4052    effective.schema = schema.clone();
4053    coverage = crate::type_coverage::analyze_code_entry(namespace, definition, &effective);
4054    diagnostics = weak_type_diagnostics(&effective, opts.budget);
4055    diagnostics.push(ContextDiagnostic {
4056      code: "I_SCHEMA_INFERRED".to_owned(),
4057      phase: "preprocess",
4058      severity: "info",
4059      message: "Function contract is proven by ordinary preprocessing; no root schema was written to source".to_owned(),
4060      path: Some("code".to_owned()),
4061      intent: None,
4062      provenance: vec![],
4063    });
4064    revision = semantic_revision(&[&revision, &format_type_query_annotation(schema)?]);
4065  }
4066  if let Err(error) = &metadata_ready {
4067    diagnostics.push(ContextDiagnostic {
4068      code: "W_STATIC_METADATA_UNAVAILABLE".to_owned(),
4069      phase: "preprocess",
4070      severity: "warning",
4071      message: error.clone(),
4072      path: None,
4073      intent: None,
4074      provenance: vec![],
4075    });
4076  }
4077
4078  let dependencies = if metadata_ready.is_ok() {
4079    match collect_direct_dependencies(snapshot, namespace, definition) {
4080      Ok(items) => items,
4081      Err(error) => {
4082        diagnostics.push(ContextDiagnostic {
4083          code: "W_DEPENDENCY_ANALYSIS_FAILED".to_owned(),
4084          phase: "static-analysis",
4085          severity: "warning",
4086          message: error,
4087          path: Some("code".to_owned()),
4088          intent: None,
4089          provenance: vec![],
4090        });
4091        vec![]
4092      }
4093    }
4094  } else {
4095    vec![]
4096  };
4097  let dependencies = dependencies
4098    .into_iter()
4099    .filter(|(id, source)| opts.include_core || !is_core_syntax_dependency(id, source))
4100    .collect::<Vec<_>>();
4101  let dependency_total = dependencies.len();
4102  let dependency_items = dependencies
4103    .into_iter()
4104    .take(opts.dependency_limit)
4105    .map(|(id, source)| ContextDependency { id, source })
4106    .collect();
4107
4108  let mut tags = entry.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
4109  tags.sort();
4110  let doc_limit = (opts.budget / 6).clamp(160, 1200);
4111  let (doc, doc_truncated) = if entry.doc.trim().is_empty() {
4112    (None, false)
4113  } else {
4114    let (text, truncated) = truncate_chars(entry.doc.trim(), doc_limit);
4115    (Some(text), truncated)
4116  };
4117  let code = build_context_code(&entry.code, (opts.budget / 3).clamp(320, 2600))?;
4118  let examples = build_context_examples(&entry.examples, opts.example_limit, opts.budget / 4)?;
4119  let tests = build_context_tests(&entry.tests, opts.test_limit, opts.budget / 4)?;
4120  let usages = context_usages(snapshot, namespace, definition, opts.deps, opts.usage_limit)?;
4121  let id = format!("{namespace}/{definition}");
4122  let docs = context_docs(&id, &mut diagnostics);
4123  let effective_schema = inferred_schema.as_deref().unwrap_or_else(|| entry.schema.as_ref());
4124  let static_methods = if metadata_ready.is_ok() {
4125    context_methods(effective_schema, opts.budget / 3, opts.include_core)
4126  } else {
4127    None
4128  };
4129
4130  let layer = runner::preprocess::classify_code_entry(namespace, definition, entry);
4131  let data = DefinitionContextData {
4132    id,
4133    uri: format!("calcit://definition/{namespace}/{definition}"),
4134    source: namespace_source(snapshot, namespace),
4135    kind: coverage.kind.as_str().to_owned(),
4136    layer: layer.as_str(),
4137    coverage: if intentional_ffi && coverage.level == crate::type_coverage::CoverageLevel::None {
4138      "intentional-dynamic"
4139    } else {
4140      coverage.level.as_str()
4141    }
4142    .to_owned(),
4143    doc,
4144    doc_truncated,
4145    tags,
4146    schema: definition_context_schema(&entry.schema)?,
4147    inferred_schema: inferred_schema.as_ref().map(|schema| context_schema(schema)).transpose()?.flatten(),
4148    runtime_arity: core_runtime_call_arity(namespace, definition, entry),
4149    failure: core_proc_failure(namespace, definition, entry),
4150    features: context_features(effective_schema),
4151    js_ffi: None,
4152    code,
4153    examples,
4154    tests,
4155    dependencies: ContextCollection::new(dependency_total, dependency_items),
4156    usages,
4157    docs,
4158    static_methods,
4159  };
4160
4161  let mut next = vec![
4162    format!("calcit query schema {namespace}/{definition}"),
4163    format!("calcit docs search {definition}"),
4164  ];
4165  if data.code.truncated || data.code.tree.is_none() {
4166    next.push(format!("calcit query def {namespace}/{definition}"));
4167  }
4168  if data.examples.truncated {
4169    next.push(format!("calcit query def {namespace}/{definition} --only examples"));
4170  }
4171  if data.tests.truncated {
4172    next.push(format!("calcit query def {namespace}/{definition} --only tests"));
4173  }
4174  if data.usages.truncated {
4175    next.push(format!("calcit query usages {namespace}/{definition}"));
4176  }
4177
4178  Ok(SemanticQueryEnvelope {
4179    schema_version: 1,
4180    command: "query.context",
4181    revision,
4182    data,
4183    diagnostics,
4184    next,
4185  })
4186}
4187
4188fn build_special_builtin_context(
4189  snapshot: &snapshot::Snapshot,
4190  namespace: &str,
4191  definition: &str,
4192  meta: SpecialBuiltinQueryMeta,
4193  opts: &QueryContextCommand,
4194) -> Result<SemanticQueryEnvelope<DefinitionContextData>, String> {
4195  let schema = format_query_schema(meta.schema.as_ref(), true).trim().to_owned();
4196  let examples_fingerprint = meta
4197    .examples
4198    .iter()
4199    .map(|example| example.format_one_liner().unwrap_or_default())
4200    .collect::<Vec<_>>()
4201    .join("\n");
4202  let arity_fingerprint = meta.runtime_arity.map(render_runtime_call_arity).unwrap_or_default();
4203  let revision = semantic_revision(&[meta.doc, &schema, &examples_fingerprint, meta.cirru_note, &arity_fingerprint]);
4204  let tags = meta.semantic_tags.iter().map(|tag| (*tag).to_owned()).collect::<Vec<_>>();
4205  let intentional_ffi = meta.semantic_tags.contains(&"js-ffi");
4206  let (doc, doc_truncated) = truncate_chars(meta.doc, (opts.budget / 6).clamp(160, 1200));
4207  let usages = context_usages(snapshot, namespace, definition, opts.deps, opts.usage_limit)?;
4208  let examples = build_context_examples(&meta.examples, opts.example_limit, opts.budget / 4)?;
4209  let id = format!("{namespace}/{definition}");
4210  let mut diagnostics = vec![];
4211  let docs = context_docs(&id, &mut diagnostics);
4212
4213  let metadata_ready = prepare_program_for_type_query(snapshot).is_ok();
4214  let static_methods = if metadata_ready {
4215    context_methods(meta.schema.as_ref(), opts.budget / 3, opts.include_core)
4216  } else {
4217    None
4218  };
4219  let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags);
4220  let data = DefinitionContextData {
4221    id,
4222    uri: format!("calcit://definition/{namespace}/{definition}"),
4223    source: "core-builtin".to_owned(),
4224    kind: "proc".to_owned(),
4225    layer: layer.as_str(),
4226    coverage: if intentional_ffi { "intentional-dynamic" } else { "partial" }.to_owned(),
4227    doc: Some(doc),
4228    doc_truncated,
4229    tags: tags.clone(),
4230    schema: Some(schema),
4231    inferred_schema: None,
4232    runtime_arity: meta.runtime_arity,
4233    failure: None,
4234    features: tags,
4235    js_ffi: None,
4236    code: ContextCode {
4237      root: "code",
4238      nodes: 0,
4239      cirru: meta.cirru_note.to_owned(),
4240      tree: None,
4241      truncated: false,
4242    },
4243    examples,
4244    tests: ContextCollection::new(0, vec![]),
4245    dependencies: ContextCollection::new(0, vec![]),
4246    usages,
4247    docs,
4248    static_methods,
4249  };
4250  if intentional_ffi {
4251    diagnostics.insert(
4252      0,
4253      ContextDiagnostic {
4254        code: "I_DYNAMIC_TYPE_INTENTIONAL".to_owned(),
4255        phase: "static-analysis",
4256        severity: "info",
4257        message: "dynamic values are intentional at this JS FFI boundary".to_owned(),
4258        path: Some("schema".to_owned()),
4259        intent: Some("intentional-js-ffi".to_owned()),
4260        provenance: vec![],
4261      },
4262    );
4263  }
4264
4265  Ok(SemanticQueryEnvelope {
4266    schema_version: 1,
4267    command: "query.context",
4268    revision,
4269    data,
4270    diagnostics,
4271    next: vec![
4272      format!("calcit query def {namespace}/{definition}"),
4273      format!("calcit query def {namespace}/{definition} --only examples"),
4274    ],
4275  })
4276}
4277
4278fn render_context_human(envelope: &SemanticQueryEnvelope<DefinitionContextData>) -> String {
4279  let data = &envelope.data;
4280  let mut out = String::new();
4281  let _ = writeln!(&mut out, "# Definition context `{}`\n", data.id);
4282  let _ = writeln!(&mut out, "- Resource: `{}`", data.uri);
4283  let _ = writeln!(&mut out, "- Revision: `{}`", envelope.revision);
4284  let _ = writeln!(&mut out, "- Source: `{}`", data.source);
4285  let _ = writeln!(&mut out, "- Kind: `{}`", data.kind);
4286  let _ = writeln!(&mut out, "- Layer: `{}`", data.layer);
4287  let _ = writeln!(&mut out, "- Type coverage: `{}`", data.coverage);
4288  if let Some(arity) = data.runtime_arity {
4289    let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
4290  }
4291  if let Some(failure) = &data.failure {
4292    let _ = writeln!(&mut out, "- Failure: {}", render_proc_failure(failure));
4293  }
4294  if let Some(info) = &data.js_ffi {
4295    let _ = writeln!(&mut out, "- JavaScript FFI: `{}`", info.source_kind.unwrap_or("invalid"));
4296  }
4297  let _ = writeln!(
4298    &mut out,
4299    "- Tags: {}",
4300    if data.tags.is_empty() {
4301      "-".to_owned()
4302    } else {
4303      data.tags.iter().map(|tag| format!(":{tag}")).collect::<Vec<_>>().join(" ")
4304    }
4305  );
4306  let _ = writeln!(
4307    &mut out,
4308    "- Features: {}",
4309    if data.features.is_empty() {
4310      "-".to_owned()
4311    } else {
4312      data
4313        .features
4314        .iter()
4315        .map(|feature| format!(":{feature}"))
4316        .collect::<Vec<_>>()
4317        .join(" ")
4318    }
4319  );
4320
4321  let _ = writeln!(&mut out, "\n## Documentation\n");
4322  if let Some(doc) = &data.doc {
4323    for line in doc.lines() {
4324      let _ = writeln!(&mut out, "> {line}");
4325    }
4326    if data.doc_truncated {
4327      let _ = writeln!(&mut out, "\n_Truncated._");
4328    }
4329  } else {
4330    let _ = writeln!(&mut out, "_No documentation._");
4331  }
4332
4333  let _ = writeln!(&mut out, "\n## Schema\n");
4334  if let Some(schema) = &data.schema {
4335    out.push_str(&markdown_fenced_block("cirru", schema));
4336  } else {
4337    let _ = writeln!(&mut out, "_No explicit schema._");
4338  }
4339  if let Some(schema) = &data.inferred_schema {
4340    let _ = writeln!(&mut out, "\n## Inferred schema\n\n_Compiler evidence; not written to source._\n");
4341    out.push_str(&markdown_fenced_block("cirru", schema));
4342  }
4343
4344  if let Some(info) = &data.js_ffi {
4345    let _ = writeln!(&mut out);
4346    out.push_str(&render_js_ffi_info(info, None));
4347  }
4348
4349  let _ = writeln!(
4350    &mut out,
4351    "\n## Code preview\n\n- Nodes: {}{}\n",
4352    data.code.nodes,
4353    if data.code.truncated { " (truncated)" } else { "" }
4354  );
4355  out.push_str(&markdown_fenced_block("cirru", &data.code.cirru));
4356
4357  let _ = writeln!(
4358    &mut out,
4359    "\n## Examples\n\nReturned {}/{}{}.",
4360    data.examples.returned,
4361    data.examples.total,
4362    if data.examples.truncated { " (truncated)" } else { "" }
4363  );
4364  for example in &data.examples.items {
4365    let _ = writeln!(
4366      &mut out,
4367      "\n### Example {}{}\n",
4368      example.index,
4369      if example.truncated { " (truncated)" } else { "" }
4370    );
4371    out.push_str(&markdown_fenced_block("cirru", &example.cirru));
4372  }
4373
4374  let _ = writeln!(
4375    &mut out,
4376    "\n## Tests\n\nReturned {}/{}{}.",
4377    data.tests.returned,
4378    data.tests.total,
4379    if data.tests.truncated { " (truncated)" } else { "" }
4380  );
4381  for test in &data.tests.items {
4382    let tags = if test.tags.is_empty() {
4383      String::new()
4384    } else {
4385      format!(" [{}]", test.tags.iter().map(|tag| format!(":{tag}")).collect::<Vec<_>>().join(" "))
4386    };
4387    let _ = writeln!(
4388      &mut out,
4389      "\n### Test `{}`{}{}\n",
4390      test.name,
4391      tags,
4392      if test.truncated { " (truncated)" } else { "" }
4393    );
4394    out.push_str(&markdown_fenced_block("cirru", &test.cirru));
4395  }
4396
4397  let _ = writeln!(
4398    &mut out,
4399    "\n## Direct dependencies\n\nReturned {}/{}{}.",
4400    data.dependencies.returned,
4401    data.dependencies.total,
4402    if data.dependencies.truncated { " (truncated)" } else { "" }
4403  );
4404  for dependency in &data.dependencies.items {
4405    let _ = writeln!(&mut out, "- `{}` [{}]", dependency.id, dependency.source);
4406  }
4407
4408  let _ = writeln!(
4409    &mut out,
4410    "\n## Usages\n\nReturned {}/{}{}.",
4411    data.usages.returned,
4412    data.usages.total,
4413    if data.usages.truncated { " (truncated)" } else { "" }
4414  );
4415  for usage in &data.usages.items {
4416    let paths = if usage.paths.is_empty() {
4417      "-".to_owned()
4418    } else {
4419      usage.paths.join(", ")
4420    };
4421    let _ = writeln!(&mut out, "- `{}` [{}:{}] @ `{}`", usage.id, usage.source, usage.area, paths);
4422  }
4423
4424  let _ = writeln!(
4425    &mut out,
4426    "\n## Related docs\n\nReturned {}/{}{}.",
4427    data.docs.returned,
4428    data.docs.total,
4429    if data.docs.truncated { " (truncated)" } else { "" }
4430  );
4431  for doc in &data.docs.items {
4432    let title = doc.title.as_deref().unwrap_or("untitled");
4433    let summary = doc.summary.as_deref().map(|summary| format!(" — {summary}")).unwrap_or_default();
4434    let _ = writeln!(&mut out, "- `{}`: {} (`{}`){}", doc.id, title, doc.path, summary);
4435  }
4436
4437  let _ = writeln!(&mut out, "\n## Static methods\n");
4438  match &data.static_methods {
4439    Some(methods) => {
4440      let _ = writeln!(
4441        &mut out,
4442        "Returned {}/{}{}.",
4443        methods.returned,
4444        methods.total,
4445        if methods.truncated { " (truncated)" } else { "" }
4446      );
4447      for method in &methods.items {
4448        let _ = writeln!(&mut out, "{}", render_context_method(method));
4449      }
4450    }
4451    None => {
4452      let _ = writeln!(&mut out, "_Unknown._");
4453    }
4454  }
4455
4456  let _ = writeln!(&mut out, "\n## Diagnostics\n\nCount: {}.", envelope.diagnostics.len());
4457  for diagnostic in &envelope.diagnostics {
4458    let location = diagnostic.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
4459    let intent = diagnostic
4460      .intent
4461      .as_deref()
4462      .map(|intent| format!(" [{intent}]"))
4463      .unwrap_or_default();
4464    let _ = writeln!(
4465      &mut out,
4466      "- **{}** `{}`{}{}: {}",
4467      diagnostic.severity, diagnostic.code, intent, location, diagnostic.message
4468    );
4469  }
4470
4471  if !envelope.next.is_empty() {
4472    let _ = writeln!(&mut out, "\n## Next\n");
4473    for command in &envelope.next {
4474      let _ = writeln!(&mut out, "- `{command}`");
4475    }
4476  }
4477  out
4478}
4479
4480fn handle_context(input_path: &str, opts: &QueryContextCommand, selected_entry: Option<&str>) -> Result<(), String> {
4481  if opts.budget < 512 {
4482    return Err("Context budget must be at least 512 characters".to_owned());
4483  }
4484  let format = parse_query_render_format(&opts.format)?;
4485  let (namespace, requested_definition) = parse_target(&opts.target)?;
4486  let resolved_input = Path::new(input_path);
4487  calcit_core::validate_snapshot_path(resolved_input)?;
4488  let snapshot = if resolved_input.exists() {
4489    load_snapshot_with_entry(input_path, selected_entry)?
4490  } else if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
4491    load_core_snapshot()?
4492  } else {
4493    return Err(format!("{} does not exist", resolved_input.display()));
4494  };
4495  let file = snapshot
4496    .files
4497    .get(namespace)
4498    .ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
4499
4500  let mut envelope = if !file.defs.contains_key(requested_definition) {
4501    if let Some(meta) = lookup_special_builtin_query_meta(namespace, requested_definition)? {
4502      build_special_builtin_context(&snapshot, namespace, requested_definition, meta, opts)?
4503    } else {
4504      let lookup = resolve_definition_lookup(namespace, requested_definition, file.defs.keys().map(|name| name.as_str()), true)?;
4505      if let Some(warning) = lookup.warning.as_deref() {
4506        print_cli_warning_block(warning);
4507      }
4508      let entry = file.defs.get(&lookup.resolved).expect("resolved definition exists");
4509      build_regular_context(&snapshot, namespace, &lookup.resolved, entry, opts)?
4510    }
4511  } else {
4512    let entry = file.defs.get(requested_definition).expect("checked definition exists");
4513    build_regular_context(&snapshot, namespace, requested_definition, entry, opts)?
4514  };
4515
4516  if let Some((_, definition)) = envelope.data.id.split_once('/')
4517    && let Some(entry) = file.defs.get(definition)
4518    && let Some(ffi) = &entry.ffi
4519  {
4520    envelope.data.js_ffi = js_ffi_query_info(input_path, &snapshot, namespace, ffi);
4521    if envelope.data.js_ffi.is_some() {
4522      let command = format!("calcit query def {namespace}/{definition}");
4523      if !envelope.next.contains(&command) {
4524        envelope.next.push(command);
4525      }
4526    }
4527  }
4528
4529  match format {
4530    QueryRenderFormat::Human => print!("{}", render_context_human(&envelope)),
4531    QueryRenderFormat::Edn | QueryRenderFormat::Json => emit_query_structured(&envelope, format, "context query result")?,
4532  }
4533  Ok(())
4534}
4535
4536/// Load a module silently (without println)
4537fn load_module_silent(path: &str, base_dir: &Path, module_folder: &Path) -> Result<snapshot::Snapshot, String> {
4538  let previous = calcit_core::quiet_tool_output();
4539  calcit_core::set_quiet_tool_output(true);
4540  let result = calcit_core::load_module(path, base_dir, module_folder);
4541  calcit_core::set_quiet_tool_output(previous);
4542  result
4543}
4544
4545pub fn load_module_with_sources_silent(
4546  path: &str,
4547  base_dir: &Path,
4548  module_folder: &Path,
4549) -> Result<calcit_core::LoadedModuleSnapshot, String> {
4550  let previous = calcit_core::quiet_tool_output();
4551  calcit_core::set_quiet_tool_output(true);
4552  let result = calcit_core::load_module_with_sources(path, base_dir, module_folder);
4553  calcit_core::set_quiet_tool_output(previous);
4554  result
4555}
4556
4557fn load_snapshot(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
4558  load_snapshot_with_entry(input_path, entry)
4559}
4560
4561pub fn load_main_snapshot(input_path: &str) -> Result<snapshot::Snapshot, String> {
4562  let resolved_input_path = Path::new(input_path);
4563  calcit_core::validate_snapshot_path(resolved_input_path)?;
4564  let resolved_input_str = resolved_input_path.to_string_lossy().to_string();
4565  if !resolved_input_path.exists() {
4566    return Err(format!("{} does not exist", resolved_input_path.display()));
4567  }
4568
4569  let mut content = fs::read_to_string(resolved_input_path).map_err(|e| format!("Failed to read file: {e}"))?;
4570  strip_shebang(&mut content);
4571  let data = cirru_edn::parse(&content).map_err(|e| {
4572    eprintln!("\nFailed to parse file '{}':", resolved_input_path.display());
4573    eprintln!("{e}");
4574    format!("Failed to parse file '{}'", resolved_input_path.display())
4575  })?;
4576  let snapshot = snapshot::load_snapshot_data(&data, &resolved_input_str)?;
4577  let project_namespaces = snapshot.files.keys().cloned().collect::<HashSet<_>>();
4578  runner::preprocess::set_project_namespaces(&project_namespaces);
4579  Ok(snapshot)
4580}
4581
4582/// Prefer the project Snapshot for metadata-only queries. Dependencies and
4583/// core are loaded only when the requested namespace is not local; dependencies
4584/// come from the selected entry's modules (the default entry when `entry` is None).
4585/// An unknown entry is rejected even when the namespace is local.
4586fn load_snapshot_for_namespace(input_path: &str, namespace: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
4587  let mut main_snapshot = load_main_snapshot(input_path)?;
4588  if entry.is_some() {
4589    main_snapshot.select_entry(entry)?;
4590  }
4591  if main_snapshot.files.contains_key(namespace) {
4592    return Ok(main_snapshot);
4593  }
4594  if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
4595    return load_core_snapshot();
4596  }
4597  load_snapshot(input_path, entry)
4598}
4599
4600fn snapshot_search_sources(
4601  snapshot: &snapshot::Snapshot,
4602  source: SearchSource,
4603  module: Option<&str>,
4604) -> BTreeMap<String, (SearchSource, SearchOrigin)> {
4605  snapshot
4606    .files
4607    .keys()
4608    .map(|namespace| {
4609      (
4610        namespace.clone(),
4611        (
4612          source,
4613          SearchOrigin {
4614            package: snapshot.package.clone(),
4615            module: module.map(str::to_owned),
4616          },
4617        ),
4618      )
4619    })
4620    .collect()
4621}
4622
4623fn load_snapshot_for_search(input_path: &str, options: &SearchCommonOpts) -> Result<SearchCatalog, String> {
4624  let mut snapshot = load_main_snapshot(input_path)?;
4625  snapshot.select_entry(options.entry)?;
4626
4627  if options.source == SearchSource::Core {
4628    let snapshot = load_core_snapshot()?;
4629    let sources = snapshot_search_sources(&snapshot, SearchSource::Core, Some("builtin"));
4630    return Ok(SearchCatalog { snapshot, sources });
4631  }
4632
4633  let mut sources = snapshot_search_sources(&snapshot, SearchSource::Project, None);
4634  if options.source == SearchSource::Project {
4635    return Ok(SearchCatalog { snapshot, sources });
4636  }
4637  if options.source == SearchSource::All
4638    && options.entry.is_none()
4639    && let Some(filter) = options.filter
4640  {
4641    let namespace = filter.split_once('/').map(|(namespace, _)| namespace).unwrap_or(filter);
4642    if snapshot.files.contains_key(namespace) {
4643      return Ok(SearchCatalog { snapshot, sources });
4644    }
4645    if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
4646      let snapshot = load_core_snapshot()?;
4647      let sources = snapshot_search_sources(&snapshot, SearchSource::Core, Some("builtin"));
4648      return Ok(SearchCatalog { snapshot, sources });
4649    }
4650  }
4651
4652  let mut modules_to_load = snapshot.active_entry()?.modules.clone();
4653  let mut seen_modules = HashSet::new();
4654  modules_to_load.retain(|module_path| seen_modules.insert(module_path.to_owned()));
4655  let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
4656  let module_folder = calcit_core::project_module_folder(base_dir);
4657
4658  for module_path in &modules_to_load {
4659    match load_module_silent(module_path, base_dir, &module_folder) {
4660      Ok(module_snapshot) => {
4661        let module_package = module_snapshot.package.clone();
4662        let module_namespaces = module_snapshot.files.keys().cloned().collect::<Vec<_>>();
4663        calcit_core::merge_project_module_files(&mut snapshot, &module_snapshot, module_path)?;
4664        for namespace in module_namespaces {
4665          if snapshot.files.contains_key(&namespace) && !sources.contains_key(&namespace) {
4666            sources.insert(
4667              namespace,
4668              (
4669                SearchSource::Deps,
4670                SearchOrigin {
4671                  package: module_package.clone(),
4672                  module: Some(module_path.clone()),
4673                },
4674              ),
4675            );
4676          }
4677        }
4678      }
4679      Err(error) => eprintln!("Warning: Failed to load module '{module_path}': {error}"),
4680    }
4681  }
4682
4683  if options.source == SearchSource::All {
4684    let core_snapshot = load_core_snapshot()?;
4685    let core_package = core_snapshot.package.clone();
4686    for (namespace, file_data) in core_snapshot.files {
4687      if let std::collections::hash_map::Entry::Vacant(entry) = snapshot.files.entry(namespace.clone()) {
4688        sources.insert(
4689          namespace,
4690          (
4691            SearchSource::Core,
4692            SearchOrigin {
4693              package: core_package.clone(),
4694              module: Some("builtin".to_owned()),
4695            },
4696          ),
4697        );
4698        entry.insert(file_data);
4699      }
4700    }
4701  }
4702
4703  if options.source == SearchSource::Deps {
4704    snapshot
4705      .files
4706      .retain(|namespace, _| sources.get(namespace).is_some_and(|(source, _)| *source == SearchSource::Deps));
4707    sources.retain(|_, (source, _)| *source == SearchSource::Deps);
4708  }
4709
4710  Ok(SearchCatalog { snapshot, sources })
4711}
4712
4713pub fn load_snapshot_for_static_analysis(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
4714  load_snapshot_with_entry(input_path, entry)
4715}
4716
4717fn load_snapshot_with_entry(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
4718  let mut snapshot = load_main_snapshot(input_path)?;
4719  snapshot.select_entry(entry)?;
4720  let mut modules_to_load = snapshot.active_entry()?.modules.clone();
4721
4722  let mut seen_modules = HashSet::new();
4723  modules_to_load.retain(|module_path| seen_modules.insert(module_path.to_owned()));
4724
4725  // Load modules (dependencies) silently
4726  let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
4727  let module_folder = calcit_core::project_module_folder(base_dir);
4728
4729  for module_path in &modules_to_load {
4730    match load_module_silent(module_path, base_dir, &module_folder) {
4731      Ok(module_snapshot) => {
4732        calcit_core::merge_project_module_files(&mut snapshot, &module_snapshot, module_path)?;
4733      }
4734      Err(e) => {
4735        eprintln!("Warning: Failed to load module '{module_path}': {e}");
4736      }
4737    }
4738  }
4739
4740  // Merge calcit.core definitions from built-in calcit-core.cirru
4741  let core_snapshot = load_core_snapshot()?;
4742  for (ns_name, file_data) in core_snapshot.files {
4743    snapshot.files.entry(ns_name).or_insert(file_data);
4744  }
4745
4746  Ok(snapshot)
4747}
4748
4749/// Handle `query ns` - list namespaces or show ns details
4750fn handle_ns(
4751  input_path: &str,
4752  namespace: Option<&str>,
4753  include_deps: bool,
4754  format: StructuredOutputFormat,
4755  entry: Option<&str>,
4756) -> Result<(), String> {
4757  // If namespace is provided, show details (merged read-ns functionality)
4758  if let Some(ns_name) = namespace {
4759    return handle_ns_details(input_path, ns_name, format, entry);
4760  }
4761
4762  // Otherwise list all namespaces
4763  if !Path::new(input_path).exists() {
4764    return Err(format!("{input_path} does not exist"));
4765  }
4766
4767  let mut content = fs::read_to_string(input_path).map_err(|e| format!("Failed to read file: {e}"))?;
4768  strip_shebang(&mut content);
4769  let data = cirru_edn::parse(&content).map_err(|e| {
4770    eprintln!("\nFailed to parse file '{input_path}':");
4771    eprintln!("{e}");
4772    format!("Failed to parse file '{input_path}'")
4773  })?;
4774  let main_snapshot = snapshot::load_snapshot_data(&data, input_path)?;
4775  let main_package = main_snapshot.package.clone();
4776
4777  let snapshot = if include_deps {
4778    load_snapshot(input_path, entry)?
4779  } else {
4780    main_snapshot
4781  };
4782
4783  let mut namespaces: Vec<&String> = snapshot.files.keys().collect();
4784  namespaces.sort();
4785
4786  let filtered: Vec<_> = namespaces
4787    .iter()
4788    .filter(|ns| {
4789      if !include_deps {
4790        ns.as_str() == main_package || ns.starts_with(&format!("{main_package}."))
4791      } else {
4792        true
4793      }
4794    })
4795    .collect();
4796
4797  if format != StructuredOutputFormat::Human {
4798    let generated: Vec<_> = filtered.iter().filter(|ns| snapshot::is_generated_namespace(ns)).collect();
4799    return format.print_value(&serde_json::json!({
4800      "schema_version": 1,
4801      "command": "query.ns",
4802      "data": {
4803        "include_dependencies": include_deps,
4804        "count": filtered.len(),
4805        "namespaces": filtered,
4806        "generated": generated,
4807      },
4808    }));
4809  }
4810
4811  println!(
4812    "{} ({} namespaces)",
4813    if include_deps { "All namespaces:" } else { "Project namespaces:" }.bold(),
4814    filtered.len()
4815  );
4816
4817  for ns in &filtered {
4818    if snapshot::is_generated_namespace(ns) {
4819      println!("  {} {}", ns.cyan(), "(generated, not in Snapshot)".dimmed());
4820    } else {
4821      println!("  {}", ns.cyan());
4822    }
4823  }
4824
4825  Ok(())
4826}
4827
4828/// Print the namespace's `FileEntry` data as stored in the Snapshot, the input `edit ns` accepts.
4829fn handle_ns_cirru_view(input_path: &str, namespace: &str, entry: Option<&str>) -> Result<(), String> {
4830  if snapshot::is_generated_namespace(namespace) {
4831    return Err(format!(
4832      "Namespace '{namespace}' is generated at load time and is not stored in the Snapshot, so it has no FileEntry source to edit"
4833    ));
4834  }
4835  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
4836  let file_data = snapshot
4837    .files
4838    .get(namespace)
4839    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
4840  print!("{}", super::ns_view::render_ns_view(file_data)?);
4841  Ok(())
4842}
4843
4844/// Handle `query ns <namespace>` - show ns details
4845fn handle_ns_details(input_path: &str, namespace: &str, format: StructuredOutputFormat, entry: Option<&str>) -> Result<(), String> {
4846  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
4847
4848  let file_data = snapshot
4849    .files
4850    .get(namespace)
4851    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
4852  let generated = snapshot::is_generated_namespace(namespace);
4853
4854  if format != StructuredOutputFormat::Human {
4855    return format.print_value(&serde_json::json!({
4856      "schema_version": 1,
4857      "command": "query.ns",
4858      "data": {
4859        "namespace": namespace,
4860        "generated": generated,
4861        "doc": file_data.ns.doc,
4862        "ns_code": cirru_to_json_value(&file_data.ns.code),
4863        "definition_count": file_data.defs.len(),
4864      },
4865    }));
4866  }
4867
4868  if generated {
4869    println!("{}", "Generated at load time, not stored in the Snapshot.".dimmed());
4870  }
4871
4872  if !file_data.ns.doc.is_empty() {
4873    println!("{} {}", "Doc:".bold(), file_data.ns.doc);
4874  }
4875
4876  println!("\n{}", "NS declaration:".bold());
4877  let ns_str =
4878    cirru_parser::format(std::slice::from_ref(&file_data.ns.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
4879  println!("{}", ns_str.dimmed());
4880
4881  println!("\n{} {}", "Definitions:".bold(), file_data.defs.len());
4882
4883  Ok(())
4884}
4885
4886fn parse_query_tag(raw: &str) -> Result<EdnTag, String> {
4887  let trimmed = raw.trim();
4888  if trimmed.is_empty() {
4889    return Err("empty tag".to_string());
4890  }
4891  let name = trimmed.strip_prefix(':').unwrap_or(trimmed);
4892  if name.is_empty() {
4893    return Err(format!("invalid tag: {raw}"));
4894  }
4895  Ok(EdnTag::new(name))
4896}
4897
4898fn format_tags_display(tags: &HashSet<EdnTag>) -> String {
4899  let mut items: Vec<String> = tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect();
4900  items.sort();
4901  items.join(",")
4902}
4903
4904/// One-line signature for a namespace overview: the schema when declared,
4905/// otherwise the declaration head such as `defn greet (name)`.
4906fn definition_signature(entry: &snapshot::CodeEntry) -> String {
4907  if let Ok(Some(schema)) = definition_schema_cirru(&entry.schema, true)
4908    && let Ok(text) = format_query_schema_oneline(&schema)
4909  {
4910    return text;
4911  }
4912  let Cirru::List(items) = &entry.code else {
4913    return "(untyped)".to_owned();
4914  };
4915  // Keep the parameter list of function-like declarations; values such as a
4916  // `defref` initializer stay out of the overview.
4917  let takes_params = items
4918    .first()
4919    .is_some_and(|head| ["defn", "defmacro", "defcomp", "defeffect"].iter().any(|name| head.eq_leaf(name)));
4920  let keep = if takes_params && matches!(items.get(2), Some(Cirru::List(_))) {
4921    3
4922  } else {
4923    2
4924  };
4925  let head = Cirru::List(items.iter().take(keep).cloned().collect());
4926  let text = head.format_one_liner().unwrap_or_else(|_| "(untyped)".to_owned());
4927  format!("(untyped) {text}")
4928}
4929
4930fn handle_defs(input_path: &str, opts: &QueryDefsCommand, entry: Option<&str>) -> Result<(), String> {
4931  let format = parse_query_render_format(&opts.format)?;
4932  let filter_tag = opts.tag.as_deref().map(parse_query_tag).transpose()?;
4933  let namespace = &opts.namespace;
4934  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
4935
4936  let file_data = snapshot
4937    .files
4938    .get(namespace)
4939    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
4940
4941  let mut defs: Vec<&String> = file_data.defs.keys().collect();
4942  defs.sort();
4943  let total = defs.len();
4944
4945  if let Some(tag) = &filter_tag {
4946    defs.retain(|def| file_data.defs[*def].tags.contains(tag));
4947  }
4948
4949  if format != QueryRenderFormat::Human {
4950    let definitions = defs
4951      .iter()
4952      .map(|name| {
4953        let mut definition = serde_json::json!({ "name": name });
4954        if opts.signatures {
4955          definition["signature"] = serde_json::json!(definition_signature(&file_data.defs[*name]));
4956        }
4957        definition
4958      })
4959      .collect::<Vec<_>>();
4960    let data = serde_json::json!({
4961      "namespace": namespace,
4962      "count": defs.len(),
4963      "definition_count": total,
4964      "filters": {
4965        "tag": filter_tag.as_ref().map(EdnTag::ref_str),
4966        "signatures": opts.signatures,
4967      },
4968      "definitions": definitions,
4969    });
4970    let fingerprint = serde_json::to_string(&data).map_err(|error| format!("Failed to encode definition list: {error}"))?;
4971    return emit_query_structured(
4972      &SemanticQueryEnvelope {
4973        schema_version: 1,
4974        command: "query.defs",
4975        revision: semantic_revision(&["query.defs", &fingerprint]),
4976        data,
4977        diagnostics: vec![],
4978        next: vec![],
4979      },
4980      format,
4981      "definition list",
4982    );
4983  }
4984
4985  if let Some(tag) = &filter_tag {
4986    println!(
4987      "{} {} (filtered by {}, {} total)",
4988      "Definitions:".bold(),
4989      defs.len(),
4990      format!(":{}", tag.ref_str()).yellow(),
4991      total
4992    );
4993  } else {
4994    println!("{} {}", "Definitions:".bold(), defs.len());
4995  }
4996
4997  for def in &defs {
4998    let entry = &file_data.defs[*def];
4999    let tags_hint = if entry.tags.is_empty() {
5000      String::new()
5001    } else {
5002      format!(" [{}]", format_tags_display(&entry.tags))
5003    };
5004    let schema_hint = if opts.signatures {
5005      format!("  {}", definition_signature(entry))
5006    } else if !snapshot::schema_annotation_is_missing(&entry.schema) {
5007      " [schema]".to_owned()
5008    } else {
5009      String::new()
5010    };
5011    if !entry.doc.is_empty() {
5012      let doc_first_line = entry.doc.lines().next().unwrap_or("");
5013      let doc_display = truncate_chars_with_dots(doc_first_line, 50);
5014      println!(
5015        "  {}{}{} - {}",
5016        def.green(),
5017        tags_hint.yellow(),
5018        schema_hint.dimmed(),
5019        doc_display.dimmed()
5020      );
5021    } else {
5022      println!("  {}{}{}", def.green(), tags_hint.yellow(), schema_hint.dimmed());
5023    }
5024  }
5025
5026  Ok(())
5027}
5028
5029fn handle_config(input_path: &str, opts: &QueryConfigCommand) -> Result<(), String> {
5030  let format = parse_query_render_format(&opts.format)?;
5031  if format != QueryRenderFormat::Human {
5032    let command = ConfigCommand {
5033      subcommand: ConfigSubcommand::Show(ConfigShowCommand {
5034        entry: None,
5035        format: opts.format.clone(),
5036      }),
5037    };
5038    return super::config::handle_config_command(&command, input_path);
5039  }
5040  let snapshot = load_main_snapshot(input_path)?;
5041
5042  println!("# Project configuration\n");
5043  println!("Package: `{}`\n", snapshot.package);
5044  let deps_path = deps_path_for_snapshot(input_path);
5045  println!("Version: managed in `deps.cirru` (use `caps version get {deps_path}`).\n");
5046  println!("## Snapshot entries\n");
5047
5048  let mut names: Vec<&String> = snapshot.entries.keys().collect();
5049  names.sort();
5050
5051  for name in names {
5052    let entry = snapshot
5053      .entries
5054      .get(name)
5055      .ok_or_else(|| format!("Missing entry config for '{name}'"))?;
5056
5057    println!("### `{name}`\n");
5058    println!("- Mode: `{}`", entry.mode);
5059    println!("- Init: `{}`", entry.init_fn);
5060    println!("- Reload: `{}`", entry.reload_fn);
5061    println!("- Modules: `{:?}`", entry.modules);
5062    println!("- Type slots: `{:?}`\n", entry.type_slots);
5063  }
5064
5065  Ok(())
5066}
5067
5068fn handle_error(input_path: &str) -> Result<(), String> {
5069  let project_directory = project_state::project_directory_for_snapshot(input_path);
5070  let error_file = project_state::state_file(project_directory, ERROR_STATE_FILE);
5071  let legacy_error_file = project_directory.join(".calcit-error.cirru");
5072  let mut selected_file = None;
5073  for candidate in [&error_file, &legacy_error_file] {
5074    // Only an absent path permits fallback; a broken symlink or unreadable
5075    // current file must not silently reveal an older diagnostic instead.
5076    match fs::symlink_metadata(candidate) {
5077      Ok(_) => {
5078        selected_file = Some(candidate);
5079        break;
5080      }
5081      Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
5082        if let Some(parent) = candidate.parent() {
5083          match fs::symlink_metadata(parent) {
5084            Ok(metadata) if metadata.is_symlink() => {
5085              fs::metadata(parent).map_err(|error| format!("Failed to get metadata of error file: {error}"))?;
5086            }
5087            Ok(_) => {}
5088            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
5089            Err(error) => return Err(format!("Failed to get metadata of error file: {error}")),
5090          }
5091        }
5092      }
5093      Err(error) => return Err(format!("Failed to get metadata of error file: {error}")),
5094    }
5095  }
5096
5097  let Some(error_file) = selected_file else {
5098    println!("{}", "No .calcit/error.cirru file found.".yellow());
5099    if command_guidance_enabled() {
5100      println!();
5101      println!("{}", "Next steps:".blue().bold());
5102      println!("  • Start watcher: {} or {}", "calcit".cyan(), "calcit js".cyan());
5103      println!("  • Run syntax check: {}", "calcit --check-only".cyan());
5104    }
5105    return Ok(());
5106  };
5107
5108  let metadata = fs::metadata(error_file).map_err(|e| format!("Failed to get metadata of error file: {e}"))?;
5109  if let Ok(modified) = metadata.modified()
5110    && let Ok(elapsed) = modified.elapsed()
5111    && elapsed.as_secs() > 10
5112  {
5113    println!(
5114      "{}",
5115      format!("Warning: {} was modified {} seconds ago.", error_file.display(), elapsed.as_secs()).yellow()
5116    );
5117    println!("{}", "It might be outdated, please recompile or check the watcher.".yellow());
5118    println!();
5119  }
5120
5121  let content = fs::read_to_string(error_file).map_err(|e| format!("Failed to read error file: {e}"))?;
5122  if error_file == &legacy_error_file {
5123    eprintln!("Reading legacy error state from '{}' without moving it.", error_file.display());
5124  }
5125
5126  if content.trim().is_empty() {
5127    println!("{}", "✓ Error file is empty (no recent errors).".green());
5128    println!();
5129    println!("{}", "Your code compiled successfully!".dimmed());
5130    println!(
5131      "{}",
5132      "Note: this only reflects recent Calcit parsing/preprocess/runtime status; still validate browser rendering, CSS values, and external side effects separately."
5133        .dimmed()
5134    );
5135  } else {
5136    println!("{}", "Last error stack trace:".bold().red());
5137    println!("{content}");
5138    if command_guidance_enabled() {
5139      println!();
5140      println!("{}", "Next steps to fix:".blue().bold());
5141      println!("  • Search for error location: {} '<symbol>'", "calcit query search".cyan());
5142      println!("  • View definition: {} '<ns/def>'", "calcit query def".cyan());
5143      println!("  • Find usages: {} '<ns/def>'", "calcit query usages".cyan());
5144      println!();
5145      println!("{}", "Tip: After fixing, watcher will recompile automatically (~300ms).".dimmed());
5146    }
5147    println!(
5148      "{}",
5149      "Note: even when this clears, non-Calcit issues like CSS strings, DOM behavior, and external integrations can still be wrong."
5150        .dimmed()
5151    );
5152  }
5153
5154  Ok(())
5155}
5156
5157fn render_chunked_display(display: &ChunkedDisplay) -> String {
5158  let mut out = String::new();
5159  let _ = writeln!(&mut out, "## Chunked Cirru\n");
5160  let _ = writeln!(
5161    &mut out,
5162    "nodes: {}, branches: {}, leaves: {}, max depth: {}, fragments: {}\n",
5163    display.total.nodes,
5164    display.total.branches,
5165    display.total.leaves,
5166    display.total.max_depth,
5167    display.fragments.len()
5168  );
5169  let _ = writeln!(&mut out);
5170
5171  for fragment in &display.fragments {
5172    let _ = writeln!(&mut out, "### Fragment `{}`\n", fragment.id);
5173    let _ = writeln!(
5174      &mut out,
5175      "- Coordinate: `{}`\n- Nodes: {}\n- Max depth: {}\n",
5176      fragment.coord, fragment.nodes, fragment.depth
5177    );
5178    out.push_str(&markdown_fenced_block("cirru", &fragment.cirru));
5179    let _ = writeln!(&mut out);
5180  }
5181
5182  out
5183}
5184
5185/// Print only `quote $ <definition>`, the exact input `edit def --overwrite
5186/// --input-format cirru` accepts, so a read can be edited and written back.
5187fn handle_def_cirru_view(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
5188  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5189  let file_data = snapshot
5190    .files
5191    .get(namespace)
5192    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5193  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?;
5194  let code_entry = file_data
5195    .defs
5196    .get(lookup.resolved.as_str())
5197    .ok_or_else(|| format!("Definition '{namespace}/{definition}' has no source in this Snapshot"))?;
5198  let quoted = Cirru::List(vec![Cirru::Leaf(Arc::from("quote")), code_entry.code.clone()]);
5199  // Only print a view that parses back to the stored node, so writing it back is lossless.
5200  let text = [true, false]
5201    .into_iter()
5202    .filter_map(|use_inline| cirru_parser::format(std::slice::from_ref(&quoted), cirru_parser::CirruWriterOptions { use_inline }).ok())
5203    .find(|text| cirru_parser::parse(text).is_ok_and(|parsed| parsed == [quoted.clone()]))
5204    .ok_or_else(|| format!("Cannot render `{namespace}/{definition}` as Cirru text that parses back to the same source"))?;
5205  print!("{}", text.trim_start_matches('\n'));
5206  if !text.ends_with('\n') {
5207    println!();
5208  }
5209  Ok(())
5210}
5211
5212/// Show one definition as Markdown (chunked only when large), a summary preview
5213/// (`--summary`), an isolated section (`--only examples|tests`), a structured
5214/// envelope (`--format edn|json`), or writable source (`--format cirru`).
5215fn handle_def(input_path: &str, namespace: &str, definition: &str, opts: &QueryDefCommand, entry: Option<&str>) -> Result<(), String> {
5216  if opts.summary && opts.only.is_some() {
5217    return Err("`query def` accepts either `--summary` or `--only`, not both.".to_owned());
5218  }
5219  if let Some(only) = opts.only.as_deref()
5220    && !matches!(only, "examples" | "tests")
5221  {
5222    return Err(format!(
5223      "Unsupported `query def --only` value '{only}'. Expected `examples` or `tests`."
5224    ));
5225  }
5226  if opts.summary && (opts.format == "cirru" || opts.raw) {
5227    return Err("`query def --summary` cannot be combined with `--format cirru` or `--raw`.".to_owned());
5228  }
5229  if let Some(only) = opts.only.as_deref() {
5230    if opts.raw {
5231      return Err("`query def --only` cannot be combined with `--raw`.".to_owned());
5232    }
5233    if opts.format == "cirru" {
5234      return match only {
5235        "examples" => handle_examples_cirru_view(input_path, namespace, definition, entry),
5236        _ => Err(
5237          "`query def --only tests` cannot be combined with `--format cirru`; default human output already renders Cirru without JSON AST."
5238            .to_owned(),
5239        ),
5240      };
5241    }
5242  }
5243
5244  if opts.format == "cirru" {
5245    return handle_def_cirru_view(input_path, namespace, definition, entry);
5246  }
5247  let format = parse_query_render_format(&opts.format)?;
5248  if opts.summary && format == QueryRenderFormat::Human {
5249    return handle_peek(input_path, namespace, definition, entry);
5250  }
5251  match opts.only.as_deref() {
5252    Some("examples") if format == QueryRenderFormat::Human => return handle_examples(input_path, namespace, definition, entry),
5253    Some("tests") if format == QueryRenderFormat::Human => return handle_tests(input_path, namespace, definition, entry),
5254    _ => {}
5255  }
5256
5257  let structured = format != QueryRenderFormat::Human;
5258  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5259
5260  let file_data = snapshot
5261    .files
5262    .get(namespace)
5263    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5264
5265  if !file_data.defs.contains_key(definition)
5266    && let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
5267  {
5268    if structured {
5269      let schema = meta
5270        .schema
5271        .as_function()
5272        .map(|annot| annot.to_schema_edn())
5273        .unwrap_or(cirru_edn::Edn::Nil);
5274      let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
5275      let mut data = match opts.only.as_deref() {
5276        Some("examples") => serde_json::json!({
5277          "id": format!("{namespace}/{definition}"),
5278          "examples": meta.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
5279          "builtin": true,
5280          "kind": "special-proc",
5281        }),
5282        Some("tests") => serde_json::json!({
5283          "id": format!("{namespace}/{definition}"),
5284          "tests": [],
5285          "builtin": true,
5286          "kind": "special-proc",
5287        }),
5288        _ if opts.summary => serde_json::json!({
5289          "id": format!("{namespace}/{definition}"),
5290          "doc": meta.doc,
5291          "tags": meta.semantic_tags,
5292          "examples_count": meta.examples.len(),
5293          "tests_count": 0,
5294          "schema": cirru_to_json(&snapshot::schema_edn_to_cirru(&schema)?),
5295          "cases": schema_cases_lines(meta.schema.as_ref())?,
5296          "checker_rules": intrinsic_checker_rules(namespace, definition, meta.schema.as_ref()),
5297          "builtin": true,
5298          "kind": "special-proc",
5299          "layer": layer,
5300        }),
5301        _ => serde_json::json!({
5302          "id": format!("{namespace}/{definition}"),
5303          "doc": meta.doc,
5304          "tags": meta.semantic_tags,
5305          "examples": meta.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
5306          "tests": [],
5307          "code": null,
5308          "schema": cirru_to_json(&snapshot::schema_edn_to_cirru(&schema)?),
5309          "ffi": null,
5310          "ffi_edn": null,
5311          "builtin": true,
5312          "kind": "special-proc",
5313          "layer": layer,
5314        }),
5315      };
5316      if let Some(arity) = meta.runtime_arity {
5317        data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to encode runtime arity: {error}"))?;
5318      }
5319      return emit_def_query(data, None, format, None);
5320    }
5321    let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
5322    let mut out = String::new();
5323    let _ = writeln!(&mut out, "# Definition `{namespace}/{definition}`\n");
5324    let _ = writeln!(&mut out, "- Type: `{}`", meta.expr_preview);
5325    let _ = writeln!(&mut out, "- Layer: `{layer}`");
5326    if let Some(arity) = meta.runtime_arity {
5327      let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
5328    }
5329    let _ = writeln!(&mut out, "- Examples: {}", meta.examples.len());
5330    let _ = writeln!(&mut out, "\n## Documentation\n\n> {}", meta.doc);
5331    let _ = writeln!(&mut out, "\n## Schema\n");
5332    out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
5333    let _ = writeln!(&mut out, "\n## Cirru\n");
5334    out.push_str(&markdown_fenced_block("text", meta.cirru_note));
5335
5336    emit_cli_output(&out, false);
5337    return Ok(());
5338  }
5339
5340  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
5341  let render_to_stderr = lookup.warning.is_some();
5342  if let Some(warning) = lookup.warning.as_deref() {
5343    print_cli_warning_block(warning);
5344  }
5345  let resolved_definition = lookup.resolved;
5346
5347  let code_entry = file_data
5348    .defs
5349    .get(resolved_definition.as_str())
5350    .expect("resolved definition exists");
5351
5352  if !structured || !matches!(opts.only.as_deref(), Some("examples" | "tests")) {
5353    let _ = prepare_program_for_type_query(&snapshot);
5354  }
5355
5356  if structured {
5357    let revision = Some(snapshot::definition_revision(code_entry)?);
5358    if opts.only.as_deref() == Some("examples") {
5359      let data = serde_json::json!({
5360        "id": format!("{namespace}/{resolved_definition}"),
5361        "examples": code_entry.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
5362      });
5363      return emit_def_query(data, revision, format, None);
5364    }
5365    if opts.only.as_deref() == Some("tests") {
5366      let data = serde_json::json!({
5367        "id": format!("{namespace}/{resolved_definition}"),
5368        "tests": code_entry.tests.iter().map(|test| {
5369          let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
5370          tags.sort();
5371          serde_json::json!({"name": test.name, "tags": tags, "code": cirru_to_json(&test.code)})
5372        }).collect::<Vec<_>>(),
5373      });
5374      return emit_def_query(data, revision, format, None);
5375    }
5376    if opts.summary {
5377      let mut tags: Vec<String> = code_entry.tags.iter().map(|tag| tag.ref_str().to_string()).collect();
5378      tags.sort();
5379      let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
5380      let mut data = serde_json::json!({
5381        "id": format!("{namespace}/{resolved_definition}"),
5382        "layer": layer,
5383        "doc": code_entry.doc,
5384        "tags": tags,
5385        "schema": definition_schema_cirru(&code_entry.schema, false)?.map(|cirru| cirru_to_json(&cirru)),
5386        "cases": schema_cases_lines(code_entry.schema.as_ref())?,
5387        "checker_rules": intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref()),
5388        "examples_count": code_entry.examples.len(),
5389        "tests_count": code_entry.tests.len(),
5390      });
5391      if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
5392        data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to serialize runtime arity: {error}"))?;
5393      }
5394      if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
5395        data["failure"] = serde_json::to_value(failure).map_err(|error| format!("Failed to serialize failure class: {error}"))?;
5396      }
5397      return emit_def_query(data, revision, format, None);
5398    }
5399    let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
5400    let mut data = code_entry_to_json(code_entry)?;
5401    data["id"] = serde_json::json!(format!("{namespace}/{resolved_definition}"));
5402    data["layer"] = serde_json::json!(layer);
5403    if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
5404      data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to serialize runtime arity: {error}"))?;
5405    }
5406    if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
5407      data["failure"] = serde_json::to_value(failure).map_err(|error| format!("Failed to serialize failure class: {error}"))?;
5408    }
5409    data["ffi_edn"] = data["ffi"].take();
5410    data["ffi"] = serde_json::to_value(&code_entry.ffi).map_err(|e| format!("Failed to serialize FFI metadata: {e}"))?;
5411    data["js_ffi"] = serde_json::to_value(
5412      code_entry
5413        .ffi
5414        .as_ref()
5415        .and_then(|ffi| js_ffi_query_info(input_path, &snapshot, namespace, ffi)),
5416    )
5417    .map_err(|error| format!("Failed to serialize JavaScript FFI provenance: {error}"))?;
5418    return emit_def_query(data, revision, format, code_entry.ffi.as_ref());
5419  }
5420
5421  let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
5422  let mut out = String::new();
5423  let _ = writeln!(&mut out, "# Definition `{namespace}/{resolved_definition}`\n");
5424  let _ = writeln!(&mut out, "- Layer: `{layer}`");
5425  if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
5426    let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
5427  }
5428  if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
5429    let _ = writeln!(&mut out, "- Failure: {}", render_proc_failure(&failure));
5430  }
5431
5432  if let Ok(code_data) = calcit_core::data::cirru::code_to_calcit(&code_entry.code, namespace, &resolved_definition, vec![])
5433    && let Some(summary) = CalcitTypeAnnotation::summarize_code(&code_data)
5434  {
5435    let _ = writeln!(&mut out, "- Type: `{summary}`");
5436  }
5437
5438  let tags_text = format_tags_display(&code_entry.tags);
5439  if tags_text.is_empty() {
5440    let _ = writeln!(&mut out, "- Tags: _(none)_");
5441  } else {
5442    let _ = writeln!(&mut out, "- Tags: {tags_text}");
5443  }
5444
5445  if !code_entry.doc.is_empty() {
5446    let _ = writeln!(&mut out, "\n## Documentation\n");
5447    for line in code_entry.doc.lines() {
5448      let _ = writeln!(&mut out, "> {line}");
5449    }
5450  }
5451
5452  if let Some(ffi) = &code_entry.ffi {
5453    let full = format_ffi_edn(ffi)?;
5454    let (label, text) = if opts.raw {
5455      ("FFI:", full)
5456    } else {
5457      let preview = format_edn_display(ffi);
5458      (
5459        if preview == full {
5460          "FFI:"
5461        } else {
5462          "FFI (preview; use --raw for full metadata):"
5463        },
5464        preview,
5465      )
5466    };
5467    let _ = writeln!(&mut out, "\n## {}\n", label.trim_end_matches(':'));
5468    out.push_str(&markdown_fenced_block("cirru", &text));
5469    if let Some(info) = js_ffi_query_info(input_path, &snapshot, namespace, ffi) {
5470      let inline_source = parse_js_source(ffi)
5471        .ok()
5472        .flatten()
5473        .and_then(|implementation| match implementation.source {
5474          JsFfiSource::Inline(source) => Some(source),
5475          JsFfiSource::File { .. } => None,
5476        });
5477      let _ = writeln!(&mut out);
5478      out.push_str(&render_js_ffi_info(&info, inline_source.as_deref()));
5479    }
5480  }
5481
5482  if !code_entry.examples.is_empty() {
5483    let _ = writeln!(&mut out, "- Examples: {}", code_entry.examples.len());
5484  }
5485  if !code_entry.tests.is_empty() {
5486    let _ = writeln!(&mut out, "- Tests: {}", code_entry.tests.len());
5487  }
5488
5489  let _ = writeln!(&mut out, "\n## Schema\n");
5490  let schema_str = format_schema_display(definition_schema_cirru(&code_entry.schema, true));
5491  if schema_str == "(none)" {
5492    let _ = writeln!(&mut out, "_No explicit schema._");
5493  } else {
5494    out.push_str(&markdown_fenced_block("cirru", &schema_str));
5495  }
5496
5497  if !opts.raw {
5498    let chunk_options = ChunkDisplayOptions {
5499      trigger_nodes: opts.chunk_trigger_nodes,
5500      target_nodes: opts.chunk_target_nodes,
5501      max_nodes: opts.chunk_max_nodes,
5502      max_branches: 64,
5503    };
5504    let cirru_str =
5505      cirru_parser::format(std::slice::from_ref(&code_entry.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
5506    // Chunking only pays off for long source; short definitions read better whole.
5507    let chunked = if cirru_str.len() >= opts.chunk_trigger_bytes {
5508      maybe_chunk_node(&code_entry.code, &chunk_options)?
5509    } else {
5510      None
5511    };
5512    if let Some(display) = chunked {
5513      let _ = writeln!(&mut out);
5514      out.push_str(&render_chunked_display(&display));
5515    } else {
5516      let _ = writeln!(&mut out, "\n## Cirru\n");
5517      out.push_str(&markdown_fenced_block("cirru", &cirru_str));
5518    }
5519  } else {
5520    let _ = writeln!(&mut out, "\n## Cirru\n");
5521    let cirru_str =
5522      cirru_parser::format(std::slice::from_ref(&code_entry.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
5523    out.push_str(&markdown_fenced_block("cirru", &cirru_str));
5524  }
5525
5526  emit_cli_output(&out, render_to_stderr);
5527  Ok(())
5528}
5529
5530fn cirru_to_json(cirru: &Cirru) -> serde_json::Value {
5531  match cirru {
5532    Cirru::Leaf(s) => serde_json::Value::String(s.to_string()),
5533    Cirru::List(items) => serde_json::Value::Array(items.iter().map(cirru_to_json).collect()),
5534  }
5535}
5536
5537fn format_ffi_edn(ffi: &cirru_edn::Edn) -> Result<String, String> {
5538  cirru_edn::format(ffi, true)
5539    .map(|text| text.trim().to_owned())
5540    .map_err(|e| format!("Failed to format FFI metadata: {e}"))
5541}
5542
5543fn format_def_query_json(data: serde_json::Value, revision: Option<String>) -> Result<String, String> {
5544  serde_json::to_string(&serde_json::json!({
5545    "schema_version": 1,
5546    "command": "query.def",
5547    "revision": revision,
5548    "data": data,
5549    "diagnostics": [],
5550  }))
5551  .map_err(|e| format!("Failed to encode definition query JSON: {e}"))
5552}
5553
5554fn emit_def_query(
5555  mut data: serde_json::Value,
5556  revision: Option<String>,
5557  format: QueryRenderFormat,
5558  ffi: Option<&cirru_edn::Edn>,
5559) -> Result<(), String> {
5560  if format == QueryRenderFormat::Edn && ffi.is_some() {
5561    data
5562      .as_object_mut()
5563      .ok_or_else(|| "Definition query data must be an object".to_owned())?
5564      .remove("ffi");
5565  }
5566  let json = format_def_query_json(data, revision)?;
5567  match format {
5568    QueryRenderFormat::Json => println!("{json}"),
5569    QueryRenderFormat::Edn => {
5570      let json_value = serde_json::from_str::<serde_json::Value>(&json)
5571        .map_err(|error| format!("Failed to decode definition query result: {error}"))?;
5572      let mut value = json_value_to_edn(&json_value)?;
5573      if let Some(ffi) = ffi {
5574        let cirru_edn::Edn::Map(root) = &mut value else {
5575          return Err("Definition query envelope must be a map".to_owned());
5576        };
5577        let Some(cirru_edn::Edn::Map(data)) = root.0.get_mut(&cirru_edn::Edn::tag("data")) else {
5578          return Err("Definition query data must be a map".to_owned());
5579        };
5580        // The EDN form keeps FFI metadata native, not its JSON interoperability encoding.
5581        data.insert(cirru_edn::Edn::tag("ffi"), ffi.clone());
5582      }
5583      println!(
5584        "{}",
5585        cirru_edn::format(&value, true).map_err(|error| format!("Failed to format definition EDN: {error}"))?
5586      );
5587    }
5588    QueryRenderFormat::Human => return Err("Cannot emit human definition as structured output".to_owned()),
5589  }
5590  Ok(())
5591}
5592
5593fn code_entry_to_json(entry: &snapshot::CodeEntry) -> Result<serde_json::Value, String> {
5594  let schema_json = definition_schema_cirru(&entry.schema, false)?.map(|cirru| cirru_to_json(&cirru));
5595  let mut tags: Vec<String> = entry.tags.iter().map(|tag| tag.ref_str().to_string()).collect();
5596  tags.sort();
5597  Ok(serde_json::json!({
5598    "doc": entry.doc,
5599    "tags": tags,
5600    "examples": entry.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
5601    "tests": entry.tests.iter().map(|test| {
5602      let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
5603      tags.sort();
5604      serde_json::json!({"name": test.name, "tags": tags, "code": cirru_to_json(&test.code)})
5605    }).collect::<Vec<_>>(),
5606    "code": cirru_to_json(&entry.code),
5607    "schema": schema_json,
5608    "ffi": entry.ffi.as_ref().map(format_ffi_edn).transpose()?,
5609  }))
5610}
5611
5612fn format_example_node(example: &Cirru) -> String {
5613  match example {
5614    Cirru::Leaf(value) => value.to_string(),
5615    Cirru::List(_) => cirru_parser::format(std::slice::from_ref(example), true.into())
5616      .map(|text| text.trim().to_owned())
5617      .unwrap_or_else(|_| format!("{example:?}")),
5618  }
5619}
5620
5621fn render_examples_cirru(target: &str, examples: &[Cirru]) -> Result<String, String> {
5622  if examples.is_empty() {
5623    return Ok(String::new());
5624  }
5625  let quoted: Vec<Cirru> = examples
5626    .iter()
5627    .map(|example| Cirru::List(vec![Cirru::Leaf(Arc::from("quote")), example.clone()]))
5628    .collect();
5629  // Only print a view that parses back to the stored nodes, so `edit meta --examples` round-trips cleanly.
5630  let text = [true, false]
5631    .into_iter()
5632    .filter_map(|use_inline| cirru_parser::format(&quoted, cirru_parser::CirruWriterOptions { use_inline }).ok())
5633    .find(|text| cirru_parser::parse(text).is_ok_and(|parsed| parsed == quoted))
5634    .ok_or_else(|| format!("Cannot render `{target}` examples as Cirru text that parses back to the same source"))?;
5635  let mut out = text.trim_start_matches('\n').to_owned();
5636  if !out.ends_with('\n') {
5637    out.push('\n');
5638  }
5639  Ok(out)
5640}
5641
5642fn handle_examples_cirru_view(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
5643  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5644
5645  let file_data = snapshot
5646    .files
5647    .get(namespace)
5648    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5649
5650  if !file_data.defs.contains_key(definition)
5651    && let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
5652  {
5653    let text = render_examples_cirru(&format!("{namespace}/{definition}"), &meta.examples)?;
5654    print!("{text}");
5655    return Ok(());
5656  }
5657
5658  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?;
5659  let code_entry = file_data.defs.get(lookup.resolved.as_str()).expect("resolved definition exists");
5660
5661  let text = render_examples_cirru(&format!("{namespace}/{}", lookup.resolved), &code_entry.examples)?;
5662  print!("{text}");
5663  Ok(())
5664}
5665
5666fn render_examples_human(target: &str, examples: &[Cirru]) -> String {
5667  let mut out = String::new();
5668  let _ = writeln!(&mut out, "# Examples for `{target}`\n");
5669  if examples.is_empty() {
5670    let _ = writeln!(&mut out, "_No examples._");
5671    return out;
5672  }
5673  let _ = writeln!(&mut out, "Count: {}.\n", examples.len());
5674  for (index, example) in examples.iter().enumerate() {
5675    let _ = writeln!(&mut out, "## Example {index}\n");
5676    out.push_str(&markdown_fenced_block("cirru", &format_example_node(example)));
5677    let _ = writeln!(&mut out, "\n### JSON AST\n");
5678    out.push_str(&markdown_fenced_block(
5679      "json",
5680      &serde_json::to_string_pretty(&cirru_to_json(example)).unwrap(),
5681    ));
5682    let _ = writeln!(&mut out);
5683  }
5684  out
5685}
5686
5687// ═══════════════════════════════════════════════════════════════════════════════
5688// Progressive disclosure commands
5689// ═══════════════════════════════════════════════════════════════════════════════
5690
5691fn handle_examples(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
5692  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5693
5694  let file_data = snapshot
5695    .files
5696    .get(namespace)
5697    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5698
5699  if !file_data.defs.contains_key(definition)
5700    && let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
5701  {
5702    let out = render_examples_human(&format!("{namespace}/{definition}"), &meta.examples);
5703    emit_cli_output(&out, false);
5704    return Ok(());
5705  }
5706
5707  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
5708  let render_to_stderr = lookup.warning.is_some();
5709  if let Some(warning) = lookup.warning.as_deref() {
5710    print_cli_warning_block(warning);
5711  }
5712  let resolved_definition = lookup.resolved;
5713
5714  let code_entry = file_data
5715    .defs
5716    .get(resolved_definition.as_str())
5717    .expect("resolved definition exists");
5718
5719  let out = render_examples_human(&format!("{namespace}/{resolved_definition}"), &code_entry.examples);
5720  emit_cli_output(&out, render_to_stderr);
5721  Ok(())
5722}
5723
5724fn handle_tests(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
5725  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5726  let file = snapshot
5727    .files
5728    .get(namespace)
5729    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5730  if !file.defs.contains_key(definition) && lookup_special_builtin_query_meta(namespace, definition)?.is_some() {
5731    let out = format!("# Tests for `{namespace}/{definition}`\n\n_No tests._\n");
5732    emit_cli_output(&out, false);
5733    return Ok(());
5734  }
5735  let lookup = resolve_definition_lookup(namespace, definition, file.defs.keys().map(|name| name.as_str()), true)?;
5736  let render_to_stderr = lookup.warning.is_some();
5737  if let Some(warning) = lookup.warning.as_deref() {
5738    print_cli_warning_block(warning);
5739  }
5740  let entry = file.defs.get(lookup.resolved.as_str()).expect("resolved definition exists");
5741  let mut out = String::new();
5742  let _ = writeln!(&mut out, "# Tests for `{namespace}/{}`\n", lookup.resolved);
5743  if entry.tests.is_empty() {
5744    let _ = writeln!(&mut out, "_No tests._");
5745  } else {
5746    let _ = writeln!(&mut out, "Count: {}.\n", entry.tests.len());
5747    for test in &entry.tests {
5748      let mut tags = test.tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect::<Vec<_>>();
5749      tags.sort();
5750      let _ = writeln!(&mut out, "## Test `{}`\n", test.name);
5751      if !tags.is_empty() {
5752        let _ = writeln!(&mut out, "- Tags: {}\n", tags.join(" "));
5753      }
5754      out.push_str(&markdown_fenced_block("cirru", &format_example_node(&test.code)));
5755      let _ = writeln!(&mut out);
5756    }
5757  }
5758  emit_cli_output(&out, render_to_stderr);
5759  Ok(())
5760}
5761
5762/// Peek definition - show signature/params/doc without full body
5763fn handle_peek(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
5764  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5765
5766  let file_data = snapshot
5767    .files
5768    .get(namespace)
5769    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5770
5771  if !file_data.defs.contains_key(definition)
5772    && let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
5773  {
5774    let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
5775    let mut out = String::new();
5776    let _ = writeln!(&mut out, "# Definition preview `{namespace}/{definition}`\n");
5777    let _ = writeln!(&mut out, "- Layer: `{layer}`");
5778    if let Some(arity) = meta.runtime_arity {
5779      let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
5780    }
5781    let _ = writeln!(&mut out, "- Examples: {}", meta.examples.len());
5782    let _ = writeln!(&mut out, "\n## Documentation\n\n> {}", meta.doc);
5783    let _ = writeln!(&mut out, "\n## Expression\n");
5784    out.push_str(&markdown_fenced_block("cirru", meta.expr_preview));
5785    let _ = writeln!(&mut out, "\n## Schema\n");
5786    out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
5787    emit_cli_output(&out, false);
5788    return Ok(());
5789  }
5790
5791  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
5792  let render_to_stderr = lookup.warning.is_some();
5793  if let Some(warning) = lookup.warning.as_deref() {
5794    print_cli_warning_block(warning);
5795  }
5796  let resolved_definition = lookup.resolved;
5797
5798  let code_entry = file_data
5799    .defs
5800    .get(resolved_definition.as_str())
5801    .expect("resolved definition exists");
5802
5803  let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
5804  let mut out = String::new();
5805  let _ = writeln!(&mut out, "# Definition preview `{namespace}/{resolved_definition}`\n");
5806  let _ = writeln!(&mut out, "- Layer: `{layer}`\n");
5807
5808  if code_entry.doc.is_empty() {
5809    let _ = writeln!(&mut out, "_No documentation._");
5810  } else {
5811    let _ = writeln!(&mut out, "## Documentation\n");
5812    for line in code_entry.doc.lines() {
5813      let _ = writeln!(&mut out, "> {line}");
5814    }
5815  }
5816
5817  let _ = writeln!(&mut out, "\n## Expression preview\n");
5818  match &code_entry.code {
5819    Cirru::List(items) if !items.is_empty() => {
5820      let preview = code_entry.code.format_one_liner()?;
5821      let display = truncate_chars_with_dots(&preview, 120);
5822      out.push_str(&markdown_fenced_block("cirru", &display));
5823    }
5824    Cirru::Leaf(leaf) => {
5825      out.push_str(&markdown_fenced_block("cirru", leaf));
5826    }
5827    _ => {
5828      let _ = writeln!(&mut out, "_Empty or invalid definition._");
5829    }
5830  }
5831
5832  let _ = writeln!(&mut out, "\n- Examples: {}", code_entry.examples.len());
5833  let _ = writeln!(&mut out, "- Tests: {}", code_entry.tests.len());
5834
5835  let _ = writeln!(&mut out, "\n## Schema\n");
5836  if let Some(cirru) = definition_schema_cirru(&code_entry.schema, true)? {
5837    let preview = format_query_schema_oneline(&cirru)?;
5838    let display = truncate_chars_with_dots(&preview, 120);
5839    out.push_str(&markdown_fenced_block("cirru", &display));
5840  } else {
5841    let _ = writeln!(&mut out, "_No explicit schema._");
5842  }
5843  if let Some(cases) = schema_cases_lines(code_entry.schema.as_ref())? {
5844    write_schema_cases(&mut out, &cases);
5845  }
5846  if let Some(rules) = intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref()) {
5847    write_intrinsic_checker_rules(&mut out, rules);
5848  }
5849
5850  emit_cli_output(&out, render_to_stderr);
5851  Ok(())
5852}
5853
5854/// Show definition schema
5855fn handle_schema(
5856  input_path: &str,
5857  namespace: &str,
5858  definition: &str,
5859  format: StructuredOutputFormat,
5860  entry: Option<&str>,
5861) -> Result<(), String> {
5862  let structured = format != StructuredOutputFormat::Human;
5863  let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
5864
5865  let file_data = snapshot
5866    .files
5867    .get(namespace)
5868    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
5869
5870  if !file_data.defs.contains_key(definition)
5871    && let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
5872  {
5873    let mut out = String::new();
5874    if structured {
5875      let id = format!("{namespace}/{definition}");
5876      let schema_fingerprint = format_query_schema(meta.schema.as_ref(), true);
5877      let arity_fingerprint = meta.runtime_arity.map(render_runtime_call_arity).unwrap_or_default();
5878      format.print_json_text(&format_schema_query_json(
5879        &id,
5880        "core-builtin",
5881        meta.schema.as_ref(),
5882        semantic_revision(&[meta.doc, &schema_fingerprint, &arity_fingerprint]),
5883        meta.runtime_arity,
5884      )?)?;
5885      return Ok(());
5886    } else {
5887      let _ = writeln!(&mut out, "# Schema for `{namespace}/{definition}`\n");
5888      if let Some(arity) = meta.runtime_arity {
5889        let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`\n", render_runtime_call_arity(arity));
5890      }
5891      out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
5892    }
5893    emit_cli_output(&out, false);
5894    return Ok(());
5895  }
5896
5897  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
5898  let render_to_stderr = lookup.warning.is_some();
5899  if let Some(warning) = lookup.warning.as_deref() {
5900    print_cli_warning_block(warning);
5901  }
5902  let resolved_definition = lookup.resolved;
5903
5904  let code_entry = file_data
5905    .defs
5906    .get(resolved_definition.as_str())
5907    .expect("resolved definition exists");
5908
5909  let mut out = String::new();
5910
5911  let schema_cases = schema_cases_lines(code_entry.schema.as_ref())?;
5912  let checker_rules = intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref());
5913  if structured {
5914    let id = format!("{namespace}/{resolved_definition}");
5915    let text = format_schema_cirru_query_json(
5916      &id,
5917      &namespace_source(&snapshot, namespace),
5918      definition_schema_cirru(&code_entry.schema, true)?,
5919      snapshot::definition_revision(code_entry)?,
5920      None,
5921    )?;
5922    let text = if schema_cases.is_some() || checker_rules.is_some() {
5923      let mut envelope: serde_json::Value =
5924        serde_json::from_str(&text).map_err(|error| format!("Failed to decode schema query JSON: {error}"))?;
5925      if let Some(cases) = &schema_cases {
5926        envelope["data"]["cases"] = serde_json::json!(cases);
5927      }
5928      if let Some(rules) = checker_rules {
5929        envelope["data"]["checker_rules"] = serde_json::json!(rules);
5930      }
5931      serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode schema query JSON: {error}"))?
5932    } else {
5933      text
5934    };
5935    format.print_json_text(&text)?;
5936    return Ok(());
5937  }
5938
5939  if let Some(cirru) = definition_schema_cirru(&code_entry.schema, true)? {
5940    let _ = writeln!(&mut out, "# Schema for `{namespace}/{resolved_definition}`\n");
5941    out.push_str(&markdown_fenced_block("cirru", &format_query_schema_oneline(&cirru)?));
5942    if let Some(cases) = &schema_cases {
5943      write_schema_cases(&mut out, cases);
5944    }
5945    if let Some(rules) = checker_rules {
5946      write_intrinsic_checker_rules(&mut out, rules);
5947    }
5948  } else {
5949    let _ = writeln!(
5950      &mut out,
5951      "# Schema for `{namespace}/{resolved_definition}`\n\n_No explicit schema._"
5952    );
5953  }
5954
5955  emit_cli_output(&out, render_to_stderr);
5956  Ok(())
5957}
5958
5959/// Find symbol across all namespaces
5960fn handle_find(input_path: &str, symbol: &str, include_deps: bool, detail_offset: usize, entry: Option<&str>) -> Result<(), String> {
5961  let snapshot = load_snapshot(input_path, entry)?;
5962
5963  let mut found_definitions: Vec<(String, String)> = vec![];
5964  let mut found_references: RefResults = vec![]; // (ns, def, context, coords, source)
5965
5966  for (ns_name, file_data) in &snapshot.files {
5967    let is_core = ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.");
5968
5969    // Always search for definitions in all namespaces (including core)
5970    if file_data.defs.contains_key(symbol) {
5971      found_definitions.push((ns_name.clone(), symbol.to_string()));
5972    }
5973
5974    // Search for references only in project namespaces (unless --deps)
5975    if !include_deps && is_core {
5976      continue;
5977    }
5978
5979    // Search for references in all definitions
5980    for (def_name, code_entry) in &file_data.defs {
5981      if find_symbol_in_cirru(&code_entry.code, symbol) {
5982        let coords = find_symbol_coords(&code_entry.code, symbol);
5983        found_references.push((
5984          ns_name.clone(),
5985          def_name.clone(),
5986          get_symbol_context_cirru(&code_entry.code, symbol),
5987          coords,
5988          "code",
5989        ));
5990      }
5991
5992      if let Ok(Some(schema)) = query_schema_cirru(code_entry.schema.as_ref(), false)
5993        && find_symbol_in_cirru(&schema, symbol)
5994      {
5995        let coords = find_symbol_coords(&schema, symbol);
5996        found_references.push((
5997          ns_name.clone(),
5998          def_name.clone(),
5999          get_symbol_context_cirru(&schema, symbol),
6000          coords,
6001          "schema",
6002        ));
6003      }
6004    }
6005  }
6006
6007  // Print summary
6008  println!(
6009    "{} {} definition(s), {} reference(s)\n",
6010    "Matches:".bold(),
6011    found_definitions.len(),
6012    found_references.len().saturating_sub(found_definitions.len())
6013  );
6014
6015  // Print definitions
6016  if !found_definitions.is_empty() {
6017    println!("{}", "Defined in:".bold().green());
6018    print_detail_window_hint(found_definitions.len(), detail_offset, "definitions");
6019    for (idx, (ns, def)) in found_definitions.iter().enumerate() {
6020      if in_detail_window(idx, found_definitions.len(), detail_offset) {
6021        println!("  {}/{}", ns.cyan(), def.green());
6022      } else {
6023        println!("  ⋯ {}/{}", ns.dimmed(), def.dimmed());
6024      }
6025    }
6026    println!();
6027  }
6028
6029  // Print references (excluding the definition itself)
6030  let references: Vec<_> = found_references
6031    .iter()
6032    .filter(|(ns, def, _, _, _)| !found_definitions.iter().any(|(dns, ddef)| dns == ns && ddef == def))
6033    .collect();
6034
6035  if !references.is_empty() {
6036    println!("{}", "Referenced in:".bold());
6037    print_detail_window_hint(references.len(), detail_offset, "references");
6038    for (idx, (ns, def, context, coords, source)) in references.iter().enumerate() {
6039      if !in_detail_window(idx, references.len(), detail_offset) {
6040        println!(
6041          "  ⋯ {}/{} [{}] ({} path{})",
6042          ns.dimmed(),
6043          def.dimmed(),
6044          source.dimmed(),
6045          coords.len(),
6046          if coords.len() == 1 { "" } else { "s" }
6047        );
6048        continue;
6049      }
6050
6051      // Show main line
6052      if !context.is_empty() {
6053        println!("  {}/{} [{}]  {}", ns.cyan(), def, source.dimmed(), context.dimmed());
6054      } else {
6055        println!("  {}/{} [{}]", ns.cyan(), def, source.dimmed());
6056      }
6057
6058      // Show coordinates on one line with "and" separator
6059      if !coords.is_empty() {
6060        let coords_parts: Vec<String> = coords
6061          .iter()
6062          .map(|path| {
6063            let coord_str = format_path(path);
6064            format!("[{coord_str}]")
6065          })
6066          .collect();
6067        println!("    {}", format!("at {}", coords_parts.join(" and ")).dimmed());
6068      }
6069    }
6070  }
6071
6072  if found_definitions.is_empty() && references.is_empty() {
6073    println!("{}", "No matches found.".yellow());
6074  }
6075
6076  Ok(())
6077}
6078
6079fn collect_usages_from_snapshot(
6080  snapshot: &snapshot::Snapshot,
6081  target_ns: &str,
6082  target_def: &str,
6083  include_deps: bool,
6084) -> Result<RefResults, String> {
6085  let mut usages: RefResults = vec![]; // (ns, def, context, coords, source)
6086
6087  for (ns_name, file_data) in &snapshot.files {
6088    if !include_deps && (ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.")) {
6089      continue;
6090    }
6091
6092    let defines_target_name = ns_name != target_ns && file_data.defs.contains_key(target_def);
6093    let symbols = target_reference_symbols(ns_name, &file_data.ns.code, defines_target_name, target_ns, target_def)?;
6094    let mut core_heads = BTreeMap::new();
6095    for head in SOURCE_SCOPE_HEADS {
6096      let mut spellings = target_reference_symbols(
6097        ns_name,
6098        &file_data.ns.code,
6099        file_data.defs.contains_key(*head),
6100        calcit_core::calcit::CORE_NS,
6101        head,
6102      )?;
6103      // Intrinsic syntax precedes module imports/defs, but not locals.
6104      if CalcitSyntax::is_valid(head) {
6105        spellings.push((*head).to_owned());
6106      }
6107      for spelling in spellings {
6108        core_heads.insert(spelling, (*head).to_owned());
6109      }
6110    }
6111
6112    for (def_name, code_entry) in &file_data.defs {
6113      if ns_name == target_ns && def_name == target_def {
6114        continue;
6115      }
6116
6117      if let Some((context, coords)) = find_reference_symbols(&code_entry.code, &symbols, Some(&core_heads)) {
6118        usages.push((ns_name.clone(), def_name.clone(), context, coords, "code"));
6119      }
6120
6121      for test in &code_entry.tests {
6122        if let Some((expression, coords)) = find_reference_symbols(&test.code, &symbols, Some(&core_heads)) {
6123          let context = if expression.is_empty() {
6124            format!("#{}", test.name)
6125          } else {
6126            format!("#{}  {expression}", test.name)
6127          };
6128          usages.push((ns_name.clone(), def_name.clone(), context, coords, "tests"));
6129        }
6130      }
6131
6132      if let Ok(Some(schema)) = query_schema_cirru(code_entry.schema.as_ref(), false)
6133        && let Some((context, coords)) = find_reference_symbols(&strip_schema_quotes(&schema), &symbols, None)
6134      {
6135        usages.push((ns_name.clone(), def_name.clone(), context, coords, "schema"));
6136      }
6137    }
6138  }
6139
6140  usages.sort_by(|left, right| (&left.0, &left.1, left.4).cmp(&(&right.0, &right.1, right.4)));
6141  Ok(usages)
6142}
6143
6144/// Find usages of a specific definition
6145fn handle_usages(
6146  input_path: &str,
6147  target_ns: &str,
6148  target_def: &str,
6149  include_deps: bool,
6150  detail_offset: usize,
6151  entry: Option<&str>,
6152) -> Result<(), String> {
6153  let snapshot = load_snapshot(input_path, entry)?;
6154
6155  let target_file = snapshot
6156    .files
6157    .get(target_ns)
6158    .ok_or_else(|| format!("Namespace '{target_ns}' not found"))?;
6159  let lookup = resolve_definition_lookup(target_ns, target_def, target_file.defs.keys().map(|name| name.as_str()), true)?;
6160  let render_to_stderr = lookup.warning.is_some();
6161  if let Some(warning) = lookup.warning.as_deref() {
6162    print_cli_warning_block(warning);
6163  }
6164  let resolved_target_def = lookup.resolved;
6165
6166  let _ = target_file
6167    .defs
6168    .get(resolved_target_def.as_str())
6169    .expect("resolved definition exists");
6170
6171  let usages = collect_usages_from_snapshot(&snapshot, target_ns, &resolved_target_def, include_deps)?;
6172
6173  let mut out = String::new();
6174  let _ = writeln!(&mut out, "{} {}", "Usages:".bold(), usages.len());
6175  let _ = writeln!(
6176    &mut out,
6177    "{}",
6178    "Source-reference candidates: unexpanded macros can introduce bindings or references; zero usages is not proof of non-use."
6179      .dimmed()
6180  );
6181
6182  if usages.is_empty() {
6183    let _ = writeln!(
6184      &mut out,
6185      "\n{}",
6186      "No usages found. This definition may be unused or only called externally.".yellow()
6187    );
6188  } else {
6189    let _ = writeln!(&mut out);
6190    if usages.len() > DETAILED_RESULTS_WINDOW {
6191      let (start, end) = detailed_window(detail_offset, usages.len());
6192      let _ = writeln!(
6193        &mut out,
6194        "{}",
6195        format!("Detail window for usages: [{start}, {end}) (detail-offset={detail_offset}), other entries are compressed.").dimmed()
6196      );
6197    }
6198    for (idx, (ns, def, context, coords, source)) in usages.iter().enumerate() {
6199      if !in_detail_window(idx, usages.len(), detail_offset) {
6200        let _ = writeln!(
6201          &mut out,
6202          "  ⋯ {}/{} [{}] ({} path{})",
6203          ns.dimmed(),
6204          def.dimmed(),
6205          source.dimmed(),
6206          coords.len(),
6207          if coords.len() == 1 { "" } else { "s" }
6208        );
6209        continue;
6210      }
6211
6212      if !context.is_empty() {
6213        let _ = writeln!(
6214          &mut out,
6215          "  {}/{} [{}]  {}",
6216          ns.cyan(),
6217          def.green(),
6218          source.dimmed(),
6219          context.dimmed()
6220        );
6221      } else {
6222        let _ = writeln!(&mut out, "  {}/{} [{}]", ns.cyan(), def.green(), source.dimmed());
6223      }
6224
6225      if !coords.is_empty() {
6226        let coords_parts: Vec<String> = coords
6227          .iter()
6228          .map(|path| {
6229            let coord_str = format_path(path);
6230            format!("[{coord_str}]")
6231          })
6232          .collect();
6233        let _ = writeln!(&mut out, "    {}", format!("at {}", coords_parts.join(" and ")).dimmed());
6234      }
6235    }
6236  }
6237
6238  if !usages.is_empty() && command_guidance_enabled() {
6239    let _ = writeln!(
6240      &mut out,
6241      "\n{}",
6242      "Tip: Modifying this definition may affect the above locations.".dimmed()
6243    );
6244  }
6245
6246  emit_cli_output(&out, render_to_stderr);
6247  Ok(())
6248}
6249
6250// Helper: find all coordinates where symbol appears in Cirru tree
6251fn find_symbol_coords(code: &Cirru, symbol: &str) -> Vec<Vec<usize>> {
6252  fn search_recursive(node: &Cirru, symbol: &str, current_path: &[usize], results: &mut Vec<Vec<usize>>) {
6253    match node {
6254      Cirru::Leaf(s) if s.as_ref() == symbol => {
6255        results.push(current_path.to_vec());
6256      }
6257      Cirru::List(items) => {
6258        for (i, item) in items.iter().enumerate() {
6259          let mut new_path = current_path.to_vec();
6260          new_path.push(i);
6261          search_recursive(item, symbol, &new_path, results);
6262        }
6263      }
6264      _ => {}
6265    }
6266  }
6267
6268  let mut results = Vec::new();
6269  search_recursive(code, symbol, &[], &mut results);
6270  results
6271}
6272
6273// Helper: recursively search for symbol in Cirru tree
6274fn find_symbol_in_cirru(code: &Cirru, symbol: &str) -> bool {
6275  match code {
6276    Cirru::Leaf(s) => s.as_ref() == symbol,
6277    Cirru::List(items) => items.iter().any(|item| find_symbol_in_cirru(item, symbol)),
6278  }
6279}
6280
6281// Helper: get context around symbol usage in Cirru format (compact)
6282// Returns the smallest expression containing the symbol
6283fn get_symbol_context_cirru(code: &Cirru, symbol: &str) -> String {
6284  fn find_smallest_containing(node: &Cirru, symbol: &str) -> Option<Cirru> {
6285    match node {
6286      Cirru::Leaf(s) if s.as_ref() == symbol => Some(node.clone()),
6287      Cirru::List(items) => {
6288        for item in items {
6289          if let Some(found) = find_smallest_containing(item, symbol) {
6290            if matches!(found, Cirru::Leaf(_)) {
6291              return Some(node.clone());
6292            }
6293            return Some(found);
6294          }
6295        }
6296        None
6297      }
6298      _ => None,
6299    }
6300  }
6301
6302  if let Some(context_node) = find_smallest_containing(code, symbol) {
6303    let cirru_str = context_node.format_one_liner().unwrap_or_default();
6304    let trimmed = cirru_str.trim();
6305    return truncate_chars_with_dots(trimmed, 50);
6306  }
6307  String::new()
6308}
6309
6310/// Spellings that name `target_ns/target_def` inside `ns_name`, following the `:require` rules
6311/// (a later rule rebinds an earlier one):
6312/// - the fully qualified name, unless the caller binds `target_ns` itself as an alias of another namespace;
6313/// - `alias/def` for every `:as` alias of the target namespace;
6314/// - the bare name inside the target namespace, when it is `:refer`-ed from the target namespace,
6315///   or for `calcit.core` when no import rule or local definition (`defines_target_name`) rebinds it.
6316fn target_reference_symbols(
6317  ns_name: &str,
6318  ns_code: &Cirru,
6319  defines_target_name: bool,
6320  target_ns: &str,
6321  target_def: &str,
6322) -> Result<Vec<String>, String> {
6323  let mut bindings: BTreeMap<Arc<str>, Arc<program::ImportRule>> = BTreeMap::new();
6324  for (index, rule) in super::edit::extract_require_rules(ns_code).into_iter().enumerate() {
6325    let pairs =
6326      program::extract_import_rule(&rule).map_err(|error| format!("in namespace '{ns_name}' import rule {}: {error}", index + 1))?;
6327    bindings.extend(pairs);
6328  }
6329  let mut symbols = vec![];
6330  let qualified_is_rebound = bindings
6331    .get(target_ns)
6332    .is_some_and(|rule| !matches!(rule.as_ref(), program::ImportRule::NsAs(source) if source.as_ref() == target_ns));
6333  if !qualified_is_rebound {
6334    symbols.push(format!("{target_ns}/{target_def}"));
6335  }
6336  for (binding, rule) in &bindings {
6337    if let program::ImportRule::NsAs(source) = rule.as_ref()
6338      && source.as_ref() == target_ns
6339    {
6340      symbols.push(format!("{binding}/{target_def}"));
6341    }
6342  }
6343  let bare_refers_target = if ns_name == target_ns {
6344    true
6345  } else if let Some(rule) = bindings.get(target_def) {
6346    matches!(rule.as_ref(), program::ImportRule::NsReferDef(source, def) if source.as_ref() == target_ns && def.as_ref() == target_def)
6347  } else {
6348    target_ns == calcit_core::calcit::CORE_NS && !defines_target_name
6349  };
6350  if bare_refers_target {
6351    symbols.push(target_def.to_owned());
6352  }
6353  symbols.sort();
6354  symbols.dedup();
6355  Ok(symbols)
6356}
6357
6358/// Schema leaves name types as quoted symbols (`'Story`, `'schema/Story`); compare them unquoted.
6359fn strip_schema_quotes(code: &Cirru) -> Cirru {
6360  match code {
6361    Cirru::Leaf(s) => match s.strip_prefix('\'') {
6362      Some(name) if !name.is_empty() => Cirru::Leaf(Arc::from(name)),
6363      _ => code.clone(),
6364    },
6365    Cirru::List(items) => Cirru::List(items.iter().map(strip_schema_quotes).collect()),
6366  }
6367}
6368
6369/// Locate namespace-resolved spellings, using the shared lexical walker for
6370/// executable source and plain leaves for the separately parsed schema tree.
6371fn find_reference_symbols(
6372  code: &Cirru,
6373  symbols: &[String],
6374  core_heads: Option<&BTreeMap<String, String>>,
6375) -> Option<(String, Vec<Vec<usize>>)> {
6376  let mut coords = vec![];
6377  for symbol in symbols {
6378    let found = match core_heads {
6379      Some(heads) => source_reference_paths(code, symbol, heads),
6380      None => find_symbol_coords(code, symbol),
6381    };
6382    coords.extend(found);
6383  }
6384  coords.sort();
6385  coords.dedup();
6386  let first = coords.first()?;
6387  let parent = first.get(..first.len().saturating_sub(1)).unwrap_or_default();
6388  let node = navigate_to_path(code, parent).unwrap_or_else(|_| code.clone());
6389  let text = node.format_one_liner().unwrap_or_default();
6390  Some((truncate_chars_with_dots(text.trim(), 50), coords))
6391}
6392
6393/// Fuzzy search for namespace/definition by pattern
6394/// Searches for `<pattern>` in qualified names like `namespace/definition`
6395fn handle_fuzzy_search(
6396  input_path: &str,
6397  pattern: &str,
6398  include_deps: bool,
6399  limit: usize,
6400  detail_offset: usize,
6401  entry: Option<&str>,
6402) -> Result<(), String> {
6403  let snapshot = load_snapshot(input_path, entry)?;
6404
6405  let pattern_lower = pattern.to_lowercase();
6406  let mut results: Vec<(String, String, bool)> = Vec::new(); // (namespace, def, is_core)
6407
6408  // Search in all files
6409  for (ns_name, file_data) in &snapshot.files {
6410    // Mark core namespaces as "dep" for display
6411    let is_core = ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.");
6412
6413    // Skip core namespaces unless deps is requested
6414    if !include_deps && is_core {
6415      continue;
6416    }
6417
6418    for def_name in file_data.defs.keys() {
6419      let qualified = format!("{ns_name}/{def_name}");
6420      let qualified_lower = qualified.to_lowercase();
6421
6422      // Fuzzy match: check if pattern appears in qualified name
6423      if fuzzy_match(&qualified_lower, &pattern_lower) {
6424        results.push((ns_name.clone(), def_name.clone(), is_core));
6425      }
6426    }
6427  }
6428
6429  // Sort results by relevance (exact prefix match first, then alphabetically)
6430  results.sort_by(|(ns_a, def_a, _), (ns_b, def_b, _)| {
6431    let qualified_a = format!("{ns_a}/{def_a}").to_lowercase();
6432    let qualified_b = format!("{ns_b}/{def_b}").to_lowercase();
6433
6434    // Prioritize exact prefix matches
6435    let a_prefix = qualified_a.starts_with(&pattern_lower);
6436    let b_prefix = qualified_b.starts_with(&pattern_lower);
6437
6438    match (a_prefix, b_prefix) {
6439      (true, false) => std::cmp::Ordering::Less,
6440      (false, true) => std::cmp::Ordering::Greater,
6441      _ => qualified_a.cmp(&qualified_b),
6442    }
6443  });
6444
6445  // Limit results
6446  let total = results.len();
6447  let displayed: Vec<_> = results.into_iter().take(limit).collect();
6448
6449  println!("{} {} results", "Search:".bold(), total);
6450
6451  if displayed.is_empty() {
6452    println!("  {}", "No matches found".dimmed());
6453    if command_guidance_enabled() {
6454      println!(
6455        "\n{}",
6456        "Tip: Try a broader pattern, or add --deps to include core namespaces.".dimmed()
6457      );
6458    }
6459    return Ok(());
6460  }
6461
6462  print_detail_window_hint(displayed.len(), detail_offset, "search results");
6463
6464  for (idx, (ns, def, is_core)) in displayed.iter().enumerate() {
6465    if !in_detail_window(idx, displayed.len(), detail_offset) {
6466      println!("  ⋯ {}/{}", ns.dimmed(), def.dimmed());
6467      continue;
6468    }
6469
6470    let qualified = format!("{}/{}", ns.cyan(), def.green());
6471    if *is_core {
6472      println!("  {} {}", qualified, "(core)".dimmed());
6473    } else {
6474      println!("  {qualified}");
6475    }
6476  }
6477
6478  if total > limit {
6479    println!("  ⋯ {} more results...", total - limit);
6480  }
6481
6482  if command_guidance_enabled() {
6483    println!("\n{}", "Tip: Use `query def <ns/def>` to view definition content.".dimmed());
6484  }
6485
6486  Ok(())
6487}
6488
6489/// Simple fuzzy matching: check if all characters of pattern appear in order in text
6490fn fuzzy_match(text: &str, pattern: &str) -> bool {
6491  // Support multiple match styles:
6492  // 1. Substring match: "map" matches "hash-map"
6493  // 2. Character sequence match: "hm" matches "hash-map"
6494
6495  // First try substring match (fast path)
6496  if text.contains(pattern) {
6497    return true;
6498  }
6499
6500  // Then try character sequence match
6501  let mut text_chars = text.chars().peekable();
6502  for pattern_char in pattern.chars() {
6503    loop {
6504      match text_chars.next() {
6505        Some(c) if c == pattern_char => break,
6506        Some(_) => continue,
6507        None => return false,
6508      }
6509    }
6510  }
6511  true
6512}
6513
6514fn snapshot_code_path(path: &[usize]) -> String {
6515  if path.is_empty() {
6516    "code".to_owned()
6517  } else {
6518    format!("code{}", format_path(path))
6519  }
6520}
6521
6522fn search_node_kind(code: &Cirru, path: &[usize], node: &Cirru) -> &'static str {
6523  match node {
6524    Cirru::List(_) => "expr",
6525    Cirru::Leaf(_) => {
6526      if path.last() == Some(&0)
6527        && navigate_to_path(code, &path[..path.len().saturating_sub(1)]).is_ok_and(|parent| matches!(parent, Cirru::List(_)))
6528      {
6529        "call"
6530      } else {
6531        "leaf"
6532      }
6533    }
6534  }
6535}
6536
6537fn format_search_results_json(
6538  command: &'static str,
6539  pattern: &str,
6540  pattern_is_json: bool,
6541  start_path: Option<&str>,
6542  common_opts: &SearchCommonOpts,
6543  catalog: &SearchCatalog,
6544  results: &SearchResults,
6545) -> Result<String, String> {
6546  let snapshot = &catalog.snapshot;
6547  let total_matches = results.iter().map(|(_, _, matches)| matches.len()).sum::<usize>();
6548  let mut cursor_index = 0_usize;
6549  let definitions = results
6550    .iter()
6551    .map(|(namespace, definition, matches)| -> Result<serde_json::Value, String> {
6552      let code_entry = snapshot
6553        .files
6554        .get(namespace)
6555        .and_then(|file| file.defs.get(definition))
6556        .ok_or_else(|| format!("Definition disappeared while formatting search results: {namespace}/{definition}"))?;
6557      let (source, origin) = catalog
6558        .sources
6559        .get(namespace)
6560        .ok_or_else(|| format!("Source origin disappeared while formatting search results: {namespace}/{definition}"))?;
6561      Ok(serde_json::json!({
6562        "id": format!("{namespace}/{definition}"),
6563        "namespace": namespace,
6564        "name": definition,
6565        "source": source,
6566        "origin": origin,
6567        "match_count": matches.len(),
6568        "matches": matches.iter().map(|(path, node)| {
6569          let current_cursor_index = cursor_index;
6570          cursor_index += 1;
6571          let parent_path = common_opts.parent_path.then(|| {
6572            if path.is_empty() {
6573              None
6574            } else {
6575              Some(snapshot_code_path(&path[..path.len() - 1]))
6576            }
6577          }).flatten();
6578          serde_json::json!({
6579            "cursor_index": current_cursor_index,
6580            "path": snapshot_code_path(path),
6581            "parent_path": parent_path,
6582            "node_kind": search_node_kind(&code_entry.code, path, node),
6583            "tree": cirru_to_json_value(node),
6584            "source": source,
6585            "origin": origin,
6586          })
6587        }).collect::<Vec<_>>(),
6588      }))
6589    })
6590    .collect::<Result<Vec<_>, String>>()?;
6591
6592  let mut revision_parts = vec![
6593    command.to_owned(),
6594    pattern.to_owned(),
6595    common_opts.filter.unwrap_or_default().to_owned(),
6596    common_opts.source.as_str().to_owned(),
6597    start_path.unwrap_or_default().to_owned(),
6598  ];
6599  for (namespace, definition, _) in results {
6600    let entry = snapshot
6601      .files
6602      .get(namespace)
6603      .and_then(|file| file.defs.get(definition))
6604      .ok_or_else(|| format!("Definition disappeared while formatting search results: {namespace}/{definition}"))?;
6605    revision_parts.push(format!("{namespace}/{definition}:{}", snapshot::definition_revision(entry)?));
6606  }
6607  let revision_refs = revision_parts.iter().map(String::as_str).collect::<Vec<_>>();
6608
6609  let envelope = serde_json::json!({
6610    "schema_version": 1,
6611    "command": command,
6612    "revision": semantic_revision(&revision_refs),
6613    "data": {
6614      "pattern": pattern,
6615      "filters": {
6616        "definition": common_opts.filter,
6617        "exact": !common_opts.loose,
6618        "regex": common_opts.regex,
6619        "max_depth": common_opts.max_depth,
6620        "start_path": start_path,
6621        "entry": common_opts.entry,
6622        "source": common_opts.source,
6623        "pattern_is_json": pattern_is_json,
6624      },
6625      "summary": {
6626        "definitions": results.len(),
6627        "matches": total_matches,
6628      },
6629      "definitions": definitions,
6630    },
6631    "diagnostics": [],
6632  });
6633  serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode search JSON: {error}"))
6634}
6635
6636fn maybe_set_cursor_from_search_results(
6637  input_path: &str,
6638  results: &SearchResults,
6639  selected_index: usize,
6640  last_query: CursorLastQuery,
6641) -> Result<(), String> {
6642  let total_matches = results.iter().map(|(_, _, matches)| matches.len()).sum::<usize>();
6643  let main_snapshot = load_main_snapshot(input_path)?;
6644  let mut current_index = 0_usize;
6645  for (namespace, definition, matches) in results {
6646    for (path, _) in matches {
6647      if current_index == selected_index {
6648        if !main_snapshot.files.contains_key(namespace) {
6649          return Err(format!(
6650            "Search match #{selected_index} belongs to dependency or builtin namespace '{namespace}', which cannot become a project edit cursor. Narrow the search with `--filter <project-namespace>` and choose its displayed cursor index."
6651          ));
6652        }
6653        return set_cursor_from_query_match(
6654          input_path,
6655          &format!("{namespace}/{definition}"),
6656          path.clone(),
6657          selected_index,
6658          last_query,
6659        );
6660      }
6661      current_index += 1;
6662    }
6663  }
6664  Err(format!(
6665    "Search cursor index {selected_index} is out of range; query returned {total_matches} match(es)."
6666  ))
6667}
6668
6669fn snapshot_content_revision(input_path: &str) -> Result<String, String> {
6670  let content = fs::read(input_path).map_err(|error| format!("Failed to read snapshot revision from '{input_path}': {error}"))?;
6671  let mut hasher = Md5::new();
6672  hasher.update(&content);
6673  Ok(format!("md5:{}", hex::encode(hasher.finalize())))
6674}
6675
6676fn cursor_last_query(
6677  input_path: &str,
6678  command: &str,
6679  pattern: &str,
6680  pattern_is_json: bool,
6681  start_path: Option<&str>,
6682  common_opts: &SearchCommonOpts,
6683  selected_index: usize,
6684) -> Result<CursorLastQuery, String> {
6685  Ok(CursorLastQuery {
6686    command: command.to_string(),
6687    pattern: pattern.to_string(),
6688    filter: common_opts.filter.map(str::to_string),
6689    exact: !common_opts.loose,
6690    regex: common_opts.regex,
6691    max_depth: common_opts.max_depth,
6692    start_path: start_path.map(str::to_string),
6693    entry: common_opts.entry.map(str::to_string),
6694    source: common_opts.source.as_str().to_owned(),
6695    pattern_is_json,
6696    selected_index,
6697    snapshot_revision: snapshot_content_revision(input_path)?,
6698  })
6699}
6700
6701fn parse_search_start_path(start_path: Option<&str>) -> Result<Option<Vec<usize>>, String> {
6702  start_path
6703    .map(|path| parse_path(path).map_err(|error| format!("Invalid start path '{path}': {error}")))
6704    .transpose()
6705}
6706
6707fn parse_search_filter(filter: Option<&str>) -> Result<(Option<&str>, Option<&str>), String> {
6708  let Some(filter) = filter else {
6709    return Ok((None, None));
6710  };
6711  let mut parts = filter.split('/');
6712  let namespace = parts.next();
6713  let definition = parts.next();
6714  if parts.next().is_some() {
6715    return Err(format!(
6716      "Invalid filter format: '{filter}'. Use 'namespace' or 'namespace/definition'"
6717    ));
6718  }
6719  Ok((namespace, definition))
6720}
6721
6722fn collect_search_results<F>(
6723  snapshot: &snapshot::Snapshot,
6724  start_path: Option<&[usize]>,
6725  filter: Option<&str>,
6726  mut search: F,
6727) -> Result<SearchResults, String>
6728where
6729  F: FnMut(&Cirru, &[usize]) -> Vec<(Vec<usize>, Cirru)>,
6730{
6731  let (filter_ns, filter_def) = parse_search_filter(filter)?;
6732  let mut all_results: SearchResults = Vec::new();
6733
6734  for (ns, file_data) in &snapshot.files {
6735    if filter_ns.is_some_and(|filter_namespace| ns != filter_namespace) {
6736      continue;
6737    }
6738    for (def_name, code_entry) in &file_data.defs {
6739      if filter_def.is_some_and(|filter_definition| def_name != filter_definition) {
6740        continue;
6741      }
6742      let owned_search_root = if let Some(path) = start_path {
6743        match navigate_to_path(&code_entry.code, path) {
6744          Ok(node) => Some(node),
6745          Err(error) => {
6746            eprintln!(
6747              "{} Failed to navigate to start path in {}/{}: {}",
6748              "Warning:".yellow(),
6749              ns,
6750              def_name,
6751              error
6752            );
6753            continue;
6754          }
6755        }
6756      } else {
6757        None
6758      };
6759      let search_root = owned_search_root.as_ref().unwrap_or(&code_entry.code);
6760      let results = search(search_root, start_path.unwrap_or(&[]));
6761      if !results.is_empty() {
6762        all_results.push((ns.clone(), def_name.clone(), results));
6763      }
6764    }
6765  }
6766
6767  all_results.sort_by(|a, b| b.2.len().cmp(&a.2.len()).then_with(|| a.0.cmp(&b.0)).then_with(|| a.1.cmp(&b.1)));
6768  Ok(all_results)
6769}
6770
6771#[derive(Clone, Copy)]
6772struct SearchResultDisplay {
6773  bracket_path: bool,
6774  show_parent_path: bool,
6775}
6776
6777fn print_search_results_human(
6778  catalog: &SearchCatalog,
6779  all_results: &SearchResults,
6780  common_opts: &SearchCommonOpts,
6781  display: SearchResultDisplay,
6782) {
6783  let snapshot = &catalog.snapshot;
6784  if all_results.is_empty() {
6785    println!("# Search results\n\n_No matches found._");
6786    return;
6787  }
6788
6789  let total_matches: usize = all_results.iter().map(|(_, _, results)| results.len()).sum();
6790  println!(
6791    "# Search results\n\n- Matches: {total_matches}\n- Definitions: {}\n",
6792    all_results.len(),
6793  );
6794
6795  let mut definition_offset = 0_usize;
6796  for (ns, def_name, results) in all_results {
6797    let source_label = catalog
6798      .sources
6799      .get(ns)
6800      .map(|(source, origin)| {
6801        let origin_label = origin.module.as_deref().unwrap_or(origin.package.as_str());
6802        format!("{}:{origin_label}", source.as_str())
6803      })
6804      .unwrap_or_else(|| "unknown".to_owned());
6805    println!("## `{ns}/{def_name}`\n\n- Matches: {}\n- Source: `{source_label}`\n", results.len());
6806    print_detail_window_hint(results.len(), common_opts.detail_offset, "matches");
6807
6808    if let Some(file_data) = snapshot.files.get(ns)
6809      && let Some(code_entry) = file_data.defs.get(def_name)
6810    {
6811      let total = results.len();
6812      let (start, end) = detailed_window(common_opts.detail_offset, total);
6813      let detailed_count = end.saturating_sub(start);
6814
6815      for (local_index, (path, node)) in results.iter().enumerate().skip(start).take(detailed_count) {
6816        let cursor_index = definition_offset + local_index;
6817        if path.is_empty() {
6818          let (content, truncated) = preview_node_oneline(&code_entry.code, 110);
6819          println!(
6820            "### Match #{cursor_index}\n\n- Path: `root`{}\n\n{}",
6821            if truncated { "\n- Preview: truncated" } else { "" },
6822            markdown_fenced_block("cirru", &content)
6823          );
6824        } else {
6825          let path_str = format_path(path);
6826          let path_label = if display.bracket_path { format!("[{path_str}]") } else { path_str };
6827          let ((expr_preview, expr_truncated), parent_previews) =
6828            expression_and_parent_preview(&code_entry.code, path, node, None, common_opts.loose);
6829          let (display_preview, display_truncated) = parent_previews
6830            .first()
6831            .map(|(text, truncated)| (text.as_str(), *truncated))
6832            .unwrap_or((expr_preview.as_str(), expr_truncated));
6833          println!(
6834            "### Match #{cursor_index}\n\n- Path: `{path_label}`{}\n\n{}",
6835            if display_truncated { "\n- Preview: truncated" } else { "" },
6836            markdown_fenced_block("cirru", display_preview)
6837          );
6838          if display.show_parent_path && common_opts.parent_path {
6839            let parent_path_str = snapshot_code_path(&path[..path.len() - 1]);
6840            println!("- Parent: `{parent_path_str}`\n");
6841          }
6842        }
6843      }
6844
6845      if start > 0 {
6846        println!(
6847          "_Matches #{}–#{} compressed before this window ({})._",
6848          definition_offset,
6849          definition_offset + start - 1,
6850          start,
6851        );
6852      }
6853      if end < total {
6854        println!(
6855          "_Matches #{}–#{} compressed after this window ({})._",
6856          definition_offset + end,
6857          definition_offset + total - 1,
6858          total - end,
6859        );
6860      }
6861    }
6862
6863    definition_offset += results.len();
6864    println!();
6865  }
6866
6867  if total_matches > 10 && common_opts.loose {
6868    println!("## Tip\n\nMany matches ({total_matches}); add `--exact` to show exact matches only.");
6869  }
6870}
6871
6872struct SearchCommandInfo<'a> {
6873  envelope_command: &'static str,
6874  cursor_command: &'static str,
6875  pattern: &'a str,
6876  pattern_is_json: bool,
6877  start_path: Option<&'a str>,
6878  display: SearchResultDisplay,
6879}
6880
6881fn finish_search_results(
6882  input_path: &str,
6883  catalog: &SearchCatalog,
6884  all_results: &SearchResults,
6885  common_opts: &SearchCommonOpts,
6886  info: SearchCommandInfo<'_>,
6887) -> Result<(), String> {
6888  if let Some(selected_index) = common_opts.set_cursor {
6889    let last_query = cursor_last_query(
6890      input_path,
6891      info.cursor_command,
6892      info.pattern,
6893      info.pattern_is_json,
6894      info.start_path,
6895      common_opts,
6896      selected_index,
6897    )?;
6898    maybe_set_cursor_from_search_results(input_path, all_results, selected_index, last_query)?;
6899  }
6900
6901  if common_opts.compact_output {
6902    return Ok(());
6903  }
6904  if common_opts.format != QueryRenderFormat::Human {
6905    let json = format_search_results_json(
6906      info.envelope_command,
6907      info.pattern,
6908      info.pattern_is_json,
6909      info.start_path,
6910      common_opts,
6911      catalog,
6912      all_results,
6913    )?;
6914    match common_opts.format {
6915      QueryRenderFormat::Json => println!("{json}"),
6916      QueryRenderFormat::Edn => {
6917        let value =
6918          serde_json::from_str::<serde_json::Value>(&json).map_err(|error| format!("Failed to decode search query result: {error}"))?;
6919        emit_query_structured(&value, QueryRenderFormat::Edn, "search query result")?;
6920      }
6921      QueryRenderFormat::Human => unreachable!("structured search format checked above"),
6922    }
6923    return Ok(());
6924  }
6925  print_search_results_human(catalog, all_results, common_opts, info.display);
6926  Ok(())
6927}
6928
6929/// Search for leaf nodes (strings) in a definition
6930fn handle_search_leaf(input_path: &str, pattern: &str, start_path: Option<&str>, common_opts: &SearchCommonOpts) -> Result<(), String> {
6931  let catalog = load_snapshot_for_search(input_path, common_opts)?;
6932  let parsed_start_path = parse_search_start_path(start_path)?;
6933  let all_results = collect_search_results(
6934    &catalog.snapshot,
6935    parsed_start_path.as_deref(),
6936    common_opts.filter,
6937    |search_root, base_path| {
6938      search_leaf_nodes(
6939        search_root,
6940        pattern,
6941        common_opts.loose,
6942        common_opts.regex,
6943        common_opts.max_depth,
6944        base_path,
6945      )
6946    },
6947  )?;
6948
6949  finish_search_results(
6950    input_path,
6951    &catalog,
6952    &all_results,
6953    common_opts,
6954    SearchCommandInfo {
6955      envelope_command: "query.search",
6956      cursor_command: "search",
6957      pattern,
6958      pattern_is_json: false,
6959      start_path,
6960      display: SearchResultDisplay {
6961        bracket_path: false,
6962        show_parent_path: true,
6963      },
6964    },
6965  )
6966}
6967
6968/// Search for structural expressions across project or in filtered scope
6969fn handle_search_expr(
6970  input_path: &str,
6971  pattern: &str,
6972  json: bool,
6973  start_path: Option<&str>,
6974  common_opts: &SearchCommonOpts,
6975) -> Result<(), String> {
6976  let catalog = load_snapshot_for_search(input_path, common_opts)?;
6977  let parsed_start_path = parse_search_start_path(start_path)?;
6978
6979  let pattern_node = if json {
6980    let json_val: serde_json::Value = serde_json::from_str(pattern).map_err(|e| format!("Failed to parse JSON pattern: {e}"))?;
6981    json_to_cirru(&json_val)?
6982  } else {
6983    cirru_parser::parse(pattern)
6984      .map_err(|e| format!("Failed to parse Cirru pattern: {e}"))?
6985      .first()
6986      .ok_or("Pattern is empty")?
6987      .clone()
6988  };
6989
6990  let all_results = collect_search_results(
6991    &catalog.snapshot,
6992    parsed_start_path.as_deref(),
6993    common_opts.filter,
6994    |search_root, base_path| search_expr_nodes(search_root, &pattern_node, common_opts.loose, common_opts.max_depth, base_path),
6995  )?;
6996
6997  finish_search_results(
6998    input_path,
6999    &catalog,
7000    &all_results,
7001    common_opts,
7002    SearchCommandInfo {
7003      envelope_command: "query.search-expr",
7004      cursor_command: "search-expr",
7005      pattern,
7006      pattern_is_json: json,
7007      start_path,
7008      display: SearchResultDisplay {
7009        bracket_path: true,
7010        show_parent_path: false,
7011      },
7012    },
7013  )
7014}
7015
7016/// Helper function to convert JSON to Cirru
7017fn json_to_cirru(json: &serde_json::Value) -> Result<Cirru, String> {
7018  match json {
7019    serde_json::Value::String(s) => Ok(Cirru::Leaf(s.as_str().into())),
7020    serde_json::Value::Array(arr) => {
7021      let items: Result<Vec<_>, _> = arr.iter().map(json_to_cirru).collect();
7022      Ok(Cirru::List(items?))
7023    }
7024    _ => Err("Pattern must be a string or array".to_string()),
7025  }
7026}
7027
7028/// Print search results with parent context
7029/// Search for leaf nodes with exact or loose matching
7030fn search_leaf_nodes(
7031  node: &Cirru,
7032  pattern: &str,
7033  loose: bool,
7034  regex: bool,
7035  max_depth: usize,
7036  current_path: &[usize],
7037) -> Vec<(Vec<usize>, Cirru)> {
7038  let mut results = Vec::new();
7039
7040  // Check depth limit
7041  if max_depth > 0 && current_path.len() >= max_depth {
7042    return results;
7043  }
7044
7045  // Compile regex once if needed
7046  let regex_pattern = if regex {
7047    match regex::Regex::new(pattern) {
7048      Ok(r) => Some(r),
7049      Err(e) => {
7050        eprintln!("{} Invalid regex '{}': {}", "Error:".red().bold(), pattern, e);
7051        return results;
7052      }
7053    }
7054  } else {
7055    None
7056  };
7057
7058  // Only match leaf nodes
7059  match node {
7060    Cirru::Leaf(s) => {
7061      let matches = if regex {
7062        regex_pattern.as_ref().is_some_and(|r| r.is_match(s))
7063      } else if loose {
7064        // Loose: check if leaf contains pattern
7065        s.to_lowercase().contains(&pattern.to_lowercase())
7066      } else {
7067        // Exact: check if leaf equals pattern
7068        s.as_ref() == pattern
7069      };
7070
7071      if matches {
7072        results.push((current_path.to_vec(), node.clone()));
7073      }
7074    }
7075    Cirru::List(items) => {
7076      // Recursively search children
7077      for (i, item) in items.iter().enumerate() {
7078        let mut new_path = current_path.to_vec();
7079        new_path.push(i);
7080        results.extend(search_leaf_nodes(item, pattern, loose, regex, max_depth, &new_path));
7081      }
7082    }
7083  }
7084
7085  results
7086}
7087
7088fn search_expr_nodes(node: &Cirru, pattern: &Cirru, loose: bool, max_depth: usize, current_path: &[usize]) -> Vec<(Vec<usize>, Cirru)> {
7089  let mut results = Vec::new();
7090
7091  if max_depth > 0 && current_path.len() >= max_depth {
7092    return results;
7093  }
7094
7095  // Check if current node matches pattern
7096  let matches = if loose {
7097    contains_pattern(node, pattern)
7098  } else {
7099    matches_exact_structure(node, pattern)
7100  };
7101
7102  if matches {
7103    results.push((current_path.to_vec(), node.clone()));
7104  }
7105
7106  // Recursively search children
7107  if let Cirru::List(items) = node {
7108    for (i, item) in items.iter().enumerate() {
7109      let mut new_path = current_path.to_vec();
7110      new_path.push(i);
7111      results.extend(search_expr_nodes(item, pattern, loose, max_depth, &new_path));
7112    }
7113  }
7114
7115  results
7116}
7117
7118/// Check if node starts with pattern (prefix matching)
7119/// In loose mode, pattern must match from the beginning of the list
7120fn contains_pattern(node: &Cirru, pattern: &Cirru) -> bool {
7121  match (node, pattern) {
7122    // Leaf nodes: check string containment
7123    (Cirru::Leaf(s), Cirru::Leaf(p)) => s.to_lowercase().contains(&p.as_ref().to_lowercase()),
7124
7125    // List: pattern must match from the beginning (prefix match)
7126    (Cirru::List(items), Cirru::List(pattern_items)) => {
7127      if pattern_items.is_empty() {
7128        return true;
7129      }
7130
7131      // Pattern must not be longer than the actual list
7132      if pattern_items.len() > items.len() {
7133        return false;
7134      }
7135
7136      // Check if pattern matches from the beginning using prefix matching
7137      for (i, pattern_item) in pattern_items.iter().enumerate() {
7138        if !matches_prefix_structure(&items[i], pattern_item) {
7139          return false;
7140        }
7141      }
7142      true
7143    }
7144
7145    _ => false,
7146  }
7147}
7148
7149/// Check if node matches pattern as a prefix (allows node to be longer than pattern)
7150fn matches_prefix_structure(node: &Cirru, pattern: &Cirru) -> bool {
7151  super::structural_pattern::match_structure(node, pattern, true, false).is_some()
7152}
7153
7154/// Check if node exactly matches pattern structure
7155fn matches_exact_structure(node: &Cirru, pattern: &Cirru) -> bool {
7156  super::structural_pattern::match_structure(node, pattern, false, false).is_some()
7157}
7158
7159// ═══════════════════════════════════════════════════════════════════════════════
7160// L4: path expression resolver
7161// ═══════════════════════════════════════════════════════════════════════════════
7162
7163pub(crate) fn resolve_path_expression(root: &Cirru, selector: &str) -> Result<Vec<usize>, String> {
7164  // Parse the selector as Cirru
7165  let parsed = cirru_parser::parse(selector).map_err(|e| format!("Failed to parse path selector: {e}"))?;
7166  let Some(first) = parsed.first() else {
7167    return Err("Empty path selector".to_string());
7168  };
7169
7170  // Verify it starts with "path"
7171  let Cirru::List(steps) = first else {
7172    return Err("Path expression must be a list starting with 'path'".to_string());
7173  };
7174  if steps.is_empty() {
7175    return Err("Empty path expression".to_string());
7176  }
7177  let Cirru::Leaf(head) = &steps[0] else {
7178    return Err("Path expression must start with 'path'".to_string());
7179  };
7180  if head.as_ref() != "path" {
7181    return Err(format!("Expected 'path' at start, got '{head}'"));
7182  }
7183
7184  // Walk the selectors
7185  let mut current_node = root.clone();
7186  let mut current_path: Vec<usize> = vec![];
7187
7188  for step in &steps[1..] {
7189    match step {
7190      Cirru::Leaf(leaf_val) => {
7191        // Bare leaf: match the current node as a leaf
7192        let Cirru::Leaf(current_leaf) = &current_node else {
7193          return Err(format!("Expected leaf but got list at path {}", format_path(&current_path)));
7194        };
7195        if current_leaf.as_ref() != leaf_val.as_ref() {
7196          return Err(format!(
7197            "Leaf mismatch at path {}: expected {:?}, got {:?}",
7198            format_path(&current_path),
7199            leaf_val.as_ref(),
7200            current_leaf.as_ref()
7201          ));
7202        }
7203        // Leaf matched — search next sibling by going up and right
7204        // For simplicity, we just verify and move on
7205      }
7206      Cirru::List(selector_list) => {
7207        if selector_list.is_empty() {
7208          return Err("Empty selector".to_string());
7209        }
7210        let Cirru::Leaf(op) = &selector_list[0] else {
7211          return Err("Selector must start with an operator leaf".to_string());
7212        };
7213        match op.as_ref() {
7214          "heading" => {
7215            // Match current node's children against pattern
7216            let Cirru::List(ref current_children) = current_node else {
7217              return Err("heading requires a list node".to_string());
7218            };
7219            let pattern = &selector_list[1..];
7220            if !starts_with_pattern(current_children, pattern) {
7221              return Err(format!(
7222                "heading mismatch at path {}: node does not start with expected pattern",
7223                format_path(&current_path)
7224              ));
7225            }
7226          }
7227          "nth" => {
7228            if selector_list.len() < 2 {
7229              return Err("nth requires an index argument".to_string());
7230            }
7231            let Cirru::Leaf(idx_leaf) = &selector_list[1] else {
7232              return Err("nth index must be a number".to_string());
7233            };
7234            let idx: usize = idx_leaf
7235              .as_ref()
7236              .parse()
7237              .map_err(|_| format!("Invalid nth index: '{}'", idx_leaf.as_ref()))?;
7238            let Cirru::List(ref children) = current_node else {
7239              return Err("nth requires a list node".to_string());
7240            };
7241            if idx >= children.len() {
7242              return Err(format!("nth index {} out of bounds ({} children)", idx, children.len()));
7243            }
7244            current_path.push(idx);
7245            current_node = children[idx].clone();
7246          }
7247          _ => return Err(format!("Unknown selector: '{}'", op.as_ref())),
7248        }
7249      }
7250    }
7251  }
7252
7253  Ok(current_path)
7254}
7255
7256fn starts_with_pattern(node_children: &[Cirru], pattern: &[Cirru]) -> bool {
7257  if pattern.len() > node_children.len() {
7258    return false;
7259  }
7260  for (i, pat) in pattern.iter().enumerate() {
7261    match pat {
7262      Cirru::Leaf(pat_leaf) => {
7263        let Cirru::Leaf(child_leaf) = &node_children[i] else {
7264          return false;
7265        };
7266        if child_leaf.as_ref() != pat_leaf.as_ref() {
7267          return false;
7268        }
7269      }
7270      Cirru::List(pat_list) => {
7271        let Cirru::List(child_list) = &node_children[i] else {
7272          return false;
7273        };
7274        if !starts_with_pattern(child_list, pat_list) {
7275          return false;
7276        }
7277      }
7278    }
7279  }
7280  true
7281}
7282
7283#[cfg(test)]
7284mod usage_symbol_tests {
7285  use super::*;
7286
7287  fn symbols_for(ns_source: &str, defines_target_name: bool, target: (&str, &str)) -> Vec<String> {
7288    let ns_code = cirru_parser::parse(ns_source).expect("ns form should parse").remove(0);
7289    target_reference_symbols("app.caller", &ns_code, defines_target_name, target.0, target.1)
7290      .expect("canonical require rules should resolve")
7291  }
7292
7293  #[test]
7294  fn legacy_require_list_is_rejected_for_usages() {
7295    let ns_code = cirru_parser::parse("ns app.caller $ :require $ [] app.schema :as s")
7296      .expect("ns form should parse")
7297      .remove(0);
7298    let err = target_reference_symbols("app.caller", &ns_code, false, "app.schema", "decode")
7299      .expect_err("legacy `[]` require list must be rejected");
7300    assert!(err.contains(calcit_core::program::LEGACY_REQUIRE_LIST_ERROR), "{err}");
7301  }
7302
7303  #[test]
7304  fn reference_symbols_follow_require_rules() {
7305    let target = ("app.schema", "decode");
7306    assert_eq!(symbols_for("ns app.caller", false, target), ["app.schema/decode"]);
7307    // Two aliases for one namespace, plus a refer.
7308    assert_eq!(
7309      symbols_for(
7310        "ns app.caller $ :require (app.schema :as s) (app.schema :as schema) (app.schema :refer $ decode)",
7311        false,
7312        target
7313      ),
7314      ["app.schema/decode", "decode", "s/decode", "schema/decode"]
7315    );
7316    // A namespace whose name only shares a prefix is a different namespace.
7317    assert_eq!(
7318      symbols_for(
7319        "ns app.caller $ :require (app.schema-v2 :as schema) (app.schema-v2 :refer $ decode)",
7320        false,
7321        target
7322      ),
7323      ["app.schema/decode"]
7324    );
7325    // A later rule rebinding the referred name wins: `:refer`, `:as` and `:default`.
7326    for rebinding in ["app.other :refer $ decode", "app.other :as decode", "|pkg :default decode"] {
7327      let source = format!("ns app.caller $ :require (app.schema :refer $ decode) ({rebinding})");
7328      assert_eq!(symbols_for(&source, false, target), ["app.schema/decode"], "{rebinding}");
7329    }
7330    // A later rule rebinding the alias drops the alias spelling.
7331    assert_eq!(
7332      symbols_for("ns app.caller $ :require (app.schema :as s) (app.other :as s)", false, target),
7333      ["app.schema/decode"]
7334    );
7335    // Binding the target namespace name itself to another namespace hides the qualified spelling.
7336    assert_eq!(
7337      symbols_for(
7338        "ns app.caller $ :require (app.other :as app.schema) (app.schema :as s)",
7339        false,
7340        target
7341      ),
7342      ["s/decode"]
7343    );
7344  }
7345
7346  #[test]
7347  fn core_names_are_bare_unless_rebound() {
7348    let target = ("calcit.core", "map");
7349    assert_eq!(symbols_for("ns app.caller", false, target), ["calcit.core/map", "map"]);
7350    assert_eq!(symbols_for("ns app.caller", true, target), ["calcit.core/map"]);
7351    assert_eq!(
7352      symbols_for("ns app.caller $ :require (app.util :refer $ map)", false, target),
7353      ["calcit.core/map"]
7354    );
7355  }
7356}
7357
7358#[cfg(test)]
7359mod examples_cirru_tests {
7360  use super::*;
7361
7362  #[test]
7363  fn render_examples_cirru_round_trips_expressions_and_leaves() {
7364    let examples = vec![
7365      cirru_parser::parse("+ 1 2").expect("expr should parse").remove(0),
7366      Cirru::Leaf(Arc::from("CounterOps")),
7367      cirru_parser::parse("let ((x 1)) $ + x 2").expect("let expr should parse").remove(0),
7368    ];
7369    let rendered = render_examples_cirru("app.main/sample", &examples).expect("should format examples as Cirru");
7370    assert!(!rendered.contains("JSON AST"), "{rendered}");
7371    assert!(!rendered.contains("```"), "{rendered}");
7372    let reparsed = crate::cli_handlers::common::parse_quoted_cirru_nodes(&rendered).expect("rendered Cirru should reparse");
7373    assert_eq!(reparsed, examples);
7374  }
7375
7376  #[test]
7377  fn render_examples_cirru_returns_empty_for_no_examples() {
7378    let rendered = render_examples_cirru("app.main/empty", &[]).expect("empty examples should succeed");
7379    assert!(rendered.is_empty(), "{rendered:?}");
7380  }
7381
7382  #[test]
7383  fn special_js_intrinsics_share_compiler_signature() {
7384    for name in ["js-array", "&js-object"] {
7385      let meta = lookup_special_builtin_query_meta(calcit_core::calcit::CORE_NS, name)
7386        .expect("query meta lookup should succeed")
7387        .expect("intrinsic metadata should exist");
7388      let expected = runner::preprocess::special_js_intrinsic_signature(name).expect("compiler signature should exist");
7389      assert_eq!(meta.schema, expected, "{name} query schema drifted from compiler");
7390      let sig = meta.schema.as_function().expect("schema should be Fn");
7391      assert!(matches!(sig.return_type.as_ref(), CalcitTypeAnnotation::JsObject));
7392    }
7393  }
7394}