Skip to main content

proa_cli/rsjs/
inspect.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `proa rsjs`: inspection tools for rsjs compiler artifacts.
5
6use std::collections::BTreeSet;
7use std::path::{Path, PathBuf};
8
9use anyhow::{bail, Context, Result};
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, Serialize)]
13pub struct StrategyExplanation {
14    pub source: StrategySource,
15    pub strategy_mode: String,
16    pub render_strategy: String,
17    /// Whether this component may originate browser behavior. Absent only for
18    /// legacy strategy sidecars written before the permission field existed.
19    pub client_origin_permission: Option<String>,
20    pub hydration_strategy: Option<ExplainedHydrationStrategy>,
21    pub declared_client_modules: Vec<String>,
22    pub client_modules: Vec<String>,
23    pub unused_client_modules: Vec<String>,
24    pub component_fragment_imports: Vec<String>,
25    pub runtime_features: Vec<String>,
26    pub shared_state_dependencies: Vec<StrategySharedStateDependency>,
27    pub server_surfaces: Vec<ExplainedServerSurface>,
28    pub crossings: Vec<ExplainedClientCrossing>,
29    pub dead_primitives: Vec<ExplainedDeadPrimitive>,
30    pub summary: String,
31    pub roots: Vec<ExplainedRoot>,
32    pub emitted: ExplainedEmission,
33    pub next_actions: Vec<String>,
34    pub sidecar_path: String,
35    /// Set when the anchored source no longer matches the sidecar's input
36    /// fingerprint (or cannot be found), meaning this analysis is outdated.
37    pub staleness: Option<String>,
38}
39
40#[derive(Debug, Clone, Serialize)]
41pub struct StrategySource {
42    pub analysis_id: String,
43    pub runtime_asset_id: Option<String>,
44    pub struct_name: String,
45    pub struct_path: String,
46    pub input_fingerprint: Option<String>,
47    pub source_anchor: Option<StrategySourceAnchor>,
48}
49
50#[derive(Debug, Clone, Serialize)]
51pub struct StrategySourceAnchor {
52    pub file: Option<String>,
53    pub impl_start_line: Option<usize>,
54    pub impl_start_column: Option<usize>,
55    pub render_start_line: Option<usize>,
56    pub render_start_column: Option<usize>,
57}
58
59#[derive(Debug, Clone, Serialize)]
60pub struct ExplainedRoot {
61    pub kind: String,
62    pub detail: String,
63}
64
65#[derive(Debug, Clone, Serialize)]
66pub struct ExplainedServerSurface {
67    pub kind: String,
68    pub source: Option<String>,
69    pub source_anchor: Option<StrategyServerSurfaceAnchor>,
70    pub detail: String,
71}
72
73#[derive(Debug, Clone, Serialize)]
74pub struct ExplainedClientCrossing {
75    pub kind: String,
76    pub label: Option<String>,
77    pub module: Option<String>,
78    pub name: Option<String>,
79    pub arg_index: Option<u64>,
80    pub asset_id: Option<String>,
81    pub prop: Option<String>,
82    pub root: Option<u64>,
83    pub child_signal: Option<u64>,
84    pub parent_signal: Option<u64>,
85    pub signal: Option<u64>,
86    pub query: Option<u64>,
87    pub mutation: Option<u64>,
88    pub invalidation_index: Option<u64>,
89    pub node: Option<u64>,
90    pub attr: Option<String>,
91    pub surface: Option<String>,
92    pub requirement: Option<String>,
93    pub source_anchor: Option<StrategyClientCrossingAnchor>,
94    pub detail: String,
95}
96
97#[derive(Debug, Clone, Serialize)]
98pub struct ExplainedDeadPrimitive {
99    pub kind: String,
100    pub label: Option<String>,
101    pub signal: Option<u64>,
102    pub handler: Option<u64>,
103    pub node_ref: Option<u64>,
104    pub query: Option<u64>,
105    pub mutation: Option<u64>,
106    pub source_anchor: Option<StrategyDeadPrimitiveAnchor>,
107    pub detail: String,
108}
109
110#[derive(Debug, Clone, Serialize)]
111pub struct ExplainedHydrationStrategy {
112    pub kind: String,
113    pub label: String,
114    pub ignored: bool,
115}
116
117#[derive(Debug, Clone, Serialize)]
118pub struct ExplainedEmission {
119    pub wrapper: bool,
120    pub seed_script: bool,
121    pub manifest_registration: bool,
122    pub js_asset: bool,
123    pub component_fragment_asset: bool,
124    pub uses_queries: bool,
125    pub uses_mutations: bool,
126    pub uses_shared_state: bool,
127}
128
129#[derive(Debug, Clone)]
130pub struct StrategySidecarSummary {
131    pub analysis_id: String,
132    pub runtime_asset_id: Option<String>,
133    pub struct_name: String,
134    pub struct_path: String,
135    pub input_fingerprint: Option<String>,
136    pub source_anchor: Option<StrategySourceAnchor>,
137    pub render_strategy: String,
138    pub client_origin_permission: Option<String>,
139    pub hydration_strategy_kind: Option<String>,
140    pub hydration_strategy_label: Option<String>,
141    pub declared_client_modules: Vec<String>,
142    pub client_modules: Vec<String>,
143    pub unused_client_modules: Vec<String>,
144    pub component_fragment_imports: Vec<String>,
145    pub runtime_features: Vec<String>,
146    pub shared_state_dependencies: Vec<StrategySharedStateDependency>,
147    pub server_surfaces: Vec<StrategyServerSurfaceSummary>,
148    pub crossings: Vec<StrategyClientCrossingSummary>,
149    pub dead_primitives: Vec<StrategyDeadPrimitiveSummary>,
150    pub component_fragment_mounts: Vec<StrategyFragmentMountSummary>,
151    pub sidecar_path: PathBuf,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct StrategyFragmentMountSummary {
156    pub root: u64,
157    pub asset_id: String,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
161pub struct StrategySharedStateDependency {
162    pub store: u64,
163    pub rust_type: String,
164    pub type_key: Option<String>,
165    /// Fields this island actually subscribes to.
166    pub fields: Vec<String>,
167    /// Every field serialized by the provider snapshot, including fields
168    /// this island never reads.
169    pub serialized_fields: Vec<String>,
170    pub provider_serializes_full_snapshot: bool,
171    pub source_anchor: Option<StrategyClientCrossingAnchor>,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct StrategyServerSurfaceSummary {
176    pub kind: String,
177    pub source: Option<String>,
178    pub node: Option<u64>,
179    pub attr: Option<String>,
180    pub reason: Option<String>,
181    pub source_anchor: Option<StrategyServerSurfaceAnchor>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
185pub struct StrategyServerSurfaceAnchor {
186    pub start_line: usize,
187    pub start_column: usize,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
191pub struct StrategyClientCrossingSummary {
192    pub kind: String,
193    pub label: Option<String>,
194    pub module: Option<String>,
195    pub name: Option<String>,
196    pub arg_index: Option<u64>,
197    pub asset_id: Option<String>,
198    pub prop: Option<String>,
199    pub root: Option<u64>,
200    pub child_signal: Option<u64>,
201    pub parent_signal: Option<u64>,
202    pub signal: Option<u64>,
203    pub query: Option<u64>,
204    pub mutation: Option<u64>,
205    pub invalidation_index: Option<u64>,
206    pub node: Option<u64>,
207    pub attr: Option<String>,
208    pub surface: Option<String>,
209    pub requirement: Option<String>,
210    pub source_anchor: Option<StrategyClientCrossingAnchor>,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct StrategyDeadPrimitiveSummary {
215    pub kind: String,
216    pub label: Option<String>,
217    pub signal: Option<u64>,
218    pub handler: Option<u64>,
219    pub node_ref: Option<u64>,
220    pub query: Option<u64>,
221    pub mutation: Option<u64>,
222    pub source_anchor: Option<StrategyDeadPrimitiveAnchor>,
223}
224
225#[derive(Debug, Clone, Serialize)]
226pub struct CrossingReport {
227    pub root: String,
228    pub selector: Option<String>,
229    pub sidecar_count: usize,
230    pub crossing_count: usize,
231    pub crossings: Vec<CrossingReportEntry>,
232}
233
234#[derive(Debug, Clone, Serialize)]
235pub struct CrossingReportEntry {
236    pub sidecar_path: String,
237    pub analysis_id: String,
238    pub runtime_asset_id: Option<String>,
239    pub struct_name: String,
240    pub struct_path: String,
241    pub render_strategy: String,
242    #[serde(flatten)]
243    pub crossing: StrategyClientCrossingSummary,
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
247pub struct StrategyClientCrossingAnchor {
248    pub start_line: usize,
249    pub start_column: usize,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
253pub struct StrategyDeadPrimitiveAnchor {
254    pub start_line: usize,
255    pub start_column: usize,
256}
257
258#[derive(Debug, Deserialize)]
259struct StrategySidecar {
260    format: String,
261    strategy_version: u64,
262    strategy_mode: String,
263    analysis_id: String,
264    #[serde(default)]
265    runtime_asset_id: Option<String>,
266    struct_name: String,
267    struct_path: String,
268    #[serde(default)]
269    input_fingerprint: Option<String>,
270    #[serde(default)]
271    source: Option<StrategySourceSidecar>,
272    render_strategy: String,
273    #[serde(default)]
274    client_origin_permission: Option<String>,
275    #[serde(default)]
276    hydration_strategy: Option<HydrationStrategySidecar>,
277    #[serde(default)]
278    declared_client_modules: Vec<String>,
279    #[serde(default)]
280    client_modules: Vec<String>,
281    #[serde(default)]
282    component_fragment_imports: Vec<String>,
283    #[serde(default)]
284    runtime_features: Vec<String>,
285    #[serde(default)]
286    shared_state_dependencies: Vec<SharedStateDependencySidecar>,
287    #[serde(default)]
288    server_surfaces: Vec<ServerSurfaceSidecar>,
289    #[serde(default)]
290    crossings: Vec<ClientCrossingSidecar>,
291    #[serde(default)]
292    dead_primitives: Vec<DeadPrimitiveSidecar>,
293    #[serde(default)]
294    roots: Vec<StrategyRoot>,
295    #[serde(default)]
296    emitted: EmittedSidecar,
297}
298
299#[derive(Debug, Clone, Deserialize)]
300struct StrategySourceSidecar {
301    #[serde(default)]
302    file: Option<String>,
303    #[serde(default)]
304    impl_start_line: Option<usize>,
305    #[serde(default)]
306    impl_start_column: Option<usize>,
307    #[serde(default)]
308    render_start_line: Option<usize>,
309    #[serde(default)]
310    render_start_column: Option<usize>,
311}
312
313#[derive(Debug, Clone, Deserialize)]
314struct SharedStateDependencySidecar {
315    store: u64,
316    rust_type: String,
317    #[serde(default)]
318    type_key: Option<String>,
319    #[serde(default)]
320    fields: Vec<String>,
321    #[serde(default)]
322    serialized_fields: Vec<String>,
323    #[serde(default)]
324    provider_serializes_full_snapshot: bool,
325    #[serde(default)]
326    source: Option<ClientCrossingAnchorSidecar>,
327}
328
329#[derive(Debug, Clone, Deserialize)]
330struct HydrationStrategySidecar {
331    kind: String,
332    #[serde(default)]
333    label: Option<String>,
334    #[serde(default)]
335    event: Option<String>,
336    #[serde(default)]
337    query: Option<String>,
338}
339
340#[derive(Debug, Deserialize)]
341struct StrategyRoot {
342    kind: String,
343    #[serde(default)]
344    node: Option<u64>,
345    #[serde(default)]
346    parent: Option<u64>,
347    #[serde(default)]
348    name: Option<String>,
349    #[serde(default)]
350    module: Option<String>,
351    #[serde(default)]
352    event: Option<String>,
353    #[serde(default)]
354    dom_event: Option<String>,
355    #[serde(default)]
356    node_ref: Option<u64>,
357    #[serde(default)]
358    id: Option<u64>,
359    #[serde(default)]
360    index: Option<u64>,
361    #[serde(default)]
362    container: Option<u64>,
363    #[serde(default)]
364    root: Option<u64>,
365    #[serde(default)]
366    asset_id: Option<String>,
367    #[serde(default)]
368    read: Option<String>,
369    #[serde(default)]
370    effect: Option<String>,
371}
372
373#[derive(Debug, Deserialize)]
374struct ServerSurfaceSidecar {
375    kind: String,
376    #[serde(default)]
377    source: Option<String>,
378    #[serde(default)]
379    node: Option<u64>,
380    #[serde(default)]
381    attr: Option<String>,
382    #[serde(default)]
383    reason: Option<String>,
384    #[serde(default)]
385    source_anchor: Option<ServerSurfaceAnchorSidecar>,
386}
387
388#[derive(Debug, Clone, Deserialize)]
389struct ServerSurfaceAnchorSidecar {
390    start_line: usize,
391    start_column: usize,
392}
393
394#[derive(Debug, Deserialize)]
395struct ClientCrossingSidecar {
396    kind: String,
397    #[serde(default)]
398    label: Option<String>,
399    #[serde(default)]
400    module: Option<String>,
401    #[serde(default)]
402    name: Option<String>,
403    #[serde(default)]
404    arg_index: Option<u64>,
405    #[serde(default)]
406    asset_id: Option<String>,
407    #[serde(default)]
408    prop: Option<String>,
409    #[serde(default)]
410    root: Option<u64>,
411    #[serde(default)]
412    child_signal: Option<u64>,
413    #[serde(default)]
414    parent_signal: Option<u64>,
415    #[serde(default)]
416    signal: Option<u64>,
417    #[serde(default)]
418    query: Option<u64>,
419    #[serde(default)]
420    mutation: Option<u64>,
421    #[serde(default)]
422    invalidation_index: Option<u64>,
423    #[serde(default)]
424    node: Option<u64>,
425    #[serde(default)]
426    attr: Option<String>,
427    #[serde(default)]
428    surface: Option<String>,
429    #[serde(default)]
430    requirement: Option<String>,
431    #[serde(default)]
432    source_anchor: Option<ClientCrossingAnchorSidecar>,
433}
434
435#[derive(Debug, Clone, Deserialize)]
436struct ClientCrossingAnchorSidecar {
437    start_line: usize,
438    start_column: usize,
439}
440
441#[derive(Debug, Deserialize)]
442struct DeadPrimitiveSidecar {
443    kind: String,
444    #[serde(default)]
445    label: Option<String>,
446    #[serde(default)]
447    signal: Option<u64>,
448    #[serde(default)]
449    handler: Option<u64>,
450    #[serde(default)]
451    node_ref: Option<u64>,
452    #[serde(default)]
453    query: Option<u64>,
454    #[serde(default)]
455    mutation: Option<u64>,
456    #[serde(default)]
457    source_anchor: Option<DeadPrimitiveAnchorSidecar>,
458}
459
460#[derive(Debug, Clone, Deserialize)]
461struct DeadPrimitiveAnchorSidecar {
462    start_line: usize,
463    start_column: usize,
464}
465
466#[derive(Debug, Default, Deserialize)]
467struct EmittedSidecar {
468    #[serde(default)]
469    wrapper: bool,
470    #[serde(default)]
471    seed_script: bool,
472    #[serde(default)]
473    manifest_registration: bool,
474    #[serde(default)]
475    js_asset: bool,
476    #[serde(default)]
477    component_fragment_asset: bool,
478    #[serde(default)]
479    uses_queries: bool,
480    #[serde(default)]
481    uses_mutations: bool,
482    #[serde(default)]
483    uses_shared_state: bool,
484}
485
486pub fn explain_strategy(root: &Path, selector: &str) -> Result<StrategyExplanation> {
487    let sidecar_path = find_strategy_sidecar(root, selector)?;
488    let text = std::fs::read_to_string(&sidecar_path)
489        .with_context(|| format!("read {}", sidecar_path.display()))?;
490    let sidecar: StrategySidecar =
491        serde_json::from_str(&text).with_context(|| format!("parse {}", sidecar_path.display()))?;
492    validate_sidecar(&sidecar, &sidecar_path)?;
493    let staleness = sidecar_staleness(root, &sidecar);
494
495    let roots: Vec<_> = sidecar.roots.iter().map(explain_root).collect();
496    let render_strategy = human_strategy(&sidecar.render_strategy).to_string();
497    let hydration_strategy = sidecar.hydration_strategy.as_ref().map(|strategy| {
498        explain_hydration_strategy(strategy, sidecar.render_strategy == "server_only")
499    });
500    let declared_client_modules = sidecar.declared_client_modules.clone();
501    let client_modules = sidecar.client_modules.clone();
502    let unused_client_modules = unused_client_modules(&declared_client_modules, &client_modules);
503    let component_fragment_imports = sidecar_component_fragment_imports(&sidecar);
504    let runtime_features = sidecar_runtime_features(&sidecar);
505    let shared_state_dependencies = sidecar
506        .shared_state_dependencies
507        .iter()
508        .map(strategy_shared_state_dependency)
509        .collect();
510    let server_surfaces: Vec<_> = sidecar
511        .server_surfaces
512        .iter()
513        .map(explain_server_surface)
514        .collect();
515    let crossings: Vec<_> = sidecar
516        .crossings
517        .iter()
518        .map(explain_client_crossing)
519        .collect();
520    let dead_primitives: Vec<_> = sidecar
521        .dead_primitives
522        .iter()
523        .map(explain_dead_primitive)
524        .collect();
525    let summary = if sidecar.render_strategy == "server_only" {
526        let mut summary = format!(
527            "{} is ServerOnly: no reachable client roots were recorded, so no island JS should be emitted.",
528            sidecar.struct_name
529        );
530        if !declared_client_modules.is_empty() {
531            summary.push_str(
532                " Client helper grouping metadata is unreachable here; grouping never forces hydration.",
533            );
534        }
535        if !dead_primitives.is_empty() {
536            summary.push_str(
537                " Declared client primitives are dead here; declarations alone do not force hydration.",
538            );
539        }
540        summary
541    } else {
542        format!(
543            "{} is {}: {} reachable client root(s) require browser JS.",
544            sidecar.struct_name,
545            render_strategy,
546            roots.len()
547        )
548    };
549    let mut next_actions = if sidecar.render_strategy == "server_only" {
550        let mut actions = vec![
551            "keep #[rsjs(component)] when this type must remain compiler-composable; use an undecorated render trait only for intentionally opaque SSR"
552                .to_string(),
553        ];
554        if sidecar.client_origin_permission.as_deref() == Some("participant_only") {
555            actions.push(
556                "change to #[rsjs(component, client)] before adding a local signal, handler, query, mutation, shared-state acquisition, or browser capability"
557                    .to_string(),
558            );
559        } else {
560            actions.push(
561                "add a reachable signal/event/bind/query/ref primitive if browser behavior is intended"
562                    .to_string(),
563            );
564        }
565        if hydration_strategy
566            .as_ref()
567            .is_some_and(|strategy| strategy.ignored)
568        {
569            actions.push(
570                "remove the `strategy = ...` argument because no browser hydration is emitted"
571                    .to_string(),
572            );
573        }
574        if !declared_client_modules.is_empty() {
575            actions.push(
576                "remove obsolete component helper allowlists; annotate each portable origin-free helper once with #[rsjs::client] and call it from reachable Client IR if browser computation is intended"
577                    .to_string(),
578            );
579        }
580        if !dead_primitives.is_empty() {
581            actions.push(
582                "remove dead client primitive declarations or connect them to a reachable template binding/handler"
583                    .to_string(),
584            );
585        }
586        actions
587    } else {
588        vec![
589            "review reachable roots to confirm each browser dependency is intentional".to_string(),
590            "move opaque SSR-only work behind rsjs::server_only(...) or rsjs::server_attr(...)"
591                .to_string(),
592        ]
593    };
594    next_actions.sort();
595    next_actions.dedup();
596
597    Ok(StrategyExplanation {
598        source: StrategySource {
599            analysis_id: sidecar.analysis_id,
600            runtime_asset_id: sidecar.runtime_asset_id,
601            struct_name: sidecar.struct_name,
602            struct_path: sidecar.struct_path,
603            input_fingerprint: sidecar.input_fingerprint,
604            source_anchor: sidecar.source.map(strategy_source_anchor),
605        },
606        strategy_mode: sidecar.strategy_mode,
607        render_strategy,
608        client_origin_permission: sidecar.client_origin_permission,
609        hydration_strategy,
610        declared_client_modules,
611        client_modules,
612        unused_client_modules,
613        component_fragment_imports,
614        runtime_features,
615        shared_state_dependencies,
616        server_surfaces,
617        crossings,
618        dead_primitives,
619        summary,
620        roots,
621        emitted: ExplainedEmission {
622            wrapper: sidecar.emitted.wrapper,
623            seed_script: sidecar.emitted.seed_script,
624            manifest_registration: sidecar.emitted.manifest_registration,
625            js_asset: sidecar.emitted.js_asset,
626            component_fragment_asset: sidecar.emitted.component_fragment_asset,
627            uses_queries: sidecar.emitted.uses_queries,
628            uses_mutations: sidecar.emitted.uses_mutations,
629            uses_shared_state: sidecar.emitted.uses_shared_state,
630        },
631        next_actions,
632        sidecar_path: sidecar_path.display().to_string(),
633        staleness,
634    })
635}
636
637/// Compare the sidecar's recorded input fingerprint against the current
638/// source of the anchored file. A mismatch means the analysis predates the
639/// latest edit and should not be presented as ground truth.
640fn sidecar_staleness(root: &Path, sidecar: &StrategySidecar) -> Option<String> {
641    let fingerprint = sidecar.input_fingerprint.as_deref()?;
642    let anchor = sidecar.source.as_ref()?;
643    let file = anchor.file.as_deref()?;
644
645    let direct = PathBuf::from(file);
646    let source_path = if direct.is_absolute() {
647        direct
648    } else {
649        let joined = root.join(file);
650        if joined.exists() {
651            joined
652        } else {
653            direct
654        }
655    };
656    if !source_path.exists() {
657        return Some(format!(
658            "anchored source file `{file}` was not found; re-run the build to refresh target/rsjs/strategy"
659        ));
660    }
661
662    let source = std::fs::read_to_string(&source_path).ok()?;
663    let parsed = syn::parse_file(&source).ok()?;
664    let mut fingerprints = Vec::new();
665    rsjs_impl_fingerprints(&parsed.items, &sidecar.struct_name, &mut fingerprints);
666    if fingerprints.is_empty() {
667        return Some(format!(
668            "no `#[rsjs(component)]` or `#[rsjs(component, client)]` render impl for `{}` found in `{file}`; re-run the build to refresh target/rsjs/strategy",
669            sidecar.struct_name
670        ));
671    }
672    if fingerprints.iter().any(|current| current == fingerprint) {
673        return None;
674    }
675    Some(format!(
676        "`{file}` changed since this sidecar was written; re-run the build to refresh target/rsjs/strategy"
677    ))
678}
679
680fn rsjs_impl_fingerprints(items: &[syn::Item], struct_name: &str, out: &mut Vec<String>) {
681    for item in items {
682        match item {
683            syn::Item::Impl(item_impl) => {
684                let is_rsjs = item_impl.attrs.iter().any(|attr| {
685                    attr.path()
686                        .segments
687                        .last()
688                        .is_some_and(|segment| segment.ident == "rsjs")
689                });
690                if !is_rsjs {
691                    continue;
692                }
693                let matches_struct = match item_impl.self_ty.as_ref() {
694                    syn::Type::Path(path) => path
695                        .path
696                        .segments
697                        .last()
698                        .is_some_and(|segment| segment.ident == struct_name),
699                    _ => false,
700                };
701                if matches_struct {
702                    if let Some(fingerprint) =
703                        crate::lint::rsjs_input_fingerprint_for_impl(item_impl)
704                    {
705                        out.push(fingerprint);
706                    }
707                }
708            }
709            syn::Item::Mod(module) => {
710                if let Some((_, items)) = &module.content {
711                    rsjs_impl_fingerprints(items, struct_name, out);
712                }
713            }
714            _ => {}
715        }
716    }
717}
718
719pub fn strategy_sidecar_summaries(root: &Path) -> Vec<StrategySidecarSummary> {
720    let mut summaries = Vec::new();
721    for dir in strategy_dirs(root) {
722        let Ok(entries) = std::fs::read_dir(&dir) else {
723            continue;
724        };
725        for entry in entries.flatten() {
726            let path = entry.path();
727            if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
728                continue;
729            }
730            if let Ok(summary) = read_strategy_sidecar_summary(&path) {
731                summaries.push(summary);
732            }
733        }
734    }
735    summaries.sort_by(|left, right| left.sidecar_path.cmp(&right.sidecar_path));
736    summaries
737}
738
739pub fn crossing_report(root: &Path, selector: Option<&str>) -> Result<CrossingReport> {
740    let summaries = if let Some(selector) = selector {
741        vec![read_strategy_sidecar_summary(&find_strategy_sidecar(
742            root, selector,
743        )?)?]
744    } else {
745        strategy_sidecar_summaries(root)
746    };
747    let sidecar_count = summaries.len();
748    let mut crossings = Vec::new();
749    for summary in summaries {
750        for crossing in summary.crossings {
751            crossings.push(CrossingReportEntry {
752                sidecar_path: summary.sidecar_path.display().to_string(),
753                analysis_id: summary.analysis_id.clone(),
754                runtime_asset_id: summary.runtime_asset_id.clone(),
755                struct_name: summary.struct_name.clone(),
756                struct_path: summary.struct_path.clone(),
757                render_strategy: summary.render_strategy.clone(),
758                crossing,
759            });
760        }
761    }
762    let crossing_count = crossings.len();
763    Ok(CrossingReport {
764        root: root.display().to_string(),
765        selector: selector.map(ToString::to_string),
766        sidecar_count,
767        crossing_count,
768        crossings,
769    })
770}
771
772fn read_strategy_sidecar_summary(path: &Path) -> Result<StrategySidecarSummary> {
773    let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
774    let sidecar: StrategySidecar =
775        serde_json::from_str(&text).with_context(|| format!("parse {}", path.display()))?;
776    validate_sidecar(&sidecar, path)?;
777    Ok(strategy_sidecar_summary(sidecar, path.to_path_buf()))
778}
779
780fn strategy_sidecar_summary(sidecar: StrategySidecar, path: PathBuf) -> StrategySidecarSummary {
781    let runtime_features = sidecar_runtime_features(&sidecar);
782    let component_fragment_imports = sidecar_component_fragment_imports(&sidecar);
783    let shared_state_dependencies = sidecar
784        .shared_state_dependencies
785        .iter()
786        .map(strategy_shared_state_dependency)
787        .collect();
788    let unused_client_modules =
789        unused_client_modules(&sidecar.declared_client_modules, &sidecar.client_modules);
790    let server_surfaces = sidecar
791        .server_surfaces
792        .iter()
793        .map(strategy_server_surface_summary)
794        .collect();
795    let crossings = sidecar
796        .crossings
797        .iter()
798        .map(strategy_client_crossing_summary)
799        .collect();
800    let dead_primitives = sidecar
801        .dead_primitives
802        .iter()
803        .map(strategy_dead_primitive_summary)
804        .collect();
805    let component_fragment_mounts = sidecar
806        .roots
807        .iter()
808        .filter_map(strategy_fragment_mount_summary)
809        .collect();
810    StrategySidecarSummary {
811        analysis_id: sidecar.analysis_id,
812        runtime_asset_id: sidecar.runtime_asset_id,
813        struct_name: sidecar.struct_name,
814        struct_path: sidecar.struct_path,
815        input_fingerprint: sidecar.input_fingerprint,
816        source_anchor: sidecar.source.map(strategy_source_anchor),
817        render_strategy: sidecar.render_strategy,
818        client_origin_permission: sidecar.client_origin_permission,
819        hydration_strategy_kind: sidecar
820            .hydration_strategy
821            .as_ref()
822            .map(|strategy| strategy.kind.clone()),
823        hydration_strategy_label: sidecar
824            .hydration_strategy
825            .as_ref()
826            .map(hydration_strategy_label),
827        declared_client_modules: sidecar.declared_client_modules,
828        client_modules: sidecar.client_modules,
829        unused_client_modules,
830        component_fragment_imports,
831        runtime_features,
832        shared_state_dependencies,
833        server_surfaces,
834        crossings,
835        dead_primitives,
836        component_fragment_mounts,
837        sidecar_path: path,
838    }
839}
840
841fn strategy_fragment_mount_summary(root: &StrategyRoot) -> Option<StrategyFragmentMountSummary> {
842    if root.kind != "component_fragment_mount" {
843        return None;
844    }
845    Some(StrategyFragmentMountSummary {
846        root: root.root.unwrap_or_default(),
847        asset_id: root
848            .asset_id
849            .clone()
850            .unwrap_or_else(|| "<unknown>".to_string()),
851    })
852}
853
854pub fn print_strategy_explanation(explanation: &StrategyExplanation, json: bool) -> Result<()> {
855    if json {
856        println!("{}", serde_json::to_string_pretty(explanation)?);
857        return Ok(());
858    }
859
860    if let Some(staleness) = &explanation.staleness {
861        eprintln!("warning: {staleness}");
862    }
863    println!("RSJS strategy: {}", explanation.render_strategy);
864    println!("component: {}", explanation.source.struct_path);
865    println!(
866        "client origin permission: {}",
867        explanation
868            .client_origin_permission
869            .as_deref()
870            .unwrap_or("unknown (legacy sidecar)")
871    );
872    if let Some(anchor) = &explanation.source.source_anchor {
873        match (
874            anchor.file.as_deref(),
875            anchor.impl_start_line,
876            anchor.impl_start_column,
877        ) {
878            (Some(file), Some(line), Some(column)) => println!("source: {file}:{line}:{column}"),
879            (None, Some(line), Some(column)) => println!("source: {line}:{column}"),
880            _ => {}
881        }
882    }
883    println!("analysis id: {}", explanation.source.analysis_id);
884    if let Some(fingerprint) = &explanation.source.input_fingerprint {
885        println!("input fingerprint: {fingerprint}");
886    }
887    match &explanation.source.runtime_asset_id {
888        Some(id) => println!("runtime asset id: {id}"),
889        None => println!("runtime asset id: none"),
890    }
891    if let Some(strategy) = &explanation.hydration_strategy {
892        if strategy.ignored {
893            println!(
894                "hydration strategy: {} (ignored; ServerOnly emitted no JS)",
895                strategy.label
896            );
897        } else {
898            println!("hydration strategy: {}", strategy.label);
899        }
900    }
901    println!("mode: {}", explanation.strategy_mode);
902    println!("{}", explanation.summary);
903    if explanation.declared_client_modules.is_empty() {
904        println!("declared client modules: none");
905    } else {
906        println!("declared client modules:");
907        for module in &explanation.declared_client_modules {
908            println!("- {module}");
909        }
910    }
911    if explanation.client_modules.is_empty() {
912        println!("client modules: none");
913    } else {
914        println!("client modules:");
915        for module in &explanation.client_modules {
916            println!("- {module}");
917        }
918    }
919    if !explanation.unused_client_modules.is_empty() {
920        println!("unused client module declarations:");
921        for module in &explanation.unused_client_modules {
922            println!("- {module}");
923        }
924    }
925    if explanation.component_fragment_imports.is_empty() {
926        println!("component fragments: none");
927    } else {
928        println!("component fragments:");
929        for asset_id in &explanation.component_fragment_imports {
930            println!("- {asset_id}");
931        }
932    }
933    if explanation.runtime_features.is_empty() {
934        println!("runtime features: none");
935    } else {
936        println!("runtime features:");
937        for feature in &explanation.runtime_features {
938            println!("- {feature}");
939        }
940    }
941    if explanation.shared_state_dependencies.is_empty() {
942        println!("shared state: none");
943    } else {
944        println!("shared state:");
945        for dependency in &explanation.shared_state_dependencies {
946            let used_fields = if dependency.fields.is_empty() {
947                "<no reachable fields>".to_string()
948            } else {
949                dependency.fields.join(", ")
950            };
951            // The macro cannot resolve a shared state's Rust type (see
952            // `Analyzer::shared_field_client_type`), so the sidecar records the
953            // store's Rust type as written and the fields this island reads.
954            // The provider's full serialized field list is a property of the
955            // type and is only known to the running provider.
956            let serialized_fields = if dependency.serialized_fields.is_empty() {
957                "<resolved by the provider at run time>".to_string()
958            } else {
959                dependency.serialized_fields.join(", ")
960            };
961            let identity = dependency
962                .type_key
963                .as_deref()
964                .unwrap_or(&dependency.rust_type);
965            if let Some(anchor) = &dependency.source_anchor {
966                println!(
967                    "- store {} {} @ {}:{}: used [{}]; provider serializes [{}]",
968                    dependency.store,
969                    identity,
970                    anchor.start_line,
971                    anchor.start_column,
972                    used_fields,
973                    serialized_fields
974                );
975            } else {
976                println!(
977                    "- store {} {}: used [{}]; provider serializes [{}]",
978                    dependency.store, identity, used_fields, serialized_fields
979                );
980            }
981        }
982    }
983    if explanation.server_surfaces.is_empty() {
984        println!("server surfaces: none");
985    } else {
986        println!("server surfaces:");
987        for surface in &explanation.server_surfaces {
988            if let Some(anchor) = &surface.source_anchor {
989                println!(
990                    "- {} @ {}:{}: {}",
991                    surface.kind, anchor.start_line, anchor.start_column, surface.detail
992                );
993            } else {
994                println!("- {}: {}", surface.kind, surface.detail);
995            }
996        }
997    }
998    if explanation.crossings.is_empty() {
999        println!("client crossings: none");
1000    } else {
1001        println!("client crossings:");
1002        for crossing in &explanation.crossings {
1003            if let Some(anchor) = &crossing.source_anchor {
1004                println!(
1005                    "- {} @ {}:{}: {}",
1006                    crossing.kind, anchor.start_line, anchor.start_column, crossing.detail
1007                );
1008            } else {
1009                println!("- {}: {}", crossing.kind, crossing.detail);
1010            }
1011        }
1012    }
1013    if explanation.dead_primitives.is_empty() {
1014        println!("dead client primitives: none");
1015    } else {
1016        println!("dead client primitives:");
1017        for primitive in &explanation.dead_primitives {
1018            if let Some(anchor) = &primitive.source_anchor {
1019                println!(
1020                    "- {} @ {}:{}: {}",
1021                    primitive.kind, anchor.start_line, anchor.start_column, primitive.detail
1022                );
1023            } else {
1024                println!("- {}: {}", primitive.kind, primitive.detail);
1025            }
1026        }
1027    }
1028
1029    if explanation.roots.is_empty() {
1030        println!("why: no reachable client roots");
1031    } else {
1032        println!("why:");
1033        for root in &explanation.roots {
1034            println!("- {}: {}", root.kind, root.detail);
1035        }
1036    }
1037
1038    println!("emitted:");
1039    println!("- wrapper: {}", yes_no(explanation.emitted.wrapper));
1040    println!("- seed script: {}", yes_no(explanation.emitted.seed_script));
1041    println!(
1042        "- manifest registration: {}",
1043        yes_no(explanation.emitted.manifest_registration)
1044    );
1045    println!("- JS asset: {}", yes_no(explanation.emitted.js_asset));
1046    println!(
1047        "- component fragment asset: {}",
1048        yes_no(explanation.emitted.component_fragment_asset)
1049    );
1050
1051    println!("next actions:");
1052    for action in &explanation.next_actions {
1053        println!("- {action}");
1054    }
1055
1056    Ok(())
1057}
1058
1059pub fn print_crossing_report(report: &CrossingReport, json: bool) -> Result<()> {
1060    if json {
1061        println!("{}", serde_json::to_string_pretty(report)?);
1062        return Ok(());
1063    }
1064
1065    println!("RSJS client crossings: {}", report.crossing_count);
1066    println!("strategy sidecars: {}", report.sidecar_count);
1067    if let Some(selector) = &report.selector {
1068        println!("selector: {selector}");
1069    }
1070    if report.crossings.is_empty() {
1071        println!("client crossings: none");
1072        return Ok(());
1073    }
1074    for crossing in &report.crossings {
1075        let label = crossing.crossing.label.as_deref().unwrap_or("<unlabeled>");
1076        let surface = crossing
1077            .crossing
1078            .surface
1079            .as_deref()
1080            .unwrap_or("browser_state");
1081        let requirement = crossing
1082            .crossing
1083            .requirement
1084            .as_deref()
1085            .unwrap_or("client_encode");
1086        if let Some(anchor) = &crossing.crossing.source_anchor {
1087            println!(
1088                "- {} {} `{label}` -> `{surface}` ({requirement}) @ {}:{}",
1089                crossing.struct_path,
1090                crossing.crossing.kind,
1091                anchor.start_line,
1092                anchor.start_column
1093            );
1094        } else {
1095            println!(
1096                "- {} {} `{label}` -> `{surface}` ({requirement})",
1097                crossing.struct_path, crossing.crossing.kind
1098            );
1099        }
1100    }
1101    Ok(())
1102}
1103
1104fn find_strategy_sidecar(root: &Path, selector: &str) -> Result<PathBuf> {
1105    let direct = PathBuf::from(selector);
1106    if direct.exists() {
1107        return Ok(direct);
1108    }
1109
1110    let mut candidates = Vec::new();
1111    for dir in strategy_dirs(root) {
1112        let exact = dir.join(format!("{selector}.json"));
1113        if exact.exists() {
1114            return Ok(exact);
1115        }
1116        candidates.push(dir);
1117    }
1118
1119    let mut matches: Vec<(PathBuf, String, String)> = Vec::new();
1120    for dir in candidates {
1121        let Ok(entries) = std::fs::read_dir(&dir) else {
1122            continue;
1123        };
1124        for entry in entries.flatten() {
1125            let path = entry.path();
1126            if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
1127                continue;
1128            }
1129            let Ok(text) = std::fs::read_to_string(&path) else {
1130                continue;
1131            };
1132            let Ok(sidecar) = serde_json::from_str::<StrategySidecar>(&text) else {
1133                continue;
1134            };
1135            if sidecar_matches(&sidecar, selector)
1136                && !matches
1137                    .iter()
1138                    .any(|(_, analysis_id, _)| *analysis_id == sidecar.analysis_id)
1139            {
1140                matches.push((path, sidecar.analysis_id, sidecar.struct_path));
1141            }
1142        }
1143    }
1144
1145    match matches.len() {
1146        0 => bail!(
1147            "could not find rsjs strategy sidecar for `{selector}` under {}",
1148            root.display()
1149        ),
1150        1 => Ok(matches.remove(0).0),
1151        _ => {
1152            let mut listing = String::new();
1153            for (path, analysis_id, struct_path) in &matches {
1154                listing.push_str(&format!(
1155                    "\n  {struct_path} (analysis id {analysis_id}, {})",
1156                    path.display()
1157                ));
1158            }
1159            bail!(
1160                "selector `{selector}` matches {} rsjs strategy sidecars; disambiguate with the struct path or analysis id:{listing}",
1161                matches.len()
1162            )
1163        }
1164    }
1165}
1166
1167fn strategy_dirs(root: &Path) -> Vec<PathBuf> {
1168    let root_local = root.join("target").join("rsjs").join("strategy");
1169    if let Ok(current) = std::env::current_dir() {
1170        let same_workspace = current == root || current.starts_with(root);
1171        if !same_workspace && root_local.exists() {
1172            // An explicit foreign workspace (including isolated test
1173            // fixtures) must not be contaminated by this process's own
1174            // CARGO_TARGET_DIR or current working directory artifacts.
1175            return vec![root_local];
1176        }
1177    }
1178
1179    let mut dirs = Vec::new();
1180    if let Ok(target) = std::env::var("CARGO_TARGET_DIR") {
1181        dirs.push(PathBuf::from(target).join("rsjs").join("strategy"));
1182    }
1183    dirs.push(root_local);
1184    if let Some(parent) = root.parent() {
1185        dirs.push(parent.join("target").join("rsjs").join("strategy"));
1186    }
1187    if let Ok(current) = std::env::current_dir() {
1188        dirs.push(current.join("target").join("rsjs").join("strategy"));
1189    }
1190
1191    let mut seen = BTreeSet::new();
1192    dirs.into_iter()
1193        .filter(|dir| seen.insert(dir.clone()))
1194        .collect()
1195}
1196
1197fn validate_sidecar(sidecar: &StrategySidecar, path: &Path) -> Result<()> {
1198    if sidecar.format != "rsjs.strategy" {
1199        bail!(
1200            "{} is not an rsjs strategy sidecar (format={:?})",
1201            path.display(),
1202            sidecar.format
1203        );
1204    }
1205    if sidecar.strategy_version != 1 {
1206        bail!(
1207            "{} uses unsupported rsjs strategy_version {}; this CLI supports 1",
1208            path.display(),
1209            sidecar.strategy_version
1210        );
1211    }
1212    Ok(())
1213}
1214
1215fn sidecar_matches(sidecar: &StrategySidecar, selector: &str) -> bool {
1216    sidecar.format == "rsjs.strategy"
1217        && (sidecar.analysis_id == selector
1218            || sidecar.runtime_asset_id.as_deref() == Some(selector)
1219            || sidecar.struct_name == selector
1220            || sidecar.struct_path == selector)
1221}
1222
1223fn explain_hydration_strategy(
1224    strategy: &HydrationStrategySidecar,
1225    server_only: bool,
1226) -> ExplainedHydrationStrategy {
1227    let label = hydration_strategy_label(strategy);
1228    ExplainedHydrationStrategy {
1229        kind: strategy.kind.clone(),
1230        ignored: server_only && strategy.kind != "immediate",
1231        label,
1232    }
1233}
1234
1235fn hydration_strategy_label(strategy: &HydrationStrategySidecar) -> String {
1236    if let Some(label) = &strategy.label {
1237        return label.clone();
1238    }
1239    match strategy.kind.as_str() {
1240        "interaction" => strategy
1241            .event
1242            .as_ref()
1243            .map(|event| format!("interaction:{event}"))
1244            .unwrap_or_else(|| "interaction".to_string()),
1245        "media" => strategy
1246            .query
1247            .as_ref()
1248            .map(|query| format!("media:{query}"))
1249            .unwrap_or_else(|| "media:<unknown>".to_string()),
1250        other => other.to_string(),
1251    }
1252}
1253
1254fn sidecar_runtime_features(sidecar: &StrategySidecar) -> Vec<String> {
1255    let mut features = if sidecar.runtime_features.is_empty() {
1256        let mut derived = Vec::new();
1257        if sidecar.emitted.uses_queries {
1258            derived.push("query".to_string());
1259        }
1260        if sidecar.emitted.uses_mutations {
1261            derived.push("mutation".to_string());
1262        }
1263        if sidecar.emitted.uses_shared_state {
1264            derived.push("shared_state".to_string());
1265        }
1266        derived
1267    } else {
1268        sidecar.runtime_features.clone()
1269    };
1270
1271    let mut seen = BTreeSet::new();
1272    features.retain(|feature| seen.insert(feature.clone()));
1273    features
1274}
1275
1276/// Sidecar `rust_type` strings are recorded from proc-macro token streams,
1277/// whose Display form inserts spaces between every token: `state::WorkbenchState`
1278/// arrives as "state :: WorkbenchState" and `Vec<Item>` as "Vec < Item >".
1279/// Collapse that spacing back to the canonical source spelling so `explain`
1280/// prints what the author wrote and the same store type spelled through the
1281/// same path compares equal across islands in `--json` output. A space is
1282/// kept only where removing it would glue two word tokens together
1283/// (`dyn Trait`, `impl Trait`).
1284fn normalize_rust_type_tokens(raw: &str) -> String {
1285    fn is_word_char(ch: char) -> bool {
1286        ch.is_alphanumeric() || ch == '_'
1287    }
1288
1289    let mut out = String::with_capacity(raw.len());
1290    let mut chars = raw.chars().peekable();
1291    while let Some(ch) = chars.next() {
1292        if ch.is_whitespace() {
1293            while chars.peek().is_some_and(|next| next.is_whitespace()) {
1294                chars.next();
1295            }
1296            let previous = out.chars().next_back();
1297            let next = chars.peek().copied();
1298            if let (Some(previous), Some(next)) = (previous, next) {
1299                if is_word_char(previous) && is_word_char(next) {
1300                    out.push(' ');
1301                }
1302            }
1303            continue;
1304        }
1305        out.push(ch);
1306    }
1307    out
1308}
1309
1310fn strategy_shared_state_dependency(
1311    dependency: &SharedStateDependencySidecar,
1312) -> StrategySharedStateDependency {
1313    StrategySharedStateDependency {
1314        store: dependency.store,
1315        rust_type: normalize_rust_type_tokens(&dependency.rust_type),
1316        type_key: dependency.type_key.clone(),
1317        fields: dependency.fields.clone(),
1318        serialized_fields: dependency.serialized_fields.clone(),
1319        provider_serializes_full_snapshot: dependency.provider_serializes_full_snapshot,
1320        source_anchor: dependency
1321            .source
1322            .as_ref()
1323            .map(|anchor| StrategyClientCrossingAnchor {
1324                start_line: anchor.start_line,
1325                start_column: anchor.start_column,
1326            }),
1327    }
1328}
1329
1330fn sidecar_component_fragment_imports(sidecar: &StrategySidecar) -> Vec<String> {
1331    let mut imports = sidecar.component_fragment_imports.clone();
1332    for root in &sidecar.roots {
1333        if root.kind != "component_fragment_mount" {
1334            continue;
1335        }
1336        if let Some(asset_id) = &root.asset_id {
1337            imports.push(asset_id.clone());
1338        }
1339    }
1340
1341    imports.sort();
1342    imports.dedup();
1343    imports
1344}
1345
1346fn unused_client_modules(declared: &[String], client_modules: &[String]) -> Vec<String> {
1347    let shipped: BTreeSet<_> = client_modules.iter().map(String::as_str).collect();
1348    let mut seen = BTreeSet::new();
1349    let mut unused = Vec::new();
1350    for module in declared {
1351        if !shipped.contains(module.as_str()) && seen.insert(module.as_str()) {
1352            unused.push(module.clone());
1353        }
1354    }
1355    unused
1356}
1357
1358fn explain_root(root: &StrategyRoot) -> ExplainedRoot {
1359    ExplainedRoot {
1360        kind: root.kind.clone(),
1361        detail: root_detail(root),
1362    }
1363}
1364
1365fn explain_server_surface(surface: &ServerSurfaceSidecar) -> ExplainedServerSurface {
1366    ExplainedServerSurface {
1367        kind: surface.kind.clone(),
1368        source: surface.source.clone(),
1369        source_anchor: surface.source_anchor.as_ref().map(strategy_surface_anchor),
1370        detail: server_surface_detail(surface),
1371    }
1372}
1373
1374fn explain_client_crossing(crossing: &ClientCrossingSidecar) -> ExplainedClientCrossing {
1375    ExplainedClientCrossing {
1376        kind: crossing.kind.clone(),
1377        label: crossing.label.clone(),
1378        module: crossing.module.clone(),
1379        name: crossing.name.clone(),
1380        arg_index: crossing.arg_index,
1381        asset_id: crossing.asset_id.clone(),
1382        prop: crossing.prop.clone(),
1383        root: crossing.root,
1384        child_signal: crossing.child_signal,
1385        parent_signal: crossing.parent_signal,
1386        signal: crossing.signal,
1387        query: crossing.query,
1388        mutation: crossing.mutation,
1389        invalidation_index: crossing.invalidation_index,
1390        node: crossing.node,
1391        attr: crossing.attr.clone(),
1392        surface: crossing.surface.clone(),
1393        requirement: crossing.requirement.clone(),
1394        source_anchor: crossing
1395            .source_anchor
1396            .as_ref()
1397            .map(strategy_client_crossing_anchor),
1398        detail: client_crossing_detail(crossing),
1399    }
1400}
1401
1402fn explain_dead_primitive(primitive: &DeadPrimitiveSidecar) -> ExplainedDeadPrimitive {
1403    ExplainedDeadPrimitive {
1404        kind: primitive.kind.clone(),
1405        label: primitive.label.clone(),
1406        signal: primitive.signal,
1407        handler: primitive.handler,
1408        node_ref: primitive.node_ref,
1409        query: primitive.query,
1410        mutation: primitive.mutation,
1411        source_anchor: primitive
1412            .source_anchor
1413            .as_ref()
1414            .map(strategy_dead_primitive_anchor),
1415        detail: dead_primitive_detail(primitive),
1416    }
1417}
1418
1419fn strategy_server_surface_summary(surface: &ServerSurfaceSidecar) -> StrategyServerSurfaceSummary {
1420    StrategyServerSurfaceSummary {
1421        kind: surface.kind.clone(),
1422        source: surface.source.clone(),
1423        node: surface.node,
1424        attr: surface.attr.clone(),
1425        reason: surface.reason.clone(),
1426        source_anchor: surface.source_anchor.as_ref().map(strategy_surface_anchor),
1427    }
1428}
1429
1430fn strategy_client_crossing_summary(
1431    crossing: &ClientCrossingSidecar,
1432) -> StrategyClientCrossingSummary {
1433    StrategyClientCrossingSummary {
1434        kind: crossing.kind.clone(),
1435        label: crossing.label.clone(),
1436        module: crossing.module.clone(),
1437        name: crossing.name.clone(),
1438        arg_index: crossing.arg_index,
1439        asset_id: crossing.asset_id.clone(),
1440        prop: crossing.prop.clone(),
1441        root: crossing.root,
1442        child_signal: crossing.child_signal,
1443        parent_signal: crossing.parent_signal,
1444        signal: crossing.signal,
1445        query: crossing.query,
1446        mutation: crossing.mutation,
1447        invalidation_index: crossing.invalidation_index,
1448        node: crossing.node,
1449        attr: crossing.attr.clone(),
1450        surface: crossing.surface.clone(),
1451        requirement: crossing.requirement.clone(),
1452        source_anchor: crossing
1453            .source_anchor
1454            .as_ref()
1455            .map(strategy_client_crossing_anchor),
1456    }
1457}
1458
1459fn strategy_dead_primitive_summary(
1460    primitive: &DeadPrimitiveSidecar,
1461) -> StrategyDeadPrimitiveSummary {
1462    StrategyDeadPrimitiveSummary {
1463        kind: primitive.kind.clone(),
1464        label: primitive.label.clone(),
1465        signal: primitive.signal,
1466        handler: primitive.handler,
1467        node_ref: primitive.node_ref,
1468        query: primitive.query,
1469        mutation: primitive.mutation,
1470        source_anchor: primitive
1471            .source_anchor
1472            .as_ref()
1473            .map(strategy_dead_primitive_anchor),
1474    }
1475}
1476
1477fn strategy_surface_anchor(anchor: &ServerSurfaceAnchorSidecar) -> StrategyServerSurfaceAnchor {
1478    StrategyServerSurfaceAnchor {
1479        start_line: anchor.start_line,
1480        start_column: anchor.start_column,
1481    }
1482}
1483
1484fn strategy_client_crossing_anchor(
1485    anchor: &ClientCrossingAnchorSidecar,
1486) -> StrategyClientCrossingAnchor {
1487    StrategyClientCrossingAnchor {
1488        start_line: anchor.start_line,
1489        start_column: anchor.start_column,
1490    }
1491}
1492
1493fn strategy_dead_primitive_anchor(
1494    anchor: &DeadPrimitiveAnchorSidecar,
1495) -> StrategyDeadPrimitiveAnchor {
1496    StrategyDeadPrimitiveAnchor {
1497        start_line: anchor.start_line,
1498        start_column: anchor.start_column,
1499    }
1500}
1501
1502fn server_surface_detail(surface: &ServerSurfaceSidecar) -> String {
1503    let reason = surface
1504        .reason
1505        .as_deref()
1506        .or_else(|| surface.source.as_deref().map(server_surface_source_label))
1507        .unwrap_or("server rendered");
1508    match surface.kind.as_str() {
1509        "server_attr" => format!(
1510            "node {} attr `{}` rendered on server ({reason})",
1511            surface.node.unwrap_or_default(),
1512            surface.attr.as_deref().unwrap_or("<unknown>")
1513        ),
1514        "server_slot" => format!(
1515            "node {} server-rendered slot ({reason})",
1516            surface.node.unwrap_or_default()
1517        ),
1518        _ => format!(
1519            "node {} server surface ({reason})",
1520            surface.node.unwrap_or_default()
1521        ),
1522    }
1523}
1524
1525fn dead_primitive_detail(primitive: &DeadPrimitiveSidecar) -> String {
1526    let label = primitive.label.as_deref().unwrap_or("<unlabeled>");
1527    match primitive.kind.as_str() {
1528        "signal" => format!(
1529            "`{label}` signal {} was declared but no reachable client root reads or writes it",
1530            primitive.signal.unwrap_or_default()
1531        ),
1532        "memo" => format!(
1533            "`{label}` memo signal {} was declared but no reachable client root reads it",
1534            primitive.signal.unwrap_or_default()
1535        ),
1536        "handler" => format!(
1537            "`{label}` handler {} was declared but no reachable event binding uses it",
1538            primitive.handler.unwrap_or_default()
1539        ),
1540        "node_ref" => format!(
1541            "`{label}` node_ref {} was declared but no reachable ref binding, handler, or expression uses it",
1542            primitive.node_ref.unwrap_or_default()
1543        ),
1544        "query" => format!(
1545            "`{label}` query {} was declared but no reachable client root observes, refetches, or invalidates it",
1546            primitive.query.unwrap_or_default()
1547        ),
1548        "mutation" => format!(
1549            "`{label}` mutation {} was declared but no reachable client root reads or runs it",
1550            primitive.mutation.unwrap_or_default()
1551        ),
1552        kind => format!("`{label}` {kind} declaration was not reachable from client roots"),
1553    }
1554}
1555
1556fn client_crossing_detail(crossing: &ClientCrossingSidecar) -> String {
1557    client_crossing_summary_detail(&strategy_client_crossing_summary(crossing))
1558}
1559
1560pub(crate) fn client_crossing_summary_detail(crossing: &StrategyClientCrossingSummary) -> String {
1561    let label = crossing.label.as_deref().unwrap_or("<unlabeled>");
1562    let surface = crossing.surface.as_deref().unwrap_or("browser_state");
1563    let requirement = crossing.requirement.as_deref().unwrap_or("client_encode");
1564    match crossing.kind.as_str() {
1565        "signal_initial_value" => format!(
1566            "`{label}` signal initial value crosses to `{surface}` and requires `{requirement}`"
1567        ),
1568        "handler_payload" => format!(
1569            "`{label}` handler payload crosses to `{surface}` on node {} attr `{}` and requires `{requirement}`",
1570            crossing.node.unwrap_or_default(),
1571            crossing.attr.as_deref().unwrap_or("<unknown>")
1572        ),
1573        "node_payload" => format!(
1574            "`{label}` node payload crosses to `{surface}` on node {} attr `{}` and requires `{requirement}`",
1575            crossing.node.unwrap_or_default(),
1576            crossing.attr.as_deref().unwrap_or("<unknown>")
1577        ),
1578        "query_key" => format!(
1579            "`{label}` query key crosses to `{surface}` for query {} and requires `{requirement}`",
1580            crossing.query.unwrap_or_default()
1581        ),
1582        "query_fetcher" => format!(
1583            "`{label}` query fetcher config crosses to `{surface}` for query {} and requires `{requirement}`",
1584            crossing.query.unwrap_or_default()
1585        ),
1586        "query_initial_value" => format!(
1587            "`{label}` query initial value crosses to `{surface}` for query {} and requires `{requirement}`",
1588            crossing.query.unwrap_or_default()
1589        ),
1590        "mutation_key" => format!(
1591            "`{label}` mutation key crosses to `{surface}` for mutation {} and requires `{requirement}`",
1592            crossing.mutation.unwrap_or_default()
1593        ),
1594        "mutation_runner" => format!(
1595            "`{label}` mutation runner config crosses to `{surface}` for mutation {} and requires `{requirement}`",
1596            crossing.mutation.unwrap_or_default()
1597        ),
1598        "mutation_invalidation_key" => format!(
1599            "`{label}` mutation invalidation key {} crosses to `{surface}` for mutation {} and requires `{requirement}`",
1600            crossing.invalidation_index.unwrap_or_default(),
1601            crossing.mutation.unwrap_or_default()
1602        ),
1603        // Compatibility for older experimental sidecars. Current v2
1604        // sidecars report client helper calls as roots/import edges; any
1605        // public data is recorded by the underlying signal/payload/query/
1606        // mutation/descriptor crossing surface instead.
1607        "client_helper_argument" => format!(
1608            "`{label}` client helper argument {} crosses to `{surface}` for `{}::{}` and requires `{requirement}`",
1609            crossing.arg_index.unwrap_or_default(),
1610            crossing.module.as_deref().unwrap_or("<unknown>"),
1611            crossing.name.as_deref().unwrap_or("<unknown>")
1612        ),
1613        "descriptor_reactive_prop" => format!(
1614            "`{label}` descriptor reactive prop `{}` crosses to `{surface}` for fragment `{}` at root {} (child signal {}, parent signal {}) and requires `{requirement}`",
1615            crossing.prop.as_deref().unwrap_or("<unknown>"),
1616            crossing.asset_id.as_deref().unwrap_or("<unknown>"),
1617            crossing.root.unwrap_or_default(),
1618            crossing.child_signal.unwrap_or_default(),
1619            crossing.parent_signal.unwrap_or_default()
1620        ),
1621        kind => {
1622            format!("`{label}` crosses to `{surface}` as `{kind}` and requires `{requirement}`")
1623        }
1624    }
1625}
1626
1627fn server_surface_source_label(source: &str) -> &'static str {
1628    match source {
1629        "explicit_boundary" => "explicit SSR boundary",
1630        "explicit_simple_ssr_boundary" => "explicit wrapper around simple SSR projection",
1631        "inferred_simple_ssr" => "inferred simple SSR projection",
1632        "keyed_list_item" => "keyed-list item SSR template",
1633        "explicit_island_boundary" => "explicit island boundary",
1634        _ => "server rendered",
1635    }
1636}
1637
1638fn root_detail(root: &StrategyRoot) -> String {
1639    match root.kind.as_str() {
1640        "text_binding" => format_node("text binding", root.node),
1641        "attr_binding" => format!(
1642            "node {} dynamic attribute `{}`",
1643            root.node.unwrap_or_default(),
1644            root.name.as_deref().unwrap_or("<unknown>")
1645        ),
1646        "event_binding" => format!(
1647            "node {} event `{}` ({})",
1648            root.node.unwrap_or_default(),
1649            root.event.as_deref().unwrap_or("<unknown>"),
1650            root.dom_event.as_deref().unwrap_or("unknown DOM event")
1651        ),
1652        "conditional_section" => format_node("conditional section parent", root.parent),
1653        "input_binding" => format_node("input binding", root.node),
1654        "node_ref_binding" => format!(
1655            "node {} bound to node_ref {}",
1656            root.node.unwrap_or_default(),
1657            root.node_ref.unwrap_or_default()
1658        ),
1659        "node_ref" => format!("node_ref {}", root.id.unwrap_or_default()),
1660        "signal" => format!("signal {}", root.id.unwrap_or_default()),
1661        "query" => format!("query {}", root.id.unwrap_or_default()),
1662        "mutation" => format!("mutation {}", root.id.unwrap_or_default()),
1663        "browser_read" => format!(
1664            "browser read `{}`",
1665            root.read.as_deref().unwrap_or("<unknown>")
1666        ),
1667        "browser_effect" => format!(
1668            "browser effect `{}`",
1669            root.effect.as_deref().unwrap_or("<unknown>")
1670        ),
1671        "client_module_call" => format!(
1672            "client module `{}` helper `{}`",
1673            root.module.as_deref().unwrap_or("<unknown>"),
1674            root.name.as_deref().unwrap_or("<unknown>")
1675        ),
1676        "interval" => format!("interval {}", root.index.unwrap_or_default()),
1677        "keyed_list" => format_node("keyed list container", root.container),
1678        "component_fragment_mount" => format!(
1679            "component fragment `{}` mounted at root {} through the schema-v4 parent-mounted fragment path",
1680            root.asset_id.as_deref().unwrap_or("<unknown>"),
1681            root.root.unwrap_or_default()
1682        ),
1683        _ => "unknown client reachability root".to_string(),
1684    }
1685}
1686
1687fn format_node(label: &str, node: Option<u64>) -> String {
1688    format!("{label} node {}", node.unwrap_or_default())
1689}
1690
1691fn strategy_source_anchor(source: StrategySourceSidecar) -> StrategySourceAnchor {
1692    StrategySourceAnchor {
1693        file: source.file,
1694        impl_start_line: source.impl_start_line,
1695        impl_start_column: source.impl_start_column,
1696        render_start_line: source.render_start_line,
1697        render_start_column: source.render_start_column,
1698    }
1699}
1700
1701fn human_strategy(strategy: &str) -> &str {
1702    match strategy {
1703        "server_only" => "ServerOnly",
1704        "ssr_hydrate" => "SSR + Hydrate",
1705        "client_only_explicit" => "ClientOnlyExplicit",
1706        other => other,
1707    }
1708}
1709
1710fn yes_no(value: bool) -> &'static str {
1711    if value {
1712        "yes"
1713    } else {
1714        "no"
1715    }
1716}
1717
1718#[cfg(test)]
1719mod tests;