Skip to main content

calcit_cli/
effects_graph.rs

1//! Effects graph analysis: State / Transform / Effect decomposition per definition.
2
3use calcit_core::builtins;
4use calcit_core::calcit::CalcitTypeAnnotation;
5use calcit_core::calcit::NullableOrigin;
6use calcit_core::calcit::{Calcit, CalcitFnArgs, CalcitLocal, CalcitProc, CalcitStructDef, CalcitSyntax, MethodKind};
7use calcit_core::program::{
8  ImportRule, PROGRAM_CODE_DATA, lookup_codegen_type_hint, lookup_def_code, lookup_def_schema, lookup_ns_target_in_import,
9};
10use cirru_edn::{Edn, EdnListView, EdnMapView, EdnTag};
11use cirru_parser::Cirru;
12use colored::Colorize;
13use serde::{Deserialize, Serialize};
14use std::collections::{HashMap, HashSet};
15
16/// Configuration for effects graph analysis.
17#[derive(Debug, Clone, Default)]
18pub struct EffectsGraphConfig {
19  pub include_core: bool,
20  pub max_depth: usize,
21  pub ns_prefix: Option<String>,
22  pub detail: EffectsGraphDetail,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum EffectsGraphDetail {
27  #[default]
28  Summary,
29  Full,
30  Minimal,
31}
32
33/// A detected state item inside a definition.
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
35pub struct StateItem {
36  pub kind: String,
37  pub name: String,
38  #[serde(skip_serializing_if = "Option::is_none")]
39  pub type_hint: Option<String>,
40}
41
42/// A classified effect occurrence.
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct EffectItem {
45  pub kind: String,
46  pub target: String,
47  pub count: usize,
48}
49
50/// Compressed transform summary for a definition.
51#[derive(Debug, Clone, Serialize, Deserialize, Default)]
52pub struct TransformInfo {
53  pub summary: String,
54  #[serde(skip_serializing_if = "Vec::is_empty")]
55  pub control: Vec<String>,
56  #[serde(skip_serializing_if = "Vec::is_empty")]
57  pub calls: Vec<String>,
58}
59
60/// Per-definition decomposition node.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct EffectsGraphNode {
63  pub ns: String,
64  pub def: String,
65  pub fqn: String,
66  #[serde(skip_serializing_if = "Option::is_none")]
67  pub doc: Option<String>,
68  pub source: String,
69  #[serde(skip_serializing_if = "Vec::is_empty")]
70  pub state: Vec<StateItem>,
71  pub transform: TransformInfo,
72  #[serde(skip_serializing_if = "Vec::is_empty")]
73  pub effects: Vec<EffectItem>,
74  #[serde(skip_serializing_if = "Vec::is_empty")]
75  pub children: Vec<EffectsGraphNode>,
76  #[serde(skip_serializing_if = "std::ops::Not::not")]
77  pub circular: bool,
78  #[serde(skip_serializing_if = "std::ops::Not::not")]
79  pub seen: bool,
80  /// True when max_depth limit prevented expanding children (analysis still present).
81  #[serde(skip_serializing_if = "std::ops::Not::not")]
82  pub depth_exceeded: bool,
83}
84
85/// Analysis result.
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct EffectsGraphResult {
88  pub entry: String,
89  pub tree: EffectsGraphNode,
90  pub stats: EffectsGraphStats,
91  pub display: EffectsGraphDisplayMeta,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct EffectsGraphDisplayMeta {
96  /// configured `--max-depth` (0 = unlimited)
97  pub max_depth_limit: usize,
98  pub detail: String,
99  pub include_core: bool,
100  pub ns_prefix: Option<String>,
101  /// package root inferred from entry or `--ns-prefix`, used to shorten display paths
102  pub package_root: Option<String>,
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct EffectsGraphStats {
107  pub reachable_count: usize,
108  pub effect_sites: usize,
109  pub state_items: usize,
110  pub max_depth: usize,
111  pub subgraph_count: usize,
112}
113
114/// Effect kind reported when a call target carries no effect declaration that the analyzer can read.
115pub const UNKNOWN_EFFECT_KIND: &str = "unknown";
116
117/// Effect tags for core syntax forms without a Snapshot entry.
118const HIDDEN_CORE_SYNTAX_TAGS: &[(CalcitSyntax, &[&str])] = &[
119  (CalcitSyntax::DefWasmExport, &[]),
120  (CalcitSyntax::DefWasmImport, &[]),
121  (CalcitSyntax::JsCast, &[]),
122  (CalcitSyntax::ParseCirruEdnAs, &[]),
123  (CalcitSyntax::AnyBox, &[]),
124  (CalcitSyntax::AnyDowncast, &[]),
125  (CalcitSyntax::AssertTraits, &["control"]),
126  (CalcitSyntax::DynBox, &[]),
127  (CalcitSyntax::Match, &[]),
128];
129
130/// Effect tags for compiler-internal core procs without a public Snapshot entry.
131const HIDDEN_CORE_PROC_TAGS: &[(CalcitProc, &[&str])] = &[
132  (CalcitProc::NativeNamedEnumNew, &[]),
133  (CalcitProc::NativeStructImplTraits, &[]),
134  (CalcitProc::NativeEnumImplTraits, &[]),
135];
136
137/// Effect declarations for core definitions, syntax forms and methods.
138struct TagIndex {
139  core: HashMap<String, HashSet<EdnTag>>,
140  /// Method name (without the leading `.`) to the union of effect kinds of every core
141  /// implementation; `unknown` when an implementation names a definition outside core.
142  core_methods: HashMap<String, Vec<String>>,
143}
144
145impl TagIndex {
146  fn load() -> Result<Self, String> {
147    let snapshot = calcit_core::load_core_snapshot()?;
148    let mut core = HashMap::new();
149    let mut method_impls: Vec<(String, Option<String>)> = vec![];
150    if let Some(file) = snapshot.files.get("calcit.core") {
151      for (def, entry) in &file.defs {
152        core.insert(def.clone(), entry.tags.clone());
153        collect_core_method_impls(&entry.code, def, &mut method_impls);
154      }
155    }
156    for (syntax, tags) in HIDDEN_CORE_SYNTAX_TAGS {
157      let name = syntax.to_string();
158      core
159        .entry(name)
160        .or_insert_with(|| tags.iter().map(|tag| EdnTag::new(*tag)).collect());
161    }
162    for (proc, tags) in HIDDEN_CORE_PROC_TAGS {
163      let name = proc.as_ref().to_owned();
164      core
165        .entry(name)
166        .or_insert_with(|| tags.iter().map(|tag| EdnTag::new(*tag)).collect());
167    }
168
169    let mut core_methods: HashMap<String, Vec<String>> = HashMap::new();
170    for (method, implementation) in method_impls {
171      let kinds = match implementation.as_deref().and_then(|name| core.get(name)) {
172        Some(tags) => tags_to_effect_kinds(tags),
173        None => vec![UNKNOWN_EFFECT_KIND.to_string()],
174      };
175      let entry = core_methods.entry(method).or_default();
176      entry.extend(kinds);
177      entry.sort();
178      entry.dedup();
179    }
180    Ok(TagIndex { core, core_methods })
181  }
182
183  fn tags_for(&self, name: &str) -> Option<&HashSet<EdnTag>> {
184    self.core.get(name)
185  }
186}
187
188/// Collect `(method, implementation)` pairs from core impl tables:
189/// `defimpl Name Trait (.method impl) ...` and `&impl::new Name (:: :method impl) ...`.
190/// An inline implementation (e.g. `(:: :empty? $ defn &enum:empty?-impl ...)`) belongs to the
191/// enclosing core definition `owner` and inherits its tags.
192fn collect_core_method_impls(code: &Cirru, owner: &str, out: &mut Vec<(String, Option<String>)>) {
193  let Cirru::List(items) = code else {
194    return;
195  };
196  let leaf = |node: &Cirru| match node {
197    Cirru::Leaf(text) => Some(text.to_string()),
198    Cirru::List(_) => None,
199  };
200  match items.first().and_then(leaf).as_deref() {
201    Some("defimpl") => {
202      for pair in items.iter().skip(3) {
203        if let Cirru::List(pair) = pair
204          && let [key, value] = pair.as_slice()
205          && let Some(method) = leaf(key).as_deref().and_then(|text| text.strip_prefix('.')).map(str::to_owned)
206        {
207          out.push((method, leaf(value).or_else(|| Some(owner.to_string()))));
208        }
209      }
210    }
211    Some("&impl::new") => {
212      for pair in items.iter().skip(2) {
213        if let Cirru::List(pair) = pair
214          && let [head, key, value] = pair.as_slice()
215          && leaf(head).as_deref() == Some("::")
216          && let Some(method) = leaf(key).as_deref().and_then(|text| text.strip_prefix(':')).map(str::to_owned)
217        {
218          out.push((method, leaf(value).or_else(|| Some(owner.to_string()))));
219        }
220      }
221    }
222    _ => {}
223  }
224  for item in items {
225    collect_core_method_impls(item, owner, out);
226  }
227}
228
229/// Method names implemented outside `calcit.core` (project and module `defimpl` / `&impl::new`).
230/// A call to one of these methods may dispatch to code whose effects are not declared at the
231/// call site, so it is reported as `unknown`.
232fn collect_program_method_names() -> HashSet<String> {
233  let mut names = HashSet::new();
234  let Ok(program_code) = PROGRAM_CODE_DATA.read() else {
235    return names;
236  };
237  for (ns, file) in program_code.iter() {
238    if ns.as_ref() == "calcit.core" {
239      continue;
240    }
241    for entry in file.defs.values() {
242      collect_program_methods_in(&entry.code, &mut names);
243    }
244  }
245  names
246}
247
248fn collect_program_methods_in(code: &Calcit, names: &mut HashSet<String>) {
249  match code {
250    Calcit::List(list) => {
251      let head = list.first().and_then(extract_symbol_name);
252      match head.as_deref() {
253        Some("defimpl") => {
254          for pair in list.iter().skip(3) {
255            if let Calcit::List(pair) = pair
256              && let Some(Calcit::Method(name, _)) = pair.first()
257            {
258              names.insert(name.to_string());
259            }
260          }
261        }
262        Some("&impl::new") => {
263          for pair in list.iter().skip(2) {
264            if let Calcit::List(pair) = pair
265              && let Some(Calcit::Tag(tag)) = pair.get(1)
266            {
267              names.insert(tag.ref_str().to_string());
268            }
269          }
270        }
271        _ => {}
272      }
273      for item in list.iter() {
274        collect_program_methods_in(item, names);
275      }
276    }
277    Calcit::Fn { info, .. } => {
278      for expr in info.body.iter() {
279        collect_program_methods_in(expr, names);
280      }
281    }
282    Calcit::Macro { info, .. } => {
283      for expr in info.body.iter() {
284        collect_program_methods_in(expr, names);
285      }
286    }
287    _ => {}
288  }
289}
290
291struct DefAnalysis {
292  /// Lexical scopes entered while walking. Each `defn` / `defmacro` / `fn` pushes its parameters
293  /// (`true`); each binding form pushes the names it binds (`false`), shadowing outer parameters.
294  /// Calling a parameter calls a function value supplied by the caller, whose effects are `unknown`.
295  scopes: Vec<HashMap<String, bool>>,
296  state: Vec<StateItem>,
297  effects: HashMap<String, EffectItem>,
298  transform: TransformInfo,
299  /// Effect kinds declared by `:tags` on project/module definitions this one calls, keyed by `ns/def`.
300  declared: HashMap<String, Vec<String>>,
301}
302
303pub struct EffectsGraphAnalyzer {
304  config: EffectsGraphConfig,
305  tag_index: TagIndex,
306  program_methods: HashSet<String>,
307  visited: HashSet<String>,
308  expanded: HashMap<String, bool>,
309  reachable: HashSet<String>,
310  max_depth: usize,
311  total_effect_sites: usize,
312  total_state_items: usize,
313}
314
315impl EffectsGraphAnalyzer {
316  pub fn new(config: EffectsGraphConfig) -> Result<Self, String> {
317    Ok(EffectsGraphAnalyzer {
318      config,
319      tag_index: TagIndex::load()?,
320      program_methods: collect_program_method_names(),
321      visited: HashSet::new(),
322      expanded: HashMap::new(),
323      reachable: HashSet::new(),
324      max_depth: 0,
325      total_effect_sites: 0,
326      total_state_items: 0,
327    })
328  }
329
330  pub fn analyze(&mut self, entry_ns: &str, entry_def: &str) -> Result<EffectsGraphResult, String> {
331    let entry = format!("{entry_ns}/{entry_def}");
332    let mut tree = self.build_node(entry_ns, entry_def, 0)?;
333    if let Some(ref prefix) = self.config.ns_prefix {
334      tree = prune_tree_by_ns_prefix(tree, prefix);
335    }
336
337    let subgraph_count = count_subgraph_nodes(&tree);
338
339    let stats = EffectsGraphStats {
340      reachable_count: self.reachable.len(),
341      effect_sites: self.total_effect_sites,
342      state_items: self.total_state_items,
343      max_depth: self.max_depth,
344      subgraph_count,
345    };
346
347    let package_root = infer_package_root(entry_ns, &self.config.ns_prefix);
348
349    let display = EffectsGraphDisplayMeta {
350      max_depth_limit: self.config.max_depth,
351      detail: match self.config.detail {
352        EffectsGraphDetail::Full => "full".into(),
353        EffectsGraphDetail::Minimal => "minimal".into(),
354        EffectsGraphDetail::Summary => "summary".into(),
355      },
356      include_core: self.config.include_core,
357      ns_prefix: self.config.ns_prefix.clone(),
358      package_root,
359    };
360
361    Ok(EffectsGraphResult {
362      entry,
363      tree,
364      stats,
365      display,
366    })
367  }
368
369  fn build_node(&mut self, ns: &str, def: &str, depth: usize) -> Result<EffectsGraphNode, String> {
370    let fqn = format!("{ns}/{def}");
371    if depth > self.max_depth {
372      self.max_depth = depth;
373    }
374
375    if self.visited.contains(&fqn) {
376      return Ok(EffectsGraphNode {
377        ns: ns.to_string(),
378        def: def.to_string(),
379        fqn,
380        doc: None,
381        source: self.source_type(ns),
382        state: vec![],
383        transform: TransformInfo::default(),
384        effects: vec![],
385        children: vec![],
386        circular: true,
387        seen: false,
388        depth_exceeded: false,
389      });
390    }
391
392    if let Some(&had_children) = self.expanded.get(&fqn) {
393      return Ok(EffectsGraphNode {
394        ns: ns.to_string(),
395        def: def.to_string(),
396        fqn,
397        doc: None,
398        source: self.source_type(ns),
399        state: vec![],
400        transform: TransformInfo::default(),
401        effects: vec![],
402        children: vec![],
403        circular: false,
404        seen: had_children,
405        depth_exceeded: false,
406      });
407    }
408
409    self.visited.insert(fqn.clone());
410    self.reachable.insert(fqn.clone());
411
412    let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
413    let (code, doc, schema_return) = match program_code.get(ns) {
414      Some(file) => match file.defs.get(def) {
415        Some(entry) => {
416          let doc = if entry.doc.is_empty() { None } else { Some(entry.doc.to_string()) };
417          let return_hint = format_type_hint(&entry.schema);
418          (Some(entry.code.clone()), doc, return_hint)
419        }
420        None => (None, None, None),
421      },
422      None => (None, None, None),
423    };
424
425    let mut children = vec![];
426    let mut analysis = DefAnalysis {
427      scopes: vec![],
428      state: vec![],
429      effects: HashMap::new(),
430      transform: TransformInfo::default(),
431      declared: HashMap::new(),
432    };
433
434    let depth_exceeded = self.config.max_depth > 0 && depth >= self.config.max_depth;
435
436    if let Some(code) = code {
437      let call_refs = extract_call_targets(&code, ns);
438      // Effects declared on called project/module definitions are read while the program is locked.
439      for (call_ns, call_def) in &call_refs {
440        if call_ns == "calcit.core" {
441          continue;
442        }
443        if let Some(entry) = program_code.get(call_ns.as_str()).and_then(|file| file.defs.get(call_def.as_str())) {
444          let kinds = tags_to_effect_kinds(&entry.tags.iter().cloned().collect());
445          if !kinds.is_empty() {
446            analysis.declared.insert(format!("{call_ns}/{call_def}"), kinds);
447          }
448        }
449      }
450      // Always analyze the code for state/effects/transform, even at max depth
451      self.analyze_code(&code, ns, doc.as_deref(), &mut analysis);
452      if def.starts_with('*') {
453        enrich_atom_def_state(ns, def, &mut analysis.state);
454      }
455      if let Some(hint) = schema_return {
456        analysis.state.push(StateItem {
457          kind: "return".into(),
458          name: "return".into(),
459          type_hint: Some(hint),
460        });
461      }
462
463      drop(program_code);
464
465      // Only build children if not at max depth
466      if !depth_exceeded {
467        for (call_ns, call_def) in call_refs {
468          if !self.config.include_core && self.is_core_ns(&call_ns) {
469            continue;
470          }
471          if call_ns == ns && call_def == def {
472            continue;
473          }
474          children.push(self.build_node(&call_ns, &call_def, depth + 1)?);
475        }
476      }
477    } else {
478      drop(program_code);
479    }
480
481    self.visited.remove(&fqn);
482    self.expanded.insert(fqn.clone(), !children.is_empty());
483
484    self.total_effect_sites += analysis.effects.values().map(|e| e.count).sum::<usize>();
485    self.total_state_items += analysis.state.len();
486
487    let effects: Vec<EffectItem> = {
488      let mut items: Vec<EffectItem> = analysis.effects.into_values().collect();
489      items.sort_by(|a, b| a.kind.cmp(&b.kind).then(a.target.cmp(&b.target)));
490      items
491    };
492
493    Ok(EffectsGraphNode {
494      ns: ns.to_string(),
495      def: def.to_string(),
496      fqn,
497      doc,
498      source: self.source_type(ns),
499      state: analysis.state,
500      transform: analysis.transform,
501      effects,
502      children,
503      circular: false,
504      seen: false,
505      depth_exceeded,
506    })
507  }
508
509  fn analyze_code(&self, code: &Calcit, current_ns: &str, doc: Option<&str>, out: &mut DefAnalysis) {
510    match code {
511      Calcit::Fn { info, .. } => {
512        extract_fn_params(&info.args, &info.arg_types, &mut out.state);
513        for expr in info.body.iter() {
514          self.walk_expr(expr, current_ns, out, 0);
515        }
516        if out.transform.summary.is_empty() {
517          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
518        }
519      }
520      Calcit::Macro { info, .. } => {
521        for expr in info.body.iter() {
522          self.walk_expr(expr, current_ns, out, 0);
523        }
524        if out.transform.summary.is_empty() {
525          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
526        }
527      }
528      _ => {
529        self.walk_expr(code, current_ns, out, 0);
530        if out.transform.summary.is_empty() {
531          out.transform.summary = doc_or_generated_summary(doc, &out.transform.control, &out.transform.calls);
532        }
533      }
534    }
535  }
536
537  fn walk_expr(&self, code: &Calcit, current_ns: &str, out: &mut DefAnalysis, depth: usize) {
538    if let Calcit::List(list) = code {
539      // A parameter list is not a call; its names form a new scope for the body.
540      let args_index = list.first().and_then(fn_form_args_index);
541      let binding = list.first().and_then(binding_form_kind);
542      let mut pushed_scope = false;
543      if let Some(Calcit::List(args)) = args_index.and_then(|index| list.get(index)) {
544        let mut scope = HashMap::new();
545        collect_bound_names(&Calcit::List(args.clone()), true, &mut scope);
546        out.scopes.push(scope);
547        pushed_scope = true;
548      }
549      // `(receiver .method args)` is a method call on `receiver`, not a call of `receiver`.
550      let call_head = match (list.first(), list.get(1)) {
551        (Some(first), Some(method @ Calcit::Method(..))) if !matches!(first, Calcit::Method(..)) => Some(method),
552        (first, _) => first,
553      };
554      if let Some(head) = call_head {
555        self.inspect_call_head(head, Some(list), current_ns, out);
556        if depth < 3 {
557          record_control_head(head, &mut out.transform.control);
558        }
559      }
560      // Binding pairs such as `(x value)` in `let` / `loop` / `&let` are not calls either;
561      // only their values are walked, and the bound names shadow outer parameters in the body.
562      let bindings_index = binding.as_ref().map(|_| 1);
563      // Clauses such as `(pattern body)` in `case` / `match` / `cond` are not calls; walk their parts.
564      let clauses_from = list.first().and_then(clause_form_start);
565      for (index, item) in list.iter().enumerate() {
566        if Some(index) == args_index {
567          continue;
568        }
569        if Some(index) == bindings_index
570          && let Some(kind) = &binding
571        {
572          let mut scope = HashMap::new();
573          match kind {
574            // `let[] (a b) value`: names only, the value comes next.
575            BindingForm::Destructure => {
576              collect_bound_names(item, false, &mut scope);
577            }
578            BindingForm::Single | BindingForm::Many => {
579              let pairs: Vec<&Calcit> = match (kind, item) {
580                (BindingForm::Many, Calcit::List(bindings)) => bindings.iter().collect(),
581                _ => vec![item],
582              };
583              for pair in pairs {
584                if let Calcit::List(pair) = pair {
585                  for value in pair.iter().skip(1) {
586                    self.walk_expr(value, current_ns, out, depth + 1);
587                  }
588                  if let Some(name) = pair.first() {
589                    collect_bound_names(name, false, &mut scope);
590                  }
591                }
592              }
593            }
594          }
595          out.scopes.push(scope);
596          pushed_scope = true;
597          continue;
598        }
599        if clauses_from.is_some_and(|start| index >= start)
600          && let Calcit::List(clause) = item
601        {
602          for part in clause.iter() {
603            self.walk_expr(part, current_ns, out, depth + 1);
604          }
605          continue;
606        }
607        self.walk_expr(item, current_ns, out, depth + 1);
608      }
609      if pushed_scope {
610        out.scopes.pop();
611      }
612      return;
613    }
614
615    match code {
616      Calcit::Fn { info, .. } => {
617        for expr in info.body.iter() {
618          self.walk_expr(expr, current_ns, out, depth);
619        }
620      }
621      Calcit::Macro { info, .. } => {
622        for expr in info.body.iter() {
623          self.walk_expr(expr, current_ns, out, depth);
624        }
625      }
626      Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => {
627        self.walk_expr(code, current_ns, out, depth);
628      }
629      Calcit::Enum(enum_value) => {
630        for item in enum_value.extra.iter() {
631          self.walk_expr(item, current_ns, out, depth);
632        }
633      }
634      Calcit::Map(map) => {
635        for (k, v) in map.iter() {
636          self.walk_expr(k, current_ns, out, depth);
637          self.walk_expr(v, current_ns, out, depth);
638        }
639      }
640      Calcit::Set(set) => {
641        for item in set.iter() {
642          self.walk_expr(item, current_ns, out, depth);
643        }
644      }
645      _ => {}
646    }
647  }
648
649  fn inspect_call_head(&self, head: &Calcit, list: Option<&calcit_core::calcit::CalcitList>, current_ns: &str, out: &mut DefAnalysis) {
650    if let Calcit::Symbol { sym, .. } = head
651      && out.is_param(sym)
652    {
653      let key = format!("{UNKNOWN_EFFECT_KIND}::{sym}");
654      out
655        .effects
656        .entry(key)
657        .and_modify(|item| item.count += 1)
658        .or_insert_with(|| EffectItem {
659          kind: UNKNOWN_EFFECT_KIND.to_string(),
660          target: sym.to_string(),
661          count: 1,
662        });
663      return;
664    }
665    let Some(call) = resolve_call_head(head, current_ns) else {
666      return;
667    };
668
669    if let CallHead::Core(name) = &call
670      && is_state_operator(name)
671    {
672      let target = extract_state_target(list, name);
673      record_state_operator(name, &target, list, current_ns, &mut out.state);
674      if matches!(name.as_str(), "defref" | "ref" | "reset!" | "swap!" | "deref" | "set!") {
675        return;
676      }
677    }
678
679    let (mut kinds, target) = self.classify_call_head(&call);
680    // `hint-fn` carries type hints in general; only the enclosing function's own schema with
681    // `:async true` declares async, the same contract the JavaScript lowering checks.
682    if matches!(&call, CallHead::Core(name) if name == "hint-fn") && !list.is_some_and(hint_marks_async) {
683      kinds.clear();
684    }
685    for kind in kinds {
686      let key = format!("{kind}::{target}");
687      out
688        .effects
689        .entry(key)
690        .and_modify(|item| item.count += 1)
691        .or_insert_with(|| EffectItem {
692          kind,
693          target: target.clone(),
694          count: 1,
695        });
696    }
697
698    if let Some((call_ns, call_def)) = resolve_def_call(head, current_ns) {
699      let fqn = format!("{call_ns}/{call_def}");
700      if let Some(kinds) = out.declared.get(&fqn).cloned() {
701        for kind in kinds {
702          let key = format!("{kind}::{fqn}");
703          out
704            .effects
705            .entry(key)
706            .and_modify(|item| item.count += 1)
707            .or_insert_with(|| EffectItem {
708              kind,
709              target: fqn.clone(),
710              count: 1,
711            });
712        }
713      }
714      if !is_meaningful_call_target(&call_ns, &call_def, self.config.include_core) {
715        return;
716      }
717      let target = format!("{call_ns}/{call_def}");
718      if !out.transform.calls.contains(&target) {
719        out.transform.calls.push(target);
720      }
721    }
722  }
723
724  /// Effect kinds of one call site, derived only from declarations:
725  /// core definition tags, registered proc descriptor tags and core impl tables.
726  /// Calls into project/module definitions add nothing here unless the callee declares effect
727  /// `:tags` (see `DefAnalysis::declared`); the callee body's own effects are reported on its node.
728  fn classify_call_head(&self, call: &CallHead) -> (Vec<String>, String) {
729    match call {
730      CallHead::Core(name) => (classify_call(name, self.tag_index.tags_for(name)), name.clone()),
731      CallHead::Registered(name) => (classify_call(name, None), name.clone()),
732      CallHead::Def(..) => (vec![], String::new()),
733      CallHead::MissingDef(ns, def) => (vec![UNKNOWN_EFFECT_KIND.to_string()], format!("{ns}/{def}")),
734      CallHead::JsGlobal(name) => (vec!["interop/js".to_string()], name.clone()),
735      CallHead::Method(name, kind) => (self.classify_method(name, kind), method_call_label(name, kind)),
736    }
737  }
738
739  fn classify_method(&self, name: &str, kind: &MethodKind) -> Vec<String> {
740    match kind {
741      // Field and tag reads do not dispatch to code.
742      MethodKind::Access
743      | MethodKind::AccessOptional
744      | MethodKind::TagAccess
745      | MethodKind::ExternalAccess(_)
746      | MethodKind::ExternalGet(_) => {
747        vec![]
748      }
749      MethodKind::InvokeNative | MethodKind::InvokeNativeOptional | MethodKind::ExternalSet(_) | MethodKind::ExternalInvoke(_) => {
750        vec!["interop/js".to_string()]
751      }
752      MethodKind::Invoke(_) => {
753        if self.program_methods.contains(name) {
754          return vec![UNKNOWN_EFFECT_KIND.to_string()];
755        }
756        match self.tag_index.core_methods.get(name) {
757          Some(kinds) => kinds.clone(),
758          None => vec![UNKNOWN_EFFECT_KIND.to_string()],
759        }
760      }
761    }
762  }
763
764  fn source_type(&self, ns: &str) -> String {
765    if self.is_core_ns(ns) {
766      "core".into()
767    } else if ns.starts_with("js/") {
768      "external".into()
769    } else {
770      "project".into()
771    }
772  }
773
774  fn is_core_ns(&self, ns: &str) -> bool {
775    ns == "calcit.core" || ns.starts_with("calcit.")
776  }
777}
778
779fn extract_fn_params(
780  args: &CalcitFnArgs,
781  arg_types: &[std::sync::Arc<calcit_core::calcit::CalcitTypeAnnotation>],
782  state: &mut Vec<StateItem>,
783) {
784  match args {
785    CalcitFnArgs::Args(indices) => {
786      for (idx, local_idx) in indices.iter().enumerate() {
787        state.push(StateItem {
788          kind: "param".into(),
789          name: CalcitLocal::read_name(*local_idx),
790          type_hint: arg_types.get(idx).map(|t| t.to_string()),
791        });
792      }
793    }
794    CalcitFnArgs::MarkedArgs(labels) => {
795      let mut arg_idx = 0usize;
796      for label in labels {
797        if let calcit_core::calcit::CalcitArgLabel::Idx(local_idx) = label {
798          state.push(StateItem {
799            kind: "param".into(),
800            name: label.to_string(),
801            type_hint: arg_types.get(arg_idx).map(|t| t.to_string()),
802          });
803          arg_idx += 1;
804          let _ = local_idx;
805        }
806      }
807    }
808  }
809}
810
811/// A call head resolved without guessing from its spelling.
812#[derive(Debug, Clone, PartialEq, Eq)]
813enum CallHead {
814  /// `calcit.core` definition, builtin proc or syntax.
815  Core(String),
816  /// Proc registered by the host (platform APIs, dylib bindings).
817  Registered(String),
818  /// Project or module definition with loaded code; analyzed as its own call-graph node.
819  Def(String, String),
820  /// Qualified reference whose definition is not loaded.
821  MissingDef(String, String),
822  /// JavaScript global accessed through the `js/` namespace or a JS default import.
823  JsGlobal(String),
824  /// Method dispatch `.name`.
825  Method(String, MethodKind),
826}
827
828impl DefAnalysis {
829  /// Whether `name` resolves to a parameter in the innermost scope that binds it.
830  fn is_param(&self, name: &str) -> bool {
831    self.scopes.iter().rev().find_map(|scope| scope.get(name).copied()).unwrap_or(false)
832  }
833}
834
835/// True when a one-argument `hint-fn` schema marks the enclosing function async.
836/// Nested function types (such as an async callback parameter) do not count.
837fn hint_marks_async(list: &calcit_core::calcit::CalcitList) -> bool {
838  CalcitTypeAnnotation::hint_form_marks_async(&Calcit::List(std::sync::Arc::new(list.clone())))
839}
840
841/// Collect symbols bound by a parameter list, a binding name or a destructuring pattern.
842fn collect_bound_names(form: &Calcit, is_param: bool, scope: &mut HashMap<String, bool>) {
843  match form {
844    Calcit::Symbol { sym, .. } if !matches!(sym.as_ref(), "&" | "?" | "[]" | "{}" | ",") => {
845      scope.insert(sym.to_string(), is_param);
846    }
847    Calcit::Local(local) => {
848      scope.insert(local.sym.to_string(), is_param);
849    }
850    Calcit::List(items) => {
851      for item in items.iter() {
852        collect_bound_names(item, is_param, scope);
853      }
854    }
855    _ => {}
856  }
857}
858
859/// Index of the first clause in `case value clauses...`, `match value clauses...` and
860/// `cond clauses...` forms.
861fn clause_form_start(head: &Calcit) -> Option<usize> {
862  let name = match head {
863    Calcit::Symbol { sym, .. } => sym.to_string(),
864    Calcit::Syntax(syntax, _) => syntax.to_string(),
865    _ => return None,
866  };
867  match name.as_str() {
868    "case" | "match" | "tag-match" | "struct-match" => Some(2),
869    "cond" => Some(1),
870    _ => None,
871  }
872}
873
874enum BindingForm {
875  /// `&let (name value) ...`, `if-let (name value) ...`, `when-let (name value) ...`,
876  /// `&doseq (name xs) ...`, `doseq (name xs) ...`
877  Single,
878  /// `let[] (a b) value ...`
879  Destructure,
880  /// `let ((name value) ...) ...`, `loop ((name value) ...) ...`
881  Many,
882}
883
884fn binding_form_kind(head: &Calcit) -> Option<BindingForm> {
885  let name = match head {
886    Calcit::Symbol { sym, .. } => sym.to_string(),
887    Calcit::Syntax(syntax, _) => syntax.to_string(),
888    _ => return None,
889  };
890  match name.as_str() {
891    "&let" | "if-let" | "when-let" | "&doseq" | "doseq" => Some(BindingForm::Single),
892    "let[]" | "let{}" => Some(BindingForm::Destructure),
893    "let" | "loop" => Some(BindingForm::Many),
894    _ => None,
895  }
896}
897
898/// Index of the parameter list in `defn name (args) ...`, `defmacro name (args) ...` and
899/// `fn (args) ...` forms.
900fn fn_form_args_index(head: &Calcit) -> Option<usize> {
901  let name = match head {
902    Calcit::Symbol { sym, .. } => sym.to_string(),
903    Calcit::Syntax(syntax, _) => syntax.to_string(),
904    _ => return None,
905  };
906  match name.as_str() {
907    "defn" | "defmacro" => Some(2),
908    "fn" => Some(1),
909    _ => None,
910  }
911}
912
913/// Display a method call with the same prefix the source uses (`.name`, `.!name`, `.?!name`).
914fn method_call_label(name: &str, kind: &MethodKind) -> String {
915  let prefix = match kind {
916    MethodKind::InvokeNative => ".!",
917    MethodKind::InvokeNativeOptional => ".?!",
918    MethodKind::Access => ".-",
919    MethodKind::AccessOptional => ".?-",
920    MethodKind::TagAccess => ".:",
921    _ => ".",
922  };
923  format!("{prefix}{name}")
924}
925
926fn def_call_head(ns: &str, def: &str) -> CallHead {
927  if ns == "calcit.core" {
928    return CallHead::Core(def.to_string());
929  }
930  // JS module imports keep their string namespace, e.g. `(|os :as os)`.
931  if let Some(module) = ns.strip_prefix('|').or_else(|| ns.strip_prefix('"')) {
932    return CallHead::JsGlobal(format!("{module}/{def}"));
933  }
934  let loaded = PROGRAM_CODE_DATA
935    .read()
936    .is_ok_and(|program_code| program_code.get(ns).is_some_and(|file| file.defs.contains_key(def)));
937  if loaded {
938    CallHead::Def(ns.to_string(), def.to_string())
939  } else {
940    CallHead::MissingDef(ns.to_string(), def.to_string())
941  }
942}
943
944/// Resolve a call head to what it refers to. Bare symbols that resolve to nothing are local
945/// bindings or parameters (calls through function values), which are not classified.
946fn resolve_call_head(head: &Calcit, current_ns: &str) -> Option<CallHead> {
947  match head {
948    Calcit::Proc(proc) => Some(CallHead::Core(proc.to_string())),
949    Calcit::Syntax(syntax, _) => Some(CallHead::Core(syntax.to_string())),
950    Calcit::Registered(name) => Some(CallHead::Registered(name.to_string())),
951    Calcit::Import(import) => Some(def_call_head(&import.ns, &import.def)),
952    Calcit::Method(name, kind) => Some(CallHead::Method(name.to_string(), kind.clone())),
953    Calcit::Fn { info, .. } => info
954      .def_ref
955      .as_ref()
956      .map(|def_ref| def_call_head(&def_ref.def_ns, &def_ref.def_name)),
957    Calcit::Symbol { sym, .. } => resolve_symbol_head(sym, current_ns),
958    _ => None,
959  }
960}
961
962fn resolve_symbol_head(sym: &str, current_ns: &str) -> Option<CallHead> {
963  let program_code = PROGRAM_CODE_DATA.read().ok()?;
964  if let Some(file) = program_code.get(current_ns) {
965    if file.defs.contains_key(sym) {
966      drop(program_code);
967      return Some(def_call_head(current_ns, sym));
968    }
969    if let Some(rule) = file.import_map.get(sym) {
970      let rule = rule.clone();
971      drop(program_code);
972      return match &*rule {
973        ImportRule::NsReferDef(ns, def) => Some(def_call_head(ns, def)),
974        ImportRule::NsDefault(ns) => Some(CallHead::JsGlobal(format!("{}/default", ns.trim_start_matches(['|', '"'])))),
975        ImportRule::NsAs(_) => None,
976      };
977    }
978  }
979  if program_code.get("calcit.core").is_some_and(|core| core.defs.contains_key(sym)) {
980    return Some(CallHead::Core(sym.to_string()));
981  }
982  if CalcitProc::parse_source_proc(sym).is_some() {
983    return Some(CallHead::Core(sym.to_string()));
984  }
985  if builtins::is_registered_proc(sym) {
986    return Some(CallHead::Registered(sym.to_string()));
987  }
988  if sym.starts_with("js/") {
989    return Some(CallHead::JsGlobal(sym.to_string()));
990  }
991  let (alias, def) = sym.split_once('/')?;
992  if alias.is_empty() || def.is_empty() {
993    return None;
994  }
995  let target_ns = match program_code.get(current_ns).and_then(|file| file.import_map.get(alias)) {
996    Some(rule) => match &**rule {
997      ImportRule::NsAs(ns) => ns.to_string(),
998      ImportRule::NsDefault(ns) => return Some(CallHead::JsGlobal(format!("{}/{def}", ns.trim_start_matches(['|', '"'])))),
999      ImportRule::NsReferDef(..) => return None,
1000    },
1001    None => alias.to_string(),
1002  };
1003  drop(program_code);
1004  Some(def_call_head(&target_ns, def))
1005}
1006
1007fn resolve_def_call(head: &Calcit, current_ns: &str) -> Option<(String, String)> {
1008  if !matches!(head, Calcit::Import(_) | Calcit::Symbol { .. } | Calcit::Fn { .. }) {
1009    return None;
1010  }
1011  match resolve_call_head(head, current_ns)? {
1012    CallHead::Def(ns, def) | CallHead::MissingDef(ns, def) => Some((ns, def)),
1013    CallHead::Core(name) => {
1014      let program_code = PROGRAM_CODE_DATA.read().ok()?;
1015      let is_core_def = program_code
1016        .get("calcit.core")
1017        .is_some_and(|core| core.defs.contains_key(name.as_str()));
1018      is_core_def.then(|| ("calcit.core".to_string(), name))
1019    }
1020    _ => None,
1021  }
1022}
1023
1024fn extract_call_targets(code: &Calcit, current_ns: &str) -> Vec<(String, String)> {
1025  let mut calls = vec![];
1026  extract_call_targets_recursive(code, current_ns, &mut calls);
1027  let mut seen = HashSet::new();
1028  calls.retain(|item| seen.insert(item.clone()));
1029  calls
1030}
1031
1032fn extract_call_targets_recursive(code: &Calcit, current_ns: &str, calls: &mut Vec<(String, String)>) {
1033  if let Some(pair) = resolve_def_call_from_expr(code, current_ns) {
1034    calls.push(pair);
1035  }
1036  match code {
1037    Calcit::List(list) => {
1038      let _ = list.traverse_result::<String>(&mut |item| {
1039        extract_call_targets_recursive(item, current_ns, calls);
1040        Ok(())
1041      });
1042    }
1043    Calcit::Fn { info, .. } => {
1044      for expr in info.body.iter() {
1045        extract_call_targets_recursive(expr, current_ns, calls);
1046      }
1047    }
1048    Calcit::Macro { info, .. } => {
1049      for expr in info.body.iter() {
1050        extract_call_targets_recursive(expr, current_ns, calls);
1051      }
1052    }
1053    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => {
1054      extract_call_targets_recursive(code, current_ns, calls);
1055    }
1056    Calcit::Enum(enum_value) => {
1057      for item in enum_value.extra.iter() {
1058        extract_call_targets_recursive(item, current_ns, calls);
1059      }
1060    }
1061    Calcit::Map(map) => {
1062      for (k, v) in map.iter() {
1063        extract_call_targets_recursive(k, current_ns, calls);
1064        extract_call_targets_recursive(v, current_ns, calls);
1065      }
1066    }
1067    Calcit::Set(set) => {
1068      for item in set.iter() {
1069        extract_call_targets_recursive(item, current_ns, calls);
1070      }
1071    }
1072    _ => {}
1073  }
1074}
1075
1076fn resolve_def_call_from_expr(code: &Calcit, current_ns: &str) -> Option<(String, String)> {
1077  match code {
1078    Calcit::Import(import) => Some((import.ns.to_string(), import.def.to_string())),
1079    Calcit::List(list) => list.first().and_then(|head| resolve_def_call(head, current_ns)),
1080    _ => None,
1081  }
1082}
1083
1084fn is_state_operator(name: &str) -> bool {
1085  matches!(
1086    name,
1087    "defref" | "reset!" | "swap!" | "ref" | "deref" | "add-watch!" | "remove-watch!" | "set!"
1088  )
1089}
1090
1091fn record_state_operator(
1092  op_name: &str,
1093  target: &str,
1094  list: Option<&calcit_core::calcit::CalcitList>,
1095  current_ns: &str,
1096  state: &mut Vec<StateItem>,
1097) {
1098  let kind = match op_name {
1099    "defref" | "ref" => "atom-def",
1100    "reset!" | "swap!" => "atom-write",
1101    "add-watch!" | "remove-watch!" => "watch",
1102    "deref" => "atom-read",
1103    "set!" => "local-write",
1104    _ => "state",
1105  };
1106  let type_hint = if kind == "atom-def" {
1107    list
1108      .and_then(|items| ref_constructor_init_index(op_name).and_then(|idx| items.get(idx)))
1109      .and_then(|init| summarize_init_expr(init, current_ns))
1110      .map(|raw| finalize_schema_hint(&raw, current_ns))
1111      .or_else(|| lookup_atom_schema(current_ns, target))
1112  } else if kind == "watch" && target.starts_with('*') {
1113    lookup_atom_schema(current_ns, target)
1114  } else {
1115    None
1116  };
1117  state.push(StateItem {
1118    kind: kind.into(),
1119    name: target.into(),
1120    type_hint,
1121  });
1122}
1123
1124/// Extract the atom name from a state-operator call like `(swap! *store ...)`.
1125fn extract_state_target(list: Option<&calcit_core::calcit::CalcitList>, op_name: &str) -> String {
1126  let Some(list) = list else {
1127    return op_name.to_string();
1128  };
1129  match op_name {
1130    "swap!" | "reset!" | "deref" | "add-watch!" | "remove-watch!" | "set!" => {
1131      list.get(1).and_then(extract_symbol_name).unwrap_or_else(|| op_name.to_string())
1132    }
1133    "defref" => list.get(1).and_then(extract_symbol_name).unwrap_or_else(|| "?".to_string()),
1134    // A local `(ref init)` has no name of its own; index 1 is the initializer.
1135    "ref" => "?".to_string(),
1136    _ => op_name.to_string(),
1137  }
1138}
1139
1140/// Position of the initial value in a Ref constructor call:
1141/// `(defref name init)` takes it at index 2,
1142/// local `(ref init)` at index 1.
1143fn ref_constructor_init_index(op_name: &str) -> Option<usize> {
1144  match op_name {
1145    "defref" => Some(2),
1146    "ref" => Some(1),
1147    _ => None,
1148  }
1149}
1150
1151fn extract_symbol_name(calcit: &Calcit) -> Option<String> {
1152  match calcit {
1153    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
1154    Calcit::Str(s) => Some(s.to_string()),
1155    _ => None,
1156  }
1157}
1158
1159fn record_control_head(head: &Calcit, control: &mut Vec<String>) {
1160  let label = match head {
1161    Calcit::Syntax(CalcitSyntax::If, _) => Some("if"),
1162    Calcit::Syntax(CalcitSyntax::CoreLet, _) => Some("let"),
1163    Calcit::Syntax(CalcitSyntax::Match, _) => Some("match"),
1164    Calcit::Syntax(CalcitSyntax::Try, _) => Some("try"),
1165    Calcit::Proc(CalcitProc::Foldl) => Some("foldl"),
1166    Calcit::Symbol { sym, .. } if matches!(sym.as_ref(), "fold" | "foldl" | "map" | "filter") => Some(sym.as_ref()),
1167    _ => None,
1168  };
1169  if let Some(name) = label {
1170    control.push(name.to_string());
1171  }
1172}
1173
1174/// Effect kinds for a core or host-registered call target, taken only from declared tags.
1175///
1176/// Registered host procs use their descriptor tags; a descriptor that declares no tags at all is
1177/// reported as `unknown`. Core definitions use their Snapshot `:tags` (or the hidden proc table);
1178/// a core definition without effect tags is effect-free by contract.
1179pub fn classify_call(name: &str, tags: Option<&HashSet<EdnTag>>) -> Vec<String> {
1180  if let Some(tag_set) = tags {
1181    return tags_to_effect_kinds(tag_set);
1182  }
1183  if let Some(descriptor) = builtins::registered_proc_descriptor(name) {
1184    if descriptor.tags.is_empty() {
1185      return vec![UNKNOWN_EFFECT_KIND.to_string()];
1186    }
1187    return tags_to_effect_kinds(&descriptor.tags);
1188  }
1189  vec![UNKNOWN_EFFECT_KIND.to_string()]
1190}
1191
1192fn tags_to_effect_kinds(tags: &HashSet<EdnTag>) -> Vec<String> {
1193  let mut kinds = vec![];
1194  if tags.contains(&EdnTag::new("log")) {
1195    kinds.push("console".into());
1196  }
1197  if tags.contains(&EdnTag::new("file")) {
1198    kinds.push("io/file".into());
1199  }
1200  if tags.contains(&EdnTag::new("env")) {
1201    kinds.push("env".into());
1202  }
1203  if tags.contains(&EdnTag::new("control")) {
1204    kinds.push("control".into());
1205  }
1206  if tags.contains(&EdnTag::new("interop")) {
1207    kinds.push("interop/host".into());
1208  }
1209  if tags.contains(&EdnTag::new("async")) {
1210    kinds.push("async".into());
1211  }
1212  if tags.contains(&EdnTag::new("watch")) {
1213    kinds.push("state/watch".into());
1214  }
1215  if tags.contains(&EdnTag::new("io")) && kinds.is_empty() {
1216    kinds.push("io".into());
1217  }
1218  if tags.contains(&EdnTag::new("effect")) {
1219    kinds.push("effect".into());
1220  }
1221  kinds.sort();
1222  kinds.dedup();
1223  kinds
1224}
1225
1226fn format_type_hint(schema: &std::sync::Arc<CalcitTypeAnnotation>) -> Option<String> {
1227  format_schema_annotation(schema, "", MAX_SCHEMA_DEPTH)
1228}
1229
1230const MAX_SCHEMA_DEPTH: usize = 4;
1231
1232fn is_informative_schema(hint: &str) -> bool {
1233  !matches!(
1234    hint,
1235    "dynamic" | ":dynamic" | "ref" | ":ref" | "ref<:dynamic>" | "map<dynamic,dynamic>" | "map<:dynamic,:dynamic>"
1236  )
1237}
1238
1239fn is_coarse_schema_hint(hint: &str) -> bool {
1240  matches!(
1241    hint,
1242    "dynamic" | ":dynamic" | "ref" | ":ref" | "ref<:dynamic>" | "map<dynamic,dynamic>" | "map<:dynamic,:dynamic>" | ":map"
1243  )
1244}
1245
1246fn finalize_schema_hint(raw: &str, context_ns: &str) -> String {
1247  if raw.starts_with('{') || raw.contains(":states") || raw.contains(":records") {
1248    return raw.to_string();
1249  }
1250  expand_type_ref_path(raw, context_ns, MAX_SCHEMA_DEPTH).unwrap_or_else(|| raw.to_string())
1251}
1252
1253fn resolve_type_ref_path(ref_path: &str, context_ns: &str) -> Option<(String, String)> {
1254  let (ns_part, def) = ref_path.split_once('/')?;
1255  if let Some(real_ns) = lookup_ns_target_in_import(context_ns, ns_part) {
1256    return Some((real_ns.to_string(), def.to_string()));
1257  }
1258  let program = PROGRAM_CODE_DATA.read().ok()?;
1259  if program.get(ns_part).is_some() {
1260    return Some((ns_part.to_string(), def.to_string()));
1261  }
1262  if ns_part.contains('.') {
1263    return Some((ns_part.to_string(), def.to_string()));
1264  }
1265  let dotted = format!("{context_ns}.{ns_part}");
1266  if program.get(dotted.as_str()).is_some() {
1267    return Some((dotted, def.to_string()));
1268  }
1269  None
1270}
1271
1272fn expand_type_ref_path(ref_path: &str, context_ns: &str, depth: usize) -> Option<String> {
1273  if depth == 0 {
1274    return None;
1275  }
1276  let (ns, def) = resolve_type_ref_path(ref_path, context_ns)?;
1277  let template = expand_from_def_template(&ns, &def, context_ns, depth);
1278  let annotated = expand_from_type_annotation(&ns, &def, context_ns, depth);
1279  match (template, annotated) {
1280    (Some(t), Some(a)) if is_coarse_schema_hint(&a) => Some(t),
1281    (Some(t), Some(a)) => Some(pick_richer_schema(Some(&a), &t)),
1282    (Some(t), None) => Some(t),
1283    (None, Some(a)) => Some(a),
1284    (None, None) => None,
1285  }
1286}
1287
1288fn expand_from_type_annotation(ns: &str, def: &str, context_ns: &str, depth: usize) -> Option<String> {
1289  let schema = lookup_codegen_type_hint(ns, def).unwrap_or_else(|| lookup_def_schema(ns, def));
1290  format_schema_annotation(&schema, context_ns, depth)
1291}
1292
1293fn format_schema_annotation(schema: &std::sync::Arc<CalcitTypeAnnotation>, context_ns: &str, depth: usize) -> Option<String> {
1294  if depth == 0 {
1295    return None;
1296  }
1297  match schema.as_ref() {
1298    CalcitTypeAnnotation::Dynamic => None,
1299    CalcitTypeAnnotation::Ref(inner, _) => format_schema_annotation(inner, context_ns, depth - 1),
1300    CalcitTypeAnnotation::TypeRef(name, _) => {
1301      let stripped = name.trim_start_matches('\'').trim_start_matches(':');
1302      expand_type_ref_path(stripped, context_ns, depth - 1)
1303    }
1304    CalcitTypeAnnotation::Fn(fn_type) => Some(fn_type.return_type.to_brief_string()),
1305    CalcitTypeAnnotation::Map(key, value)
1306      if matches!(key.as_ref(), CalcitTypeAnnotation::Dynamic) && matches!(value.as_ref(), CalcitTypeAnnotation::Dynamic) =>
1307    {
1308      None
1309    }
1310    CalcitTypeAnnotation::Map(key, value) => {
1311      let k = format_schema_annotation(key, context_ns, depth - 1).unwrap_or_else(|| key.to_brief_string());
1312      let v = format_schema_annotation(value, context_ns, depth - 1).unwrap_or_else(|| value.to_brief_string());
1313      Some(format!("map<{k},{v}>"))
1314    }
1315    CalcitTypeAnnotation::List(inner) => format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("list<{t}>")),
1316    CalcitTypeAnnotation::Nullable(inner, NullableOrigin::Inferred) => {
1317      format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("{t}?"))
1318    }
1319    CalcitTypeAnnotation::Nullable(inner, NullableOrigin::JsHost) => {
1320      format_schema_annotation(inner, context_ns, depth - 1).map(|t| format!("js-nullish<{t}>"))
1321    }
1322    _ => {
1323      if let Some(st) = schema.resolve_to_struct() {
1324        return Some(format_struct_fields(&st, context_ns, depth));
1325      }
1326      let brief = schema.to_brief_string();
1327      if is_informative_schema(&brief) { Some(brief) } else { None }
1328    }
1329  }
1330}
1331
1332fn format_struct_fields(st: &CalcitStructDef, context_ns: &str, depth: usize) -> String {
1333  let fields: Vec<String> = st
1334    .fields
1335    .iter()
1336    .zip(st.field_types.iter())
1337    .map(|(field, ty)| {
1338      let ty_str = format_schema_annotation(ty, context_ns, depth.saturating_sub(1)).unwrap_or_else(|| ty.to_brief_string());
1339      format!(":{field} {ty_str}")
1340    })
1341    .collect();
1342  if fields.is_empty() {
1343    format!("struct {}", st.name)
1344  } else {
1345    format!("{{ {} }}", fields.join(", "))
1346  }
1347}
1348
1349fn expand_from_def_template(ns: &str, def: &str, context_ns: &str, depth: usize) -> Option<String> {
1350  if depth == 0 {
1351    return None;
1352  }
1353  let code = lookup_def_code(ns, def)?;
1354  let fields = find_best_struct_template(&code)?;
1355  Some(format_struct_template_fields(&fields, context_ns, depth - 1))
1356}
1357
1358fn find_best_struct_template(code: &Calcit) -> Option<Vec<(String, String)>> {
1359  let mut best: Option<Vec<(String, String)>> = None;
1360  walk_for_struct_templates(code, &mut best);
1361  best
1362}
1363
1364fn walk_for_struct_templates(code: &Calcit, best: &mut Option<Vec<(String, String)>>) {
1365  if let Some(fields) = parse_struct_field_pairs(code)
1366    && fields.len() >= 2
1367    && best.as_ref().is_none_or(|current| current.len() < fields.len())
1368  {
1369    *best = Some(fields);
1370  }
1371  match code {
1372    Calcit::List(list) => {
1373      for item in list.iter() {
1374        walk_for_struct_templates(item, best);
1375      }
1376    }
1377    Calcit::Fn { info, .. } => {
1378      for expr in info.body.iter() {
1379        walk_for_struct_templates(expr, best);
1380      }
1381    }
1382    Calcit::Macro { info, .. } => {
1383      for expr in info.body.iter() {
1384        walk_for_struct_templates(expr, best);
1385      }
1386    }
1387    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => walk_for_struct_templates(code, best),
1388    Calcit::Struct(struct_value) => {
1389      if let Some(fields) = struct_fields_from_calcit(struct_value)
1390        && fields.len() >= 2
1391        && best.as_ref().is_none_or(|current| current.len() < fields.len())
1392      {
1393        *best = Some(fields);
1394      }
1395    }
1396    Calcit::Map(map) => {
1397      for (k, v) in map.iter() {
1398        walk_for_struct_templates(k, best);
1399        walk_for_struct_templates(v, best);
1400      }
1401    }
1402    _ => {}
1403  }
1404}
1405
1406fn format_struct_template_fields(fields: &[(String, String)], context_ns: &str, depth: usize) -> String {
1407  let parts: Vec<String> = fields
1408    .iter()
1409    .map(|(key, hint)| {
1410      let expanded = if depth > 0 && hint.contains('/') {
1411        finalize_schema_hint(hint, context_ns)
1412      } else {
1413        hint.clone()
1414      };
1415      format!(":{key} {expanded}")
1416    })
1417    .collect();
1418  format!("{{ {} }}", parts.join(", "))
1419}
1420
1421fn parse_struct_field_pairs(expr: &Calcit) -> Option<Vec<(String, String)>> {
1422  if let Calcit::Struct(struct_value) = expr {
1423    return struct_fields_from_calcit(struct_value);
1424  }
1425  let Calcit::List(list) = expr else {
1426    return None;
1427  };
1428  let start = if is_struct_literal_head(list.first()) { 1 } else { 0 };
1429  parse_flat_struct_pairs(list, start).or_else(|| parse_nested_struct_entries(list, start))
1430}
1431
1432fn parse_flat_struct_pairs(list: &calcit_core::calcit::CalcitList, start: usize) -> Option<Vec<(String, String)>> {
1433  if start >= list.len() {
1434    return None;
1435  }
1436  extract_field_key(list.get(start)?)?;
1437  let mut fields = vec![];
1438  let mut idx = start;
1439  while idx + 1 < list.len() {
1440    let key = extract_field_key(list.get(idx)?)?;
1441    let value_hint = value_shape_hint(list.get(idx + 1)?);
1442    fields.push((key, value_hint));
1443    idx += 2;
1444  }
1445  if fields.is_empty() { None } else { Some(fields) }
1446}
1447
1448fn parse_nested_struct_entries(list: &calcit_core::calcit::CalcitList, start: usize) -> Option<Vec<(String, String)>> {
1449  let mut fields = vec![];
1450  for idx in start..list.len() {
1451    let Some(entry) = list.get(idx) else { continue };
1452    let Calcit::List(entry_list) = entry else { continue };
1453    if entry_list.len() < 2 {
1454      continue;
1455    }
1456    let key = extract_field_key(entry_list.get(0)?)?;
1457    let value_hint = value_shape_hint(entry_list.get(1)?);
1458    fields.push((key, value_hint));
1459  }
1460  if fields.is_empty() { None } else { Some(fields) }
1461}
1462
1463fn struct_fields_from_calcit(struct_value: &calcit_core::calcit::CalcitStructValue) -> Option<Vec<(String, String)>> {
1464  let fields = struct_value.fields();
1465  let values = struct_value.values.as_ref();
1466  if fields.is_empty() || fields.len() != values.len() {
1467    return None;
1468  }
1469  Some(
1470    fields
1471      .iter()
1472      .zip(values.iter())
1473      .map(|(field, value)| (field.to_string(), value_shape_hint(value)))
1474      .collect(),
1475  )
1476}
1477
1478fn is_struct_literal_head(head: Option<&Calcit>) -> bool {
1479  match head {
1480    Some(Calcit::Proc(CalcitProc::NativeLooseStruct)) => true,
1481    Some(Calcit::Proc(CalcitProc::NativeEnum)) => true,
1482    Some(Calcit::Symbol { sym, .. }) => matches!(sym.as_ref(), "{}" | "?{}" | "::"),
1483    _ => false,
1484  }
1485}
1486
1487fn extract_field_key(calcit: &Calcit) -> Option<String> {
1488  match calcit {
1489    Calcit::Tag(tag) => Some(tag.to_string()),
1490    Calcit::Symbol { sym, .. } if sym.starts_with(':') => Some(sym[1..].to_string()),
1491    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
1492    Calcit::Str(s) => Some(s.to_string()),
1493    _ => None,
1494  }
1495}
1496
1497fn value_shape_hint(value: &Calcit) -> String {
1498  match value {
1499    Calcit::Nil => ":nil".into(),
1500    Calcit::Bool(_) => ":bool".into(),
1501    Calcit::Number(_) => ":number".into(),
1502    Calcit::Str(_) => ":string".into(),
1503    Calcit::Tag(_) => ":tag".into(),
1504    Calcit::Import(import) => format!("{}/{}", import.ns, import.def),
1505    Calcit::Symbol { sym, .. } if sym.contains('/') => sym.to_string(),
1506    Calcit::Map(map) if map.is_empty() => ":map {}".into(),
1507    Calcit::List(list) if list.is_empty() => ":list []".into(),
1508    Calcit::List(list) if list.len() == 1 && matches!(list.first(), Some(Calcit::Proc(CalcitProc::List))) => ":list []".into(),
1509    Calcit::List(_) => parse_struct_field_pairs(value)
1510      .map(|fields| format_struct_template_fields(&fields, "", 1))
1511      .unwrap_or_else(|| ":struct".into()),
1512    _ => "…".into(),
1513  }
1514}
1515
1516fn lookup_atom_schema(context_ns: &str, atom_name: &str) -> Option<String> {
1517  if !atom_name.starts_with('*') {
1518    return None;
1519  }
1520  let program_code = PROGRAM_CODE_DATA.read().ok()?;
1521  let mut best: Option<String> = None;
1522  if program_code.get(context_ns).is_some_and(|file| file.defs.contains_key(atom_name))
1523    && let Some(hint) = schema_hint_for_atom_def(context_ns, atom_name, context_ns)
1524  {
1525    best = Some(pick_richer_schema(best.as_deref(), &hint));
1526  }
1527  for (ns, file) in program_code.iter() {
1528    if ns.as_ref() != context_ns
1529      && file.defs.contains_key(atom_name)
1530      && let Some(hint) = schema_hint_for_atom_def(ns, atom_name, context_ns)
1531    {
1532      best = Some(pick_richer_schema(best.as_deref(), &hint));
1533    }
1534  }
1535  best.filter(|hint| is_informative_schema(hint))
1536}
1537
1538fn pick_richer_option(current: Option<&str>, next: Option<&str>) -> Option<String> {
1539  match (current, next) {
1540    (Some(cur), Some(nxt)) => Some(pick_richer_schema(Some(cur), nxt)),
1541    (Some(cur), None) => Some(cur.to_string()),
1542    (None, Some(nxt)) => Some(nxt.to_string()),
1543    (None, None) => None,
1544  }
1545}
1546
1547struct MergedStateItem {
1548  key: String,
1549  kind_label: String,
1550  kind: String,
1551  name: String,
1552  type_hint: Option<String>,
1553  count: usize,
1554}
1555
1556fn state_item_key(item: &StateItem) -> String {
1557  format!("{}::{}", item.kind, item.name)
1558}
1559
1560fn state_kind_label(kind: &str) -> &'static str {
1561  match kind {
1562    "param" => "in",
1563    "return" => "out",
1564    "atom-def" => "define",
1565    "atom" | "atom-read" | "atom-write" => "atom",
1566    "watch" => "watch",
1567    _ => "state",
1568  }
1569}
1570
1571fn merge_state_items(items: Vec<(&str, &StateItem)>) -> Vec<MergedStateItem> {
1572  let mut merged: Vec<MergedStateItem> = vec![];
1573  for (label, item) in items {
1574    let key = state_item_key(item);
1575    if let Some(entry) = merged.iter_mut().find(|entry| entry.key == key) {
1576      entry.count += 1;
1577      entry.type_hint = pick_richer_option(entry.type_hint.as_deref(), item.type_hint.as_deref());
1578      continue;
1579    }
1580    merged.push(MergedStateItem {
1581      key,
1582      kind_label: label.to_string(),
1583      kind: item.kind.clone(),
1584      name: item.name.clone(),
1585      type_hint: item.type_hint.clone(),
1586      count: 1,
1587    });
1588  }
1589  merged
1590}
1591
1592fn schema_kind_shows_subtree(kind: &str) -> bool {
1593  matches!(kind, "atom-def" | "watch")
1594}
1595
1596fn pick_richer_schema(current: Option<&str>, next: &str) -> String {
1597  match current {
1598    Some(cur) if cur.len() >= next.len() => cur.to_string(),
1599    _ => next.to_string(),
1600  }
1601}
1602
1603fn schema_hint_for_atom_def(ns: &str, def: &str, context_ns: &str) -> Option<String> {
1604  let mut raw_candidates: Vec<String> = vec![];
1605
1606  if let Some(code) = lookup_def_code(ns, def)
1607    && let Some(raw) = extract_defref_init_from_code(&code, context_ns)
1608  {
1609    raw_candidates.push(raw);
1610  }
1611
1612  if let Some(schema) = lookup_codegen_type_hint(ns, def)
1613    && let Some(hint) = format_schema_annotation(&schema, context_ns, MAX_SCHEMA_DEPTH)
1614  {
1615    raw_candidates.push(hint);
1616  }
1617  if let Some(hint) = format_schema_annotation(&lookup_def_schema(ns, def), context_ns, MAX_SCHEMA_DEPTH) {
1618    raw_candidates.push(hint);
1619  }
1620
1621  raw_candidates
1622    .into_iter()
1623    .map(|raw| finalize_schema_hint(&raw, context_ns))
1624    .filter(|hint| is_informative_schema(hint))
1625    .max_by_key(|hint| hint.len())
1626}
1627
1628fn enrich_atom_def_state(ns: &str, def: &str, state: &mut Vec<StateItem>) {
1629  let Some(schema) = lookup_atom_schema(ns, def) else {
1630    return;
1631  };
1632  if let Some(item) = state.iter_mut().find(|item| item.kind == "atom-def" && item.name == def) {
1633    item.type_hint = Some(pick_richer_schema(item.type_hint.as_deref(), &schema));
1634    return;
1635  }
1636  state.insert(
1637    0,
1638    StateItem {
1639      kind: "atom-def".into(),
1640      name: def.to_string(),
1641      type_hint: Some(schema),
1642    },
1643  );
1644}
1645
1646fn extract_defref_init_from_code(code: &Calcit, context_ns: &str) -> Option<String> {
1647  match code {
1648    Calcit::List(list) => {
1649      let head = list.first()?;
1650      let op = call_operator_name(head)?;
1651      if let Some(idx) = ref_constructor_init_index(&op) {
1652        return list
1653          .get(idx)
1654          .and_then(|init| summarize_init_expr(init, context_ns))
1655          .map(|raw| finalize_schema_hint(&raw, context_ns));
1656      }
1657      for item in list.iter() {
1658        if let Some(hint) = extract_defref_init_from_code(item, context_ns) {
1659          return Some(hint);
1660        }
1661      }
1662      None
1663    }
1664    Calcit::Fn { info, .. } => {
1665      for expr in info.body.iter() {
1666        if let Some(hint) = extract_defref_init_from_code(expr, context_ns) {
1667          return Some(hint);
1668        }
1669      }
1670      None
1671    }
1672    Calcit::Macro { info, .. } => {
1673      for expr in info.body.iter() {
1674        if let Some(hint) = extract_defref_init_from_code(expr, context_ns) {
1675          return Some(hint);
1676        }
1677      }
1678      None
1679    }
1680    Calcit::Thunk(calcit_core::calcit::CalcitThunk::Code { code, .. }) => extract_defref_init_from_code(code, context_ns),
1681    _ => None,
1682  }
1683}
1684
1685fn call_operator_name(head: &Calcit) -> Option<String> {
1686  match head {
1687    Calcit::Syntax(syntax, _) => Some(syntax.to_string()),
1688    Calcit::Proc(proc) => Some(proc.to_string()),
1689    Calcit::Registered(name) => Some(name.to_string()),
1690    Calcit::Import(import) => Some(import.def.to_string()),
1691    Calcit::Symbol { sym, .. } => Some(sym.to_string()),
1692    _ => None,
1693  }
1694}
1695
1696fn summarize_init_expr(expr: &Calcit, current_ns: &str) -> Option<String> {
1697  match expr {
1698    Calcit::Number(n) => Some(format!(":number  init={n}")),
1699    Calcit::Nil => Some(":nil".into()),
1700    Calcit::Str(_) => Some(":string".into()),
1701    Calcit::Tag(tag) => Some(format!(":{tag}")),
1702    Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
1703    Calcit::Symbol { sym, .. } if sym.contains('/') => Some(sym.to_string()),
1704    Calcit::Map(map) if map.is_empty() => Some(":map {}".into()),
1705    Calcit::List(list) if list.is_empty() => Some(":list []".into()),
1706    Calcit::List(list) => summarize_call_init(list, current_ns),
1707    _ => None,
1708  }
1709}
1710
1711fn summarize_type_ref_expr(expr: &Calcit, current_ns: &str) -> Option<String> {
1712  match expr {
1713    Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
1714    Calcit::Symbol { sym, .. } if sym.contains('/') => Some(sym.to_string()),
1715    _ => summarize_init_expr(expr, current_ns),
1716  }
1717}
1718
1719fn expand_arrow_init(list: &calcit_core::calcit::CalcitList, context_ns: &str) -> Option<String> {
1720  let base = list.get(1)?;
1721  let base_hint = summarize_type_ref_expr(base, context_ns)?;
1722  let mut overlays: Vec<String> = vec![];
1723  for idx in 2..list.len() {
1724    if let Some(item) = list.get(idx)
1725      && let Some(overlay) = extract_assoc_overlay(item, context_ns)
1726    {
1727      overlays.push(overlay);
1728    }
1729  }
1730  let base_expanded = finalize_schema_hint(&base_hint, context_ns);
1731  if overlays.is_empty() {
1732    Some(if base_expanded == base_hint {
1733      base_expanded
1734    } else {
1735      format!("{base_hint} = {base_expanded}")
1736    })
1737  } else {
1738    let base_label = if base_expanded == base_hint {
1739      base_hint
1740    } else {
1741      format!("{base_hint} = {base_expanded}")
1742    };
1743    Some(format!("{base_label} {{ {} }}", overlays.join(", ")))
1744  }
1745}
1746
1747fn extract_assoc_overlay(expr: &Calcit, context_ns: &str) -> Option<String> {
1748  let Calcit::List(list) = expr else {
1749    return None;
1750  };
1751  let head = call_operator_name(list.first()?)?;
1752  if head != "assoc" {
1753    return None;
1754  }
1755  let key = extract_field_key(list.get(1)?)?;
1756  let val = list.get(2)?;
1757  let val_hint = summarize_type_ref_expr(val, context_ns)?;
1758  let val_expanded = finalize_schema_hint(&val_hint, context_ns);
1759  Some(format!(":{key} {val_expanded}"))
1760}
1761
1762fn summarize_call_init(list: &calcit_core::calcit::CalcitList, current_ns: &str) -> Option<String> {
1763  let head = list.first()?;
1764
1765  if is_thread_first_head(head)
1766    && let Some(second) = list.get(1)
1767  {
1768    if is_arrow_head(second) {
1769      return list.get(2).and_then(|expr| summarize_init_expr(expr, current_ns));
1770    }
1771    return summarize_init_expr(second, current_ns);
1772  }
1773
1774  if is_arrow_head(head) {
1775    return expand_arrow_init(list, current_ns);
1776  }
1777
1778  if let Some((ns, def)) = resolve_def_call(head, current_ns) {
1779    return Some(format!("{ns}/{def}"));
1780  }
1781  if let Calcit::Symbol { sym, .. } = head {
1782    return Some(sym.to_string());
1783  }
1784  None
1785}
1786
1787fn is_thread_first_head(head: &Calcit) -> bool {
1788  match head {
1789    Calcit::Symbol { sym, .. } => sym.as_ref() == "$",
1790    _ => false,
1791  }
1792}
1793
1794fn is_arrow_head(head: &Calcit) -> bool {
1795  match head {
1796    Calcit::Symbol { sym, .. } => sym.as_ref() == "->",
1797    Calcit::Syntax(syntax, _) => syntax.to_string() == "->",
1798    Calcit::Import(import) => import.def.as_ref() == "->" || import.def.as_ref() == "$",
1799    _ => false,
1800  }
1801}
1802
1803fn doc_or_generated_summary(doc: Option<&str>, control: &[String], calls: &[String]) -> String {
1804  if let Some(text) = doc {
1805    let trimmed = text.lines().next().unwrap_or(text).trim();
1806    if !trimmed.is_empty() {
1807      return trimmed.to_string();
1808    }
1809  }
1810  let mut parts = vec![];
1811  if !control.is_empty() {
1812    let mut counts: HashMap<&str, usize> = HashMap::new();
1813    for item in control {
1814      *counts.entry(item.as_str()).or_default() += 1;
1815    }
1816    let control_summary: Vec<String> = counts
1817      .into_iter()
1818      .map(|(name, count)| if count > 1 { format!("{name}×{count}") } else { name.to_string() })
1819      .collect();
1820    parts.push(format!("control: {}", control_summary.join(", ")));
1821  }
1822  if !calls.is_empty() {
1823    parts.push(format!("calls: {}", calls.len()));
1824  }
1825  if parts.is_empty() { "transform".into() } else { parts.join("; ") }
1826}
1827
1828fn prune_tree_by_ns_prefix(mut node: EffectsGraphNode, prefix: &str) -> EffectsGraphNode {
1829  let children = std::mem::take(&mut node.children);
1830  node.children = children
1831    .into_iter()
1832    .map(|child| prune_tree_by_ns_prefix(child, prefix))
1833    .filter(|child| tree_contains_ns_prefix(child, prefix))
1834    .collect();
1835  node
1836}
1837
1838fn tree_contains_ns_prefix(node: &EffectsGraphNode, prefix: &str) -> bool {
1839  if node.ns.starts_with(prefix) {
1840    return true;
1841  }
1842  node.children.iter().any(|child| tree_contains_ns_prefix(child, prefix))
1843}
1844
1845pub fn analyze_effects_graph(
1846  entry_ns: &str,
1847  entry_def: &str,
1848  include_core: bool,
1849  max_depth: usize,
1850  ns_prefix: Option<String>,
1851  detail: EffectsGraphDetail,
1852) -> Result<EffectsGraphResult, String> {
1853  let config = EffectsGraphConfig {
1854    include_core,
1855    max_depth,
1856    ns_prefix,
1857    detail,
1858  };
1859  let mut analyzer = EffectsGraphAnalyzer::new(config)?;
1860  analyzer.analyze(entry_ns, entry_def)
1861}
1862
1863fn is_meaningful_call_target(ns: &str, def: &str, include_core: bool) -> bool {
1864  if matches!(
1865    def,
1866    "defn" | "defmacro" | "def" | "deftrait" | "defenum" | "defref" | "reset!" | "swap!" | "deref" | "ref"
1867  ) {
1868    return false;
1869  }
1870  if !include_core && (ns == "calcit.core" || ns.starts_with("calcit.")) {
1871    return false;
1872  }
1873  true
1874}
1875
1876fn is_analyzed_node(node: &EffectsGraphNode) -> bool {
1877  !node.state.is_empty()
1878    || !node.effects.is_empty()
1879    || !node.transform.summary.is_empty()
1880    || !node.transform.calls.is_empty()
1881    || !node.transform.control.is_empty()
1882    || !node.children.is_empty()
1883    || node.circular
1884    || node.depth_exceeded
1885}
1886
1887fn count_subgraph_nodes(tree: &EffectsGraphNode) -> usize {
1888  collect_analyzed_subgraphs(tree).len()
1889}
1890
1891fn collect_analyzed_subgraphs(tree: &EffectsGraphNode) -> Vec<&EffectsGraphNode> {
1892  let mut nodes = vec![];
1893  let mut queue: Vec<&EffectsGraphNode> = tree.children.iter().collect();
1894  while let Some(node) = queue.first().copied() {
1895    queue.remove(0);
1896    if is_analyzed_node(node) && !node.seen {
1897      nodes.push(node);
1898    }
1899    queue.extend(node.children.iter());
1900  }
1901  nodes
1902}
1903
1904// ═══════════════════════════════════════════════════════════════════════════════
1905// STE tree format — per-function State / Transform / Effect decomposition
1906// ═══════════════════════════════════════════════════════════════════════════════
1907
1908fn infer_package_root(entry_ns: &str, ns_prefix: &Option<String>) -> Option<String> {
1909  if let Some(prefix) = ns_prefix {
1910    let root = prefix.strip_suffix('.').unwrap_or(prefix.as_str());
1911    if root.is_empty() {
1912      return None;
1913    }
1914    return Some(root.to_string());
1915  }
1916  calcit_core::util::string::extract_pkg_from_ns(entry_ns.into()).map(|s| s.to_string())
1917}
1918
1919fn shorten_fqn(fqn: &str, package_root: &str) -> String {
1920  let ns_prefix = format!("{package_root}.");
1921  let Some((ns, def)) = fqn.split_once('/') else {
1922    return fqn.to_string();
1923  };
1924  if ns.starts_with(&ns_prefix) {
1925    format!("{}/{}", &ns[ns_prefix.len()..], def)
1926  } else {
1927    fqn.to_string()
1928  }
1929}
1930
1931struct SteDisplay<'a> {
1932  package_root: Option<&'a str>,
1933  color: SteColor,
1934}
1935
1936struct SteColor {
1937  enabled: bool,
1938}
1939
1940impl SteColor {
1941  fn new(enabled: bool) -> Self {
1942    if !enabled {
1943      colored::control::set_override(false);
1944    }
1945    Self { enabled }
1946  }
1947
1948  fn plain(&self, text: &str) -> String {
1949    text.to_string()
1950  }
1951
1952  fn paint<'a>(&self, text: &'a str, style: impl Fn(&'a str) -> colored::ColoredString) -> String {
1953    if self.enabled { style(text).to_string() } else { text.to_string() }
1954  }
1955
1956  fn title(&self, text: &str) -> String {
1957    self.paint(text, |s| s.cyan().bold())
1958  }
1959
1960  fn meta(&self, text: &str) -> String {
1961    self.paint(text, |s| s.dimmed())
1962  }
1963
1964  fn connector(&self, text: &str) -> String {
1965    self.paint(text, |s| s.dimmed())
1966  }
1967
1968  fn node_fqn(&self, text: &str, depth: usize) -> String {
1969    self.paint(text, |s| match depth {
1970      0 => s.green().bold(),
1971      1 => s.cyan(),
1972      2 => s.yellow(),
1973      _ => s.normal(),
1974    })
1975  }
1976
1977  fn kind_label(&self, label: &str, node: &EffectsGraphNode) -> String {
1978    self.paint(label, |s| {
1979      let styled = if node.depth_exceeded {
1980        s.yellow()
1981      } else if node.circular {
1982        s.red()
1983      } else if node.source == "core" {
1984        s.cyan()
1985      } else if node.def.starts_with('*') {
1986        s.magenta()
1987      } else if node.effects.is_empty() {
1988        s.blue()
1989      } else {
1990        s.green()
1991      };
1992      styled.dimmed()
1993    })
1994  }
1995
1996  fn schema(&self, text: &str) -> String {
1997    self.paint(text, |s| s.green().dimmed())
1998  }
1999
2000  fn section_state(&self, text: &str) -> String {
2001    self.paint(text, |s| s.magenta().bold())
2002  }
2003
2004  fn section_inputs(&self, text: &str) -> String {
2005    self.paint(text, |s| s.cyan().bold())
2006  }
2007
2008  fn section_output(&self, text: &str) -> String {
2009    self.paint(text, |s| s.green().bold())
2010  }
2011
2012  fn section_transform(&self, text: &str) -> String {
2013    self.paint(text, |s| s.blue().bold())
2014  }
2015
2016  fn section_effects(&self, text: &str) -> String {
2017    self.paint(text, |s| s.yellow().bold())
2018  }
2019
2020  fn state_kind(&self, text: &str) -> String {
2021    self.paint(text, |s| s.dimmed())
2022  }
2023
2024  fn state_name(&self, text: &str) -> String {
2025    self.paint(text, |s| s.white().bold())
2026  }
2027
2028  fn transform_arrow(&self, text: &str) -> String {
2029    self.paint(text, |s| s.blue())
2030  }
2031
2032  fn effect_kind(&self, text: &str) -> String {
2033    self.paint(text, |s| s.yellow())
2034  }
2035
2036  fn effect_target(&self, text: &str) -> String {
2037    self.plain(text)
2038  }
2039
2040  fn collapsed(&self, text: &str) -> String {
2041    self.paint(text, |s| s.dimmed())
2042  }
2043}
2044
2045impl<'a> SteDisplay<'a> {
2046  fn from_result(result: &'a EffectsGraphResult, color: bool) -> Self {
2047    SteDisplay {
2048      package_root: result.display.package_root.as_deref(),
2049      color: SteColor::new(color),
2050    }
2051  }
2052
2053  fn fqn(&self, fqn: &str) -> String {
2054    match self.package_root {
2055      Some(root) => shorten_fqn(fqn, root),
2056      None => fqn.to_string(),
2057    }
2058  }
2059}
2060
2061const SCHEMA_INLINE_MAX: usize = 72;
2062
2063struct SchemaHintParts {
2064  label: Option<String>,
2065  segments: Vec<String>,
2066}
2067
2068fn schema_should_embed(hint: &str) -> bool {
2069  hint.len() > SCHEMA_INLINE_MAX || (hint.contains('{') && hint.len() > 48)
2070}
2071
2072fn split_schema_hint(hint: &str) -> SchemaHintParts {
2073  let hint = hint.trim();
2074  if let Some((label, rest)) = hint.split_once(" = ") {
2075    let segments = extract_brace_blocks(rest);
2076    if segments.is_empty() && !rest.trim().is_empty() {
2077      return SchemaHintParts {
2078        label: Some(label.trim().to_string()),
2079        segments: vec![rest.trim().to_string()],
2080      };
2081    }
2082    return SchemaHintParts {
2083      label: Some(label.trim().to_string()),
2084      segments,
2085    };
2086  }
2087  let segments = extract_brace_blocks(hint);
2088  if segments.is_empty() {
2089    SchemaHintParts {
2090      label: None,
2091      segments: vec![hint.to_string()],
2092    }
2093  } else {
2094    SchemaHintParts { label: None, segments }
2095  }
2096}
2097
2098fn extract_brace_blocks(s: &str) -> Vec<String> {
2099  let mut blocks = Vec::new();
2100  let mut depth = 0usize;
2101  let mut start: Option<usize> = None;
2102  for (idx, ch) in s.char_indices() {
2103    match ch {
2104      '{' => {
2105        if depth == 0 {
2106          start = Some(idx);
2107        }
2108        depth += 1;
2109      }
2110      '}' => {
2111        if depth == 0 {
2112          continue;
2113        }
2114        depth -= 1;
2115        if depth == 0
2116          && let Some(from) = start
2117        {
2118          blocks.push(s[from..=idx].to_string());
2119          start = None;
2120        }
2121      }
2122      _ => {}
2123    }
2124  }
2125  blocks
2126}
2127
2128fn parse_schema_segment(segment: &str) -> Option<Edn> {
2129  parse_schema_value(segment.trim())
2130}
2131
2132fn parse_schema_value(raw: &str) -> Option<Edn> {
2133  let s = raw.trim();
2134  if s.is_empty() {
2135    return Some(Edn::Nil);
2136  }
2137  if s.starts_with('{') {
2138    return parse_schema_map(s);
2139  }
2140  if s.starts_with('[') {
2141    return parse_schema_list(s);
2142  }
2143  if s == "nil" {
2144    return Some(Edn::Nil);
2145  }
2146  if let Some(body) = s.strip_prefix(':') {
2147    let body = body.trim();
2148    if let Some(split_at) = body.find(char::is_whitespace) {
2149      let tag = &body[..split_at];
2150      let rest = body[split_at..].trim();
2151      let value = parse_schema_value(rest)?;
2152      let mut combo = EdnListView::default();
2153      combo.push(Edn::Tag(EdnTag::from(tag)));
2154      combo.push(value);
2155      return Some(combo.into());
2156    }
2157    return Some(Edn::Tag(EdnTag::from(body)));
2158  }
2159  Some(Edn::Symbol(s.into()))
2160}
2161
2162fn parse_schema_map(s: &str) -> Option<Edn> {
2163  let inner = s.trim();
2164  if !inner.starts_with('{') || !inner.ends_with('}') {
2165    return None;
2166  }
2167  let body = inner[1..inner.len() - 1].trim();
2168  let mut map = EdnMapView::default();
2169  for field in split_top_level_commas(body) {
2170    let (key, value_raw) = split_field_key_value(field)?;
2171    let key_name = key.trim_start_matches(':');
2172    let value = parse_schema_value(value_raw)?;
2173    map.insert(Edn::Tag(EdnTag::from(key_name)), value);
2174  }
2175  Some(map.into())
2176}
2177
2178fn parse_schema_list(s: &str) -> Option<Edn> {
2179  let inner = s.trim();
2180  if inner == "[]" {
2181    return Some(EdnListView::default().into());
2182  }
2183  if !inner.starts_with('[') || !inner.ends_with(']') {
2184    return None;
2185  }
2186  let body = inner[1..inner.len() - 1].trim();
2187  if body.is_empty() {
2188    return Some(EdnListView::default().into());
2189  }
2190  let mut list = EdnListView::default();
2191  for item in split_top_level_commas(body) {
2192    list.push(parse_schema_value(item)?);
2193  }
2194  Some(list.into())
2195}
2196
2197fn split_field_key_value(field: &str) -> Option<(&str, &str)> {
2198  let field = field.trim();
2199  if !field.starts_with(':') {
2200    return None;
2201  }
2202  let rest = field[1..].trim_start();
2203  let key_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
2204  let key = &field[..1 + key_end];
2205  let value = rest[key_end..].trim();
2206  Some((key, value))
2207}
2208
2209fn split_top_level_commas(s: &str) -> Vec<&str> {
2210  let mut parts = Vec::new();
2211  let mut start = 0usize;
2212  let mut brace = 0usize;
2213  let mut bracket = 0usize;
2214  for (idx, ch) in s.char_indices() {
2215    match ch {
2216      '{' => brace += 1,
2217      '}' => brace = brace.saturating_sub(1),
2218      '[' => bracket += 1,
2219      ']' => bracket = bracket.saturating_sub(1),
2220      ',' if brace == 0 && bracket == 0 => {
2221        let part = s[start..idx].trim();
2222        if !part.is_empty() {
2223          parts.push(part);
2224        }
2225        start = idx + 1;
2226      }
2227      _ => {}
2228    }
2229  }
2230  let part = s[start..].trim();
2231  if !part.is_empty() {
2232    parts.push(part);
2233  }
2234  parts
2235}
2236
2237fn format_schema_edn_lines(edn: &Edn) -> Vec<String> {
2238  cirru_edn::format(edn, true)
2239    .map(|text| {
2240      text
2241        .lines()
2242        .map(|line| line.trim_end().to_string())
2243        .filter(|line| !line.trim().is_empty())
2244        .collect()
2245    })
2246    .unwrap_or_else(|_| vec![edn.to_string()])
2247}
2248
2249fn render_schema_subtree(hint: &str, prefix: &str, display: &SteDisplay<'_>, out: &mut String) {
2250  let parts = split_schema_hint(hint);
2251  out.push_str(&format!(
2252    "{}{}\n",
2253    display.color.connector(prefix),
2254    display.color.schema("└── schema")
2255  ));
2256  let inner = format!("{prefix}    ");
2257
2258  if let Some(label) = parts.label {
2259    out.push_str(&format!(
2260      "{}{}\n",
2261      display.color.connector(&inner),
2262      display.color.schema(&format!("{label} ="))
2263    ));
2264  }
2265
2266  let segments = if parts.segments.is_empty() {
2267    vec![hint.to_string()]
2268  } else {
2269    parts.segments
2270  };
2271
2272  for segment in segments {
2273    if let Some(edn) = parse_schema_segment(&segment) {
2274      for line in format_schema_edn_lines(&edn) {
2275        out.push_str(&format!("{}{}\n", display.color.connector(&inner), display.color.schema(&line)));
2276      }
2277    } else {
2278      out.push_str(&format!("{}{}\n", display.color.connector(&inner), display.color.schema(&segment)));
2279    }
2280  }
2281}
2282
2283fn inline_schema_suffix(hint: &str, display: &SteDisplay<'_>) -> String {
2284  if schema_should_embed(hint) {
2285    return String::new();
2286  }
2287  format!("  {}", display.color.schema(&format!("schema: {hint}")))
2288}
2289
2290fn node_atom_schema_hint(node: &EffectsGraphNode) -> Option<String> {
2291  if !node.def.starts_with('*') {
2292    return None;
2293  }
2294  node
2295    .state
2296    .iter()
2297    .find(|item| item.kind == "atom-def")
2298    .and_then(|item| item.type_hint.clone())
2299    .or_else(|| lookup_atom_schema(&node.ns, &node.def))
2300}
2301
2302/// Format entry point for CLI banners and headers.
2303pub fn format_entry_label(entry_ns: &str, entry_def: &str, ns_prefix: Option<&str>) -> String {
2304  let fqn = format!("{entry_ns}/{entry_def}");
2305  match infer_package_root(entry_ns, &ns_prefix.map(|s| s.to_string())) {
2306    Some(root) => shorten_fqn(&fqn, &root),
2307    None => fqn,
2308  }
2309}
2310
2311/// Render per-function STE decomposition tree.
2312pub fn format_as_ste_tree(result: &EffectsGraphResult, color: bool) -> String {
2313  let display = SteDisplay::from_result(result, color);
2314  let mut out = String::new();
2315  out.push_str(&format!(
2316    "{}\n\n",
2317    display.color.title(&format!("# Effects Graph: `{}`", display.fqn(&result.entry)))
2318  ));
2319
2320  if let Some(root) = display.package_root {
2321    out.push_str(&format!("{}\n", display.color.meta(&format!("Package: `{root}.*`"))));
2322  }
2323
2324  let depth_limited = count_depth_limited(&result.tree);
2325  if depth_limited > 0 {
2326    out.push_str(&format!(
2327      "{}\n\n",
2328      display.color.meta(&format!(
2329        "Max depth: {}  ({} nodes truncated; rerun with larger --max-depth to expand)",
2330        result.display.max_depth_limit, depth_limited
2331      ))
2332    ));
2333  } else if result.display.max_depth_limit > 0 {
2334    out.push_str(&format!(
2335      "{}\n\n",
2336      display.color.meta(&format!("Max depth: {}", result.display.max_depth_limit))
2337    ));
2338  } else if display.package_root.is_some() {
2339    out.push('\n');
2340  }
2341
2342  render_ste_node(&result.tree, &mut out, "", true, 0, &display);
2343  out
2344}
2345
2346fn count_depth_limited(node: &EffectsGraphNode) -> usize {
2347  let mut count = if node.depth_exceeded { 1 } else { 0 };
2348  for child in &node.children {
2349    count += count_depth_limited(child);
2350  }
2351  count
2352}
2353
2354fn render_ste_node(node: &EffectsGraphNode, out: &mut String, prefix: &str, is_last: bool, depth: usize, display: &SteDisplay<'_>) {
2355  if node.seen {
2356    return;
2357  }
2358
2359  let connector = if is_last { "└── " } else { "├── " };
2360  let (kind_label, is_collapsed) = ste_kind_label(node);
2361  let summary = node_transform_summary(node);
2362  let fqn = display.fqn(&node.fqn);
2363
2364  out.push_str(&format!(
2365    "{}{}{}  {}{}\n",
2366    display.color.connector(prefix),
2367    display.color.connector(connector),
2368    display.color.node_fqn(&fqn, depth),
2369    display.color.kind_label(kind_label, node),
2370    node_schema_suffix(node, display)
2371  ));
2372
2373  let child_prefix = format!("{prefix}{}   ", if is_last { " " } else { "│" });
2374
2375  if is_collapsed {
2376    if !summary.is_empty() {
2377      out.push_str(&format!(
2378        "{}{}\n",
2379        display.color.connector(&child_prefix),
2380        display.color.collapsed(&format!("({summary})"))
2381      ));
2382    }
2383    return;
2384  }
2385
2386  render_ste_inputs(node, out, &child_prefix, display);
2387  render_ste_output(node, out, &child_prefix, display);
2388  render_ste_state(node, out, &child_prefix, display);
2389  render_ste_transform(node, out, &child_prefix, display);
2390  render_ste_effects(node, out, &child_prefix, display);
2391
2392  if !node.children.is_empty() {
2393    out.push_str(&format!(
2394      "{}{}\n",
2395      display.color.connector(&child_prefix),
2396      display.color.connector("│")
2397    ));
2398  }
2399  for (idx, child) in node.children.iter().enumerate() {
2400    let is_last_child = idx + 1 == node.children.len();
2401    render_ste_node(child, out, &child_prefix, is_last_child, depth + 1, display);
2402  }
2403}
2404
2405fn node_schema_suffix(node: &EffectsGraphNode, display: &SteDisplay<'_>) -> String {
2406  node_atom_schema_hint(node)
2407    .as_deref()
2408    .map(|hint| inline_schema_suffix(hint, display))
2409    .unwrap_or_default()
2410}
2411
2412fn ste_kind_label(node: &EffectsGraphNode) -> (&'static str, bool) {
2413  if node.depth_exceeded {
2414    ("[depth limit ↑]", true)
2415  } else if node.circular {
2416    ("[circular]", true)
2417  } else if node.source == "core" {
2418    ("[core]", true)
2419  } else if !is_analyzed_node(node) {
2420    ("[no analysis]", true)
2421  } else if node.def.starts_with('*') {
2422    ("[state]", false)
2423  } else if node.effects.is_empty() {
2424    ("[transform]", false)
2425  } else {
2426    ("[program]", false)
2427  }
2428}
2429
2430fn node_transform_summary(node: &EffectsGraphNode) -> String {
2431  let mut parts: Vec<String> = vec![];
2432
2433  let doc_line = node.doc.as_ref().and_then(|doc| {
2434    let line = doc.lines().next().unwrap_or(doc).trim();
2435    if line.is_empty() { None } else { Some(line.to_string()) }
2436  });
2437
2438  if let Some(ref line) = doc_line {
2439    parts.push(line.clone());
2440  }
2441
2442  let summary = &node.transform.summary;
2443  if !summary.is_empty() && summary != "transform" && doc_line.as_ref() != Some(summary) {
2444    parts.push(summary.clone());
2445  }
2446
2447  if !node.effects.is_empty() {
2448    let kinds: Vec<String> = node.effects.iter().map(|e| e.kind.clone()).collect();
2449    let mut unique: Vec<String> = kinds;
2450    unique.sort();
2451    unique.dedup();
2452    let effect_part = format!("effects: {}", unique.join(", "));
2453    if !parts.iter().any(|p| p.contains("effects:")) {
2454      parts.push(effect_part);
2455    }
2456  }
2457
2458  truncate_summary(parts.join("; "), 120)
2459}
2460
2461/// Truncate to at most `max_chars` characters (not bytes), appending `…` when cut,
2462/// so multi-byte text such as Chinese docs never splits a UTF-8 char boundary.
2463fn truncate_summary(text: String, max_chars: usize) -> String {
2464  if text.chars().count() <= max_chars {
2465    return text;
2466  }
2467  let keep = max_chars.saturating_sub(3);
2468  let cut = text.char_indices().nth(keep).map(|(idx, _)| idx).unwrap_or(text.len());
2469  format!("{}…", &text[..cut])
2470}
2471
2472fn render_ste_inputs(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
2473  let params: Vec<&StateItem> = node.state.iter().filter(|item| item.kind == "param").collect();
2474  if params.is_empty() {
2475    return;
2476  }
2477  let entries = merge_state_items(params.into_iter().map(|item| (state_kind_label(&item.kind), item)).collect());
2478  render_ste_entry_section(
2479    "├── Inputs",
2480    |color, text| color.section_inputs(text),
2481    &entries,
2482    prefix,
2483    display,
2484    out,
2485  );
2486}
2487
2488fn render_ste_output(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
2489  let returns: Vec<&StateItem> = node.state.iter().filter(|item| item.kind == "return").collect();
2490  if returns.is_empty() {
2491    return;
2492  }
2493  let entries = merge_state_items(returns.into_iter().map(|item| (state_kind_label(&item.kind), item)).collect());
2494  render_ste_entry_section(
2495    "├── Output",
2496    |color, text| color.section_output(text),
2497    &entries,
2498    prefix,
2499    display,
2500    out,
2501  );
2502}
2503
2504fn render_ste_state(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
2505  let mut raw: Vec<(&str, &StateItem)> = vec![];
2506  for item in &node.state {
2507    match item.kind.as_str() {
2508      "param" | "return" => {}
2509      "atom-def" | "atom" | "atom-read" | "atom-write" => {
2510        raw.push((state_kind_label(&item.kind), item));
2511      }
2512      "watch" => raw.push(("watch", item)),
2513      _ => raw.push((state_kind_label(&item.kind), item)),
2514    }
2515  }
2516  if raw.is_empty() {
2517    return;
2518  }
2519  let entries = merge_state_items(raw);
2520  render_ste_entry_section("├── State", |color, text| color.section_state(text), &entries, prefix, display, out);
2521}
2522
2523fn render_ste_entry_section(
2524  header: &str,
2525  header_style: impl Fn(&SteColor, &str) -> String,
2526  entries: &[MergedStateItem],
2527  prefix: &str,
2528  display: &SteDisplay<'_>,
2529  out: &mut String,
2530) {
2531  out.push_str(&format!(
2532    "{}{}\n",
2533    display.color.connector(prefix),
2534    header_style(&display.color, header)
2535  ));
2536  let item_prefix = format!("{prefix}│   ");
2537  for (idx, entry) in entries.iter().enumerate() {
2538    let is_last = idx + 1 == entries.len();
2539    let conn = if is_last { "└── " } else { "├── " };
2540    let line = ste_merged_state_line(entry, display);
2541    out.push_str(&format!(
2542      "{}{}{}\n",
2543      display.color.connector(&item_prefix),
2544      display.color.connector(conn),
2545      line
2546    ));
2547    if schema_kind_shows_subtree(&entry.kind)
2548      && let Some(hint) = entry.type_hint.as_deref().filter(|hint| schema_should_embed(hint))
2549    {
2550      let sub_prefix = format!("{item_prefix}{}", if is_last { "    " } else { "│   " });
2551      render_schema_subtree(hint, &sub_prefix, display, out);
2552    }
2553  }
2554}
2555
2556fn ste_merged_state_line(entry: &MergedStateItem, display: &SteDisplay<'_>) -> String {
2557  let kind = if entry.kind_label.is_empty() {
2558    state_kind_label(&entry.kind)
2559  } else {
2560    entry.kind_label.as_str()
2561  };
2562
2563  if entry.kind == "return" {
2564    let value = entry.type_hint.as_deref().unwrap_or(&entry.name);
2565    return format!(
2566      "{} {}",
2567      display.color.state_kind(&format!("{kind:<8}")),
2568      display.color.state_name(value)
2569    );
2570  }
2571
2572  if entry.kind == "param" {
2573    let type_part = entry
2574      .type_hint
2575      .as_deref()
2576      .map(|hint| format!("  {}", display.color.schema(hint)))
2577      .unwrap_or_default();
2578    return format!(
2579      "{} {}{type_part}",
2580      display.color.state_kind(&format!("{kind:<8}")),
2581      display.color.state_name(&entry.name)
2582    );
2583  }
2584
2585  let mut name = display.color.state_name(&entry.name);
2586  if entry.kind == "atom-write" {
2587    name.push_str(&display.color.meta(" (write)"));
2588  } else if entry.kind == "atom-read" {
2589    name.push_str(&display.color.meta(" (read)"));
2590  } else if entry.kind == "local-write" {
2591    name.push_str(&display.color.meta(" (set!)"));
2592  }
2593  if entry.count > 1 {
2594    name.push_str(&display.color.meta(&format!(" (×{})", entry.count)));
2595  }
2596
2597  let schema = entry
2598    .type_hint
2599    .as_deref()
2600    .filter(|_| schema_kind_shows_subtree(&entry.kind))
2601    .map(|hint| inline_schema_suffix(hint, display))
2602    .unwrap_or_default();
2603
2604  format!("{} {}{schema}", display.color.state_kind(&format!("{kind:<8}")), name)
2605}
2606
2607fn render_ste_transform(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
2608  let has_control = !node.transform.control.is_empty();
2609  let has_calls = !node.transform.calls.is_empty();
2610  let summary = if node.transform.summary.is_empty() || node.transform.summary == "transform" {
2611    String::new()
2612  } else {
2613    format!("  ({})", node.transform.summary)
2614  };
2615
2616  if !has_control && !has_calls {
2617    out.push_str(&format!(
2618      "{}{}{}\n",
2619      display.color.connector(prefix),
2620      display.color.section_transform("├── Transform"),
2621      display.color.meta(&summary)
2622    ));
2623    out.push_str(&format!(
2624      "{}{}{}\n",
2625      display.color.connector(prefix),
2626      display.color.connector("│   └── "),
2627      display.color.collapsed("(no calls)")
2628    ));
2629    return;
2630  }
2631
2632  out.push_str(&format!(
2633    "{}{}{}\n",
2634    display.color.connector(prefix),
2635    display.color.section_transform("├── Transform"),
2636    display.color.meta(&summary)
2637  ));
2638  let item_prefix = format!("{prefix}│   ");
2639  let mut lines: Vec<String> = vec![];
2640
2641  if has_control {
2642    let mut counts: HashMap<&str, usize> = HashMap::new();
2643    for item in &node.transform.control {
2644      *counts.entry(item.as_str()).or_default() += 1;
2645    }
2646    let control_summary: Vec<String> = counts
2647      .into_iter()
2648      .map(|(name, count)| if count > 1 { format!("{name}×{count}") } else { name.to_string() })
2649      .collect();
2650    lines.push(display.color.meta(&format!("control: {}", control_summary.join(", "))));
2651  }
2652
2653  for call in &node.transform.calls {
2654    lines.push(format!(
2655      "{} {}",
2656      display.color.transform_arrow("→"),
2657      display.color.node_fqn(&display.fqn(call), 1)
2658    ));
2659  }
2660
2661  for (idx, line) in lines.iter().enumerate() {
2662    let conn = if idx + 1 == lines.len() { "└── " } else { "├── " };
2663    out.push_str(&format!(
2664      "{}{}{}\n",
2665      display.color.connector(&item_prefix),
2666      display.color.connector(conn),
2667      line
2668    ));
2669  }
2670}
2671
2672fn render_ste_effects(node: &EffectsGraphNode, out: &mut String, prefix: &str, display: &SteDisplay<'_>) {
2673  if node.effects.is_empty() {
2674    out.push_str(&format!(
2675      "{}{}\n",
2676      display.color.connector(prefix),
2677      display.color.section_effects("└── Effects")
2678    ));
2679    out.push_str(&format!(
2680      "{}{}{}\n",
2681      display.color.connector(prefix),
2682      display.color.connector("    └── "),
2683      display.color.collapsed("(none — pure transform)")
2684    ));
2685    return;
2686  }
2687
2688  out.push_str(&format!(
2689    "{}{}\n",
2690    display.color.connector(prefix),
2691    display.color.section_effects("└── Effects")
2692  ));
2693  let item_prefix = format!("{prefix}    ");
2694
2695  let mut seen: HashSet<String> = HashSet::new();
2696  let mut unique_effects: Vec<&EffectItem> = vec![];
2697  for effect in &node.effects {
2698    if seen.insert(format!("{}::{}", effect.kind, effect.target)) {
2699      unique_effects.push(effect);
2700    }
2701  }
2702  unique_effects.sort_by(|a, b| a.kind.cmp(&b.kind).then(a.target.cmp(&b.target)));
2703
2704  for (idx, effect) in unique_effects.iter().enumerate() {
2705    let conn = if idx + 1 == unique_effects.len() {
2706      "└── "
2707    } else {
2708      "├── "
2709    };
2710    let count_suffix = if effect.count > 1 {
2711      display.color.meta(&format!(" (×{})", effect.count))
2712    } else {
2713      String::new()
2714    };
2715    out.push_str(&format!(
2716      "{}{}{} {}{}\n",
2717      display.color.connector(&item_prefix),
2718      display.color.connector(conn),
2719      display.color.effect_kind(&format!("{:<14}", effect.kind)),
2720      display.color.effect_target(&effect.target),
2721      count_suffix
2722    ));
2723  }
2724}
2725
2726pub fn format_as_json(result: &EffectsGraphResult) -> Result<String, String> {
2727  serde_json::to_string_pretty(result).map_err(|e| format!("Failed to serialize to JSON: {e}"))
2728}
2729
2730#[cfg(test)]
2731mod tests {
2732  use super::*;
2733  use calcit_core::builtins::proc_tags;
2734
2735  fn core_kinds(index: &TagIndex, name: &str) -> Vec<String> {
2736    classify_call(name, index.tags_for(name))
2737  }
2738
2739  fn strings(items: &[&str]) -> Vec<String> {
2740    items.iter().map(|item| item.to_string()).collect()
2741  }
2742
2743  #[test]
2744  fn truncate_summary_respects_char_boundaries() {
2745    let short = "短文档".to_string();
2746    assert_eq!(truncate_summary(short.clone(), 120), short);
2747    // 200 three-byte chars: byte slicing at 117 would land mid-char and panic.
2748    let long: String = "中".repeat(200);
2749    let cut = truncate_summary(long, 120);
2750    assert_eq!(cut.chars().count(), 118);
2751    assert!(cut.ends_with('…'));
2752    let mixed: String = format!("{}{}", "a".repeat(116), "文".repeat(10));
2753    assert_eq!(truncate_summary(mixed, 120), format!("{}文…", "a".repeat(116)));
2754    let ascii = "x".repeat(120);
2755    assert_eq!(truncate_summary(ascii.clone(), 120), ascii);
2756  }
2757
2758  #[test]
2759  fn core_effects_come_from_declared_tags() {
2760    let index = TagIndex::load().expect("load core tags");
2761    assert_eq!(core_kinds(&index, "read-file"), strings(&["io/file"]));
2762    assert_eq!(core_kinds(&index, "&read-file"), strings(&["io/file"]));
2763    assert_eq!(core_kinds(&index, "&read-dir"), strings(&["io/file"]));
2764    for name in ["add-watch!", "remove-watch!"] {
2765      assert!(is_state_operator(name));
2766      assert_eq!(core_kinds(&index, name), strings(&["state/watch"]), "{name}");
2767    }
2768    for name in ["monotonic-time-ms", "unix-time-ms", "wait-ms", "read-stdin-text", "generate-id!"] {
2769      assert_eq!(core_kinds(&index, name), strings(&["io"]), "{name}");
2770    }
2771    assert_eq!(core_kinds(&index, "get-env"), strings(&["env"]));
2772    assert_eq!(core_kinds(&index, "quit!"), strings(&["control"]));
2773    for name in ["unreachable!", "&unreachable!"] {
2774      assert_eq!(core_kinds(&index, name), strings(&["control"]), "{name}");
2775    }
2776    assert_eq!(core_kinds(&index, "try-read-dir"), strings(&["io/file"]));
2777    assert_eq!(core_kinds(&index, "&init-builtin-impls!"), strings(&["effect"]));
2778    assert_eq!(core_kinds(&index, "&reset-gensym-index!"), strings(&["effect"]));
2779  }
2780
2781  #[test]
2782  fn unmarked_lifecycle_methods_are_effects_through_core_impl_tags() {
2783    let index = TagIndex::load().expect("load core tags");
2784    for method in ["cancel!", "cancel-with!", "resolve!", "reject!"] {
2785      assert_eq!(index.core_methods.get(method), Some(&strings(&["effect"])), "{method}");
2786    }
2787    for method in ["write-text!", "read-text", "read-dir", "walk-dir"] {
2788      assert_eq!(index.core_methods.get(method), Some(&strings(&["io/file"])), "{method}");
2789    }
2790    // `empty?` / `contains?` include inline enum/struct impls; they inherit the owner's tags.
2791    for method in ["map", "get", "unwrap", "to-string", "empty?", "contains?"] {
2792      assert_eq!(index.core_methods.get(method), Some(&vec![]), "{method}");
2793    }
2794  }
2795
2796  #[test]
2797  fn name_spelling_no_longer_decides_effects() {
2798    let index = TagIndex::load().expect("load core tags");
2799    // These names contain `init` / `load`, which used to be reported as `io`.
2800    for name in ["data-definition-form", "enum-definition", "&struct:definition", "&enum:definition"] {
2801      assert!(core_kinds(&index, name).is_empty(), "{name}");
2802    }
2803    // An undeclared target is `unknown`, whatever its spelling.
2804    for name in ["load-config", "setup-app!", "render!"] {
2805      assert_eq!(classify_call(name, None), strings(&[UNKNOWN_EFFECT_KIND]), "{name}");
2806    }
2807  }
2808
2809  #[test]
2810  fn registered_procs_use_descriptor_tags_or_report_unknown() {
2811    fn noop(_xs: Vec<Calcit>, _call_stack: &calcit_core::call_stack::CallStackList) -> Result<Calcit, calcit_core::calcit::CalcitErr> {
2812      Ok(Calcit::Nil)
2813    }
2814    let tagged = "effects-graph-test-tagged-proc";
2815    let untagged = "effects-graph-test-untagged-proc";
2816    builtins::register_import_proc_with_descriptor(
2817      tagged,
2818      noop,
2819      builtins::RegisteredProcDescriptor {
2820        tags: proc_tags(["log", "io"]),
2821        ..Default::default()
2822      },
2823    );
2824    builtins::register_import_proc_with_descriptor(untagged, noop, builtins::RegisteredProcDescriptor::default());
2825    assert_eq!(classify_call(tagged, None), strings(&["console"]));
2826    assert_eq!(classify_call(untagged, None), strings(&[UNKNOWN_EFFECT_KIND]));
2827  }
2828
2829  #[test]
2830  fn core_procs_and_syntax_declare_effect_tags() {
2831    use strum::IntoEnumIterator;
2832    let snapshot = calcit_core::load_core_snapshot().expect("load core");
2833    let core = snapshot.files.get("calcit.core").expect("calcit.core");
2834    let hidden_procs: HashSet<&str> = HIDDEN_CORE_PROC_TAGS.iter().map(|(proc, _)| proc.as_ref()).collect();
2835    for proc in CalcitProc::iter() {
2836      let name = proc.as_ref();
2837      assert_eq!(
2838        core.defs.contains_key(name),
2839        !hidden_procs.contains(name),
2840        "proc `{proc}` needs exactly one effect declaration: a calcit.core entry or HIDDEN_CORE_PROC_TAGS"
2841      );
2842    }
2843    let hidden_syntax: HashSet<String> = HIDDEN_CORE_SYNTAX_TAGS.iter().map(|(syntax, _)| syntax.to_string()).collect();
2844    for syntax in CalcitSyntax::iter() {
2845      let name = syntax.to_string();
2846      assert_eq!(
2847        core.defs.contains_key(&name),
2848        !hidden_syntax.contains(&name),
2849        "syntax `{name}` needs exactly one effect declaration: a calcit.core entry or HIDDEN_CORE_SYNTAX_TAGS"
2850      );
2851    }
2852  }
2853
2854  fn collect_node_effects(node: &EffectsGraphNode, out: &mut HashMap<String, Vec<(String, String)>>) {
2855    if !node.circular && !node.seen {
2856      out
2857        .entry(node.def.clone())
2858        .or_insert_with(|| node.effects.iter().map(|e| (e.kind.clone(), e.target.clone())).collect());
2859    }
2860    for child in &node.children {
2861      collect_node_effects(child, out);
2862    }
2863  }
2864
2865  #[test]
2866  fn fixture_reports_declared_effects_and_unknown_targets() {
2867    let _guard = calcit_core::program::lock_program_test_state();
2868    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../calcit/test-effects-graph.cirru");
2869    let content = std::fs::read_to_string(&path).expect("read effects-graph fixture");
2870    let data = cirru_edn::parse(&content).expect("parse fixture");
2871    let mut snapshot = calcit_core::snapshot::load_snapshot_data(&data, path.to_string_lossy().as_ref()).expect("load fixture");
2872    let core = calcit_core::load_core_snapshot().expect("load core");
2873    for (k, v) in core.files {
2874      snapshot.files.insert(k, v);
2875    }
2876    {
2877      let mut program = calcit_core::program::PROGRAM_CODE_DATA.write().expect("program data");
2878      *program = calcit_core::program::extract_program_data(&snapshot).expect("extract program");
2879    }
2880
2881    let result =
2882      analyze_effects_graph("test-effects-graph.main", "main!", false, 0, None, EffectsGraphDetail::Summary).expect("analyze fixture");
2883    let mut effects = HashMap::new();
2884    collect_node_effects(&result.tree, &mut effects);
2885    let pair = |kind: &str, target: &str| vec![(kind.to_string(), target.to_string())];
2886
2887    assert_eq!(effects["io-helper"], pair("io/file", "read-file"));
2888    // Neither a `load-` prefix nor a trailing `!` makes a pure definition effectful.
2889    assert_eq!(effects["load-config"], vec![]);
2890    assert_eq!(effects["setup!"], vec![]);
2891    // Unmarked writes are found through core tags.
2892    assert_eq!(effects["watch-helper"], pair("state/watch", "remove-watch!"));
2893    assert_eq!(effects["cancel-helper"], pair("effect", ".cancel!"));
2894    assert_eq!(effects["write-helper"], pair("io/file", ".write-text!"));
2895    // Calling a parameter calls a function value supplied by the caller.
2896    assert_eq!(effects["call-through"], pair(UNKNOWN_EFFECT_KIND, "f"));
2897    assert_eq!(effects["js-helper"], pair("interop/js", "js/console.log"));
2898    assert_eq!(effects["native-method-helper"], pair("interop/js", ".!focus"));
2899    assert_eq!(effects["missing-helper"], pair(UNKNOWN_EFFECT_KIND, "missing.ns/thing"));
2900    // Core collection methods stay declared when the project has no same-name defimpl.
2901    assert_eq!(effects["collection-helper"], vec![]);
2902    // Only `(:async true)` in a `hint-fn` schema declares async.
2903    assert_eq!(effects["sync-hint-helper"], vec![]);
2904    assert_eq!(effects["async-hint-helper"], pair("async", "hint-fn"));
2905    // Parameter lists, binding pairs and `case` clauses that start with a parameter are not calls.
2906    assert_eq!(effects["binding-helper"], vec![]);
2907    // An async callback type in `:args` does not make the enclosing function async.
2908    assert_eq!(effects["nested-async-hint-helper"], vec![]);
2909    // A parameter of an inner `fn` is scoped to that `fn`; the outer call still reaches the definition.
2910    assert_eq!(effects["scope-helper"], pair(UNKNOWN_EFFECT_KIND, "io-helper"));
2911    let scope_node = find_node(&result.tree, "scope-helper").expect("scope-helper node");
2912    assert_eq!(scope_node.effects[0].count, 1);
2913    assert!(
2914      scope_node
2915        .transform
2916        .calls
2917        .contains(&"test-effects-graph.main/io-helper".to_string())
2918    );
2919    // `let`, `let[]` and `&doseq` bindings shadow parameters; only `&doseq`'s own tag remains.
2920    assert_eq!(effects["shadow-helper"], pair("effect", "&doseq"));
2921    // `:tags` on a project definition is an explicit declaration, reported at its call sites;
2922    // the callee's own pure body adds nothing.
2923    assert_eq!(
2924      effects["declared-caller"],
2925      pair("effect", "test-effects-graph.main/declared-helper")
2926    );
2927    assert_eq!(effects["declared-helper"], vec![]);
2928    // A non-effect tag is ignored; an effect tag next to it is recorded; a definition in another
2929    // namespace is reported as `ns/def`. Rows come out sorted by kind.
2930    assert_eq!(
2931      effects["tag-caller"],
2932      vec![
2933        ("console".to_string(), "test-effects-graph.main/mixed-tagged".to_string()),
2934        ("io/file".to_string(), "test-effects-graph.lib/lib-effect".to_string()),
2935      ]
2936    );
2937    assert_eq!(effects["deprecated-only"], vec![]);
2938    assert_eq!(effects["mixed-tagged"], vec![]);
2939  }
2940
2941  fn find_node<'a>(node: &'a EffectsGraphNode, def: &str) -> Option<&'a EffectsGraphNode> {
2942    if node.def == def && !node.seen {
2943      return Some(node);
2944    }
2945    node.children.iter().find_map(|child| find_node(child, def))
2946  }
2947
2948  fn parse_ref_call(head: &str, args: &[&str]) -> Calcit {
2949    let mut items = vec![cirru_parser::Cirru::leaf(head)];
2950    items.extend(args.iter().map(|a| cirru_parser::Cirru::leaf(*a)));
2951    calcit_core::data::cirru::code_to_calcit(&cirru_parser::Cirru::List(items), "app.main", "demo", vec![]).expect("parse ref call")
2952  }
2953
2954  #[test]
2955  fn ref_constructors_read_initializer_at_their_own_position() {
2956    for (head, args, name) in [("ref", vec!["1"], "?"), ("defref", vec!["*counter", "1"], "*counter")] {
2957      let code = parse_ref_call(head, &args);
2958      let Calcit::List(list) = &code else {
2959        panic!("expected list for {head}");
2960      };
2961      let target = extract_state_target(Some(list), head);
2962      assert_eq!(target, name, "target for {head}");
2963      let mut state = vec![];
2964      record_state_operator(head, &target, Some(list), "app.main", &mut state);
2965      assert_eq!(state.len(), 1);
2966      assert_eq!(state[0].kind, "atom-def");
2967      assert_eq!(state[0].type_hint.as_deref(), Some(":number  init=1"), "state hint for {head}");
2968      assert_eq!(
2969        extract_defref_init_from_code(&code, "app.main").as_deref(),
2970        Some(":number  init=1"),
2971        "schema hint for {head}"
2972      );
2973    }
2974  }
2975
2976  #[test]
2977  fn summarize_number_init_expr() {
2978    let init = Calcit::Number(0.0);
2979    assert_eq!(summarize_init_expr(&init, "app.main").as_deref(), Some(":number  init=0"));
2980  }
2981
2982  #[test]
2983  fn expand_store_schema_when_msg_buffer_available() {
2984    let _guard = calcit_core::program::lock_program_test_state();
2985    let path = std::path::Path::new("/Users/jon.chen/repo/termina/msg-buffer/calcit.cirru");
2986    if !path.exists() {
2987      return;
2988    }
2989    let content = std::fs::read_to_string(path).expect("read msg-buffer snapshot");
2990    let data = cirru_edn::parse(&content).expect("parse snapshot");
2991    let mut snapshot = calcit_core::snapshot::load_snapshot_data(&data, path.to_string_lossy().as_ref()).expect("load snapshot");
2992    let core = calcit_core::load_core_snapshot().expect("load core");
2993    for (k, v) in core.files {
2994      snapshot.files.insert(k, v);
2995    }
2996    {
2997      let mut prgm = calcit_core::program::PROGRAM_CODE_DATA.write().expect("program data");
2998      *prgm = calcit_core::program::extract_program_data(&snapshot).expect("extract program");
2999    }
3000
3001    let resolved = resolve_type_ref_path("schema/store", "app.main").expect("resolve schema/store");
3002    assert_eq!(resolved.0, "app.schema");
3003    assert_eq!(resolved.1, "store");
3004
3005    let code = lookup_def_code(&resolved.0, &resolved.1).expect("lookup store code");
3006    let template = find_best_struct_template(&code);
3007    assert!(template.is_some(), "struct template not found in code: {code:?}");
3008
3009    let expanded = expand_type_ref_path("schema/store", "app.main", MAX_SCHEMA_DEPTH).expect("expand schema/store");
3010    assert!(expanded.contains(":states"), "expected store fields, got: {expanded}");
3011  }
3012
3013  #[test]
3014  fn schema_hint_parses_segment_to_edn() {
3015    let hint = "{ :records :list [], :base :nil, :stopped? :bool }";
3016    let edn = parse_schema_segment(hint).expect("parse struct");
3017    let lines = format_schema_edn_lines(&edn);
3018    let joined = lines.join("\n");
3019    assert!(joined.contains(":records"));
3020    assert!(joined.contains(":list"));
3021    assert!(joined.contains(":base"));
3022  }
3023
3024  #[test]
3025  fn schema_edn_preserves_indentation() {
3026    let hint = "{ :base { :cursor :list [], :count :number }, :store :nil }";
3027    let edn = parse_schema_segment(hint).expect("parse nested struct");
3028    let raw = cirru_edn::format(&edn, true).expect("format edn");
3029    assert!(
3030      raw.lines().any(|line| line.starts_with(' ') || line.starts_with('\t')),
3031      "expected cirru edn indent, got:\n{raw}"
3032    );
3033
3034    let lines = format_schema_edn_lines(&edn);
3035    assert!(
3036      lines.iter().any(|line| line.starts_with(' ') || line.starts_with('\t')),
3037      "expected preserved indent, got:\n{}",
3038      lines.join("\n")
3039    );
3040  }
3041
3042  #[test]
3043  fn long_schema_renders_as_indented_subtree() {
3044    let hint = "reel-schema/reel = { :records :list [], :base :nil, :store :nil, :pointer :nil, :stopped? :bool, :display? :bool, :merged? :bool } { :base { :states { :cursor :list [] }, :sessions :list [] }, :store { :states { :cursor :list [] } } }";
3045    assert!(schema_should_embed(hint));
3046
3047    let result = EffectsGraphResult {
3048      entry: "app.main/main!".into(),
3049      tree: EffectsGraphNode {
3050        ns: "app.main".into(),
3051        def: "main!".into(),
3052        fqn: "app.main/main!".into(),
3053        doc: None,
3054        source: "project".into(),
3055        state: vec![StateItem {
3056          kind: "watch".into(),
3057          name: "*reel".into(),
3058          type_hint: Some(hint.to_string()),
3059        }],
3060        transform: TransformInfo::default(),
3061        effects: vec![],
3062        children: vec![],
3063        circular: false,
3064        seen: false,
3065        depth_exceeded: false,
3066      },
3067      stats: EffectsGraphStats {
3068        reachable_count: 1,
3069        effect_sites: 0,
3070        state_items: 1,
3071        max_depth: 0,
3072        subgraph_count: 1,
3073      },
3074      display: EffectsGraphDisplayMeta {
3075        max_depth_limit: 2,
3076        detail: "summary".into(),
3077        include_core: false,
3078        ns_prefix: None,
3079        package_root: Some("app".into()),
3080      },
3081    };
3082
3083    let text = format_as_ste_tree(&result, false);
3084    assert!(text.contains("watch    *reel\n"));
3085    assert!(!text.contains("schema: reel-schema"));
3086    assert!(text.contains("└── schema"));
3087    assert!(text.contains("reel-schema/reel ="));
3088    assert!(text.contains(":records"));
3089    assert!(text.contains(":base"));
3090  }
3091
3092  #[test]
3093  fn duplicate_atom_reads_merge_in_display() {
3094    let result = EffectsGraphResult {
3095      entry: "app.main/render!".into(),
3096      tree: EffectsGraphNode {
3097        ns: "app.main".into(),
3098        def: "render!".into(),
3099        fqn: "app.main/render!".into(),
3100        doc: None,
3101        source: "project".into(),
3102        state: vec![
3103          StateItem {
3104            kind: "atom-read".into(),
3105            name: "*reel".into(),
3106            type_hint: None,
3107          },
3108          StateItem {
3109            kind: "atom-read".into(),
3110            name: "*reel".into(),
3111            type_hint: None,
3112          },
3113        ],
3114        transform: TransformInfo::default(),
3115        effects: vec![],
3116        children: vec![],
3117        circular: false,
3118        seen: false,
3119        depth_exceeded: false,
3120      },
3121      stats: EffectsGraphStats {
3122        reachable_count: 1,
3123        effect_sites: 0,
3124        state_items: 2,
3125        max_depth: 0,
3126        subgraph_count: 1,
3127      },
3128      display: EffectsGraphDisplayMeta {
3129        max_depth_limit: 2,
3130        detail: "summary".into(),
3131        include_core: false,
3132        ns_prefix: None,
3133        package_root: Some("app".into()),
3134      },
3135    };
3136
3137    let text = format_as_ste_tree(&result, false);
3138    assert_eq!(text.matches("atom     *reel (read)").count(), 1);
3139    assert!(text.contains("(×2)"));
3140  }
3141
3142  #[test]
3143  fn ste_tree_shows_inputs_and_output_sections() {
3144    let result = EffectsGraphResult {
3145      entry: "app.main/main!".into(),
3146      tree: EffectsGraphNode {
3147        ns: "app.main".into(),
3148        def: "dispatch!".into(),
3149        fqn: "app.main/dispatch!".into(),
3150        doc: None,
3151        source: "project".into(),
3152        state: vec![
3153          StateItem {
3154            kind: "param".into(),
3155            name: "event".into(),
3156            type_hint: Some(":map".into()),
3157          },
3158          StateItem {
3159            kind: "return".into(),
3160            name: "return".into(),
3161            type_hint: Some(":nil".into()),
3162          },
3163        ],
3164        transform: TransformInfo::default(),
3165        effects: vec![],
3166        children: vec![],
3167        circular: false,
3168        seen: false,
3169        depth_exceeded: false,
3170      },
3171      stats: EffectsGraphStats {
3172        reachable_count: 1,
3173        effect_sites: 0,
3174        state_items: 2,
3175        max_depth: 0,
3176        subgraph_count: 1,
3177      },
3178      display: EffectsGraphDisplayMeta {
3179        max_depth_limit: 2,
3180        detail: "summary".into(),
3181        include_core: false,
3182        ns_prefix: None,
3183        package_root: Some("app".into()),
3184      },
3185    };
3186
3187    let text = format_as_ste_tree(&result, false);
3188    assert!(text.contains("├── Inputs"));
3189    assert!(text.contains("in       event"));
3190    assert!(text.contains("├── Output"));
3191    assert!(text.contains("out      :nil"));
3192  }
3193
3194  #[test]
3195  fn ste_tree_contains_core_sections() {
3196    let result = EffectsGraphResult {
3197      entry: "app.main/main!".into(),
3198      tree: EffectsGraphNode {
3199        ns: "app.main".into(),
3200        def: "main!".into(),
3201        fqn: "app.main/main!".into(),
3202        doc: None,
3203        source: "project".into(),
3204        state: vec![],
3205        transform: TransformInfo::default(),
3206        effects: vec![EffectItem {
3207          kind: "console".into(),
3208          target: "println".into(),
3209          count: 1,
3210        }],
3211        children: vec![EffectsGraphNode {
3212          ns: "app.main".into(),
3213          def: "dispatch!".into(),
3214          fqn: "app.main/dispatch!".into(),
3215          doc: Some("state update handler".into()),
3216          source: "project".into(),
3217          state: vec![],
3218          transform: TransformInfo::default(),
3219          effects: vec![],
3220          children: vec![],
3221          circular: false,
3222          seen: false,
3223          depth_exceeded: false,
3224        }],
3225        circular: false,
3226        seen: false,
3227        depth_exceeded: false,
3228      },
3229      stats: EffectsGraphStats {
3230        reachable_count: 2,
3231        effect_sites: 1,
3232        state_items: 0,
3233        max_depth: 1,
3234        subgraph_count: 1,
3235      },
3236      display: EffectsGraphDisplayMeta {
3237        max_depth_limit: 2,
3238        detail: "summary".into(),
3239        include_core: false,
3240        ns_prefix: None,
3241        package_root: Some("app".into()),
3242      },
3243    };
3244
3245    let text = format_as_ste_tree(&result, false);
3246    assert!(text.contains("# Effects Graph"));
3247    assert!(text.contains("main/main!"));
3248    assert!(!text.contains("app.main/main!"));
3249    assert!(text.contains("console"));
3250    assert!(text.contains("println"));
3251    assert!(text.contains("[program]"));
3252  }
3253}