Skip to main content

fallow_types/
envelope.rs

1//! Typed envelope and utility-shape structs for the JSON output contract.
2//!
3//! Today the JSON serialization layer (`crates/cli/src/report/json.rs`) builds
4//! its envelopes (`CheckOutput`, `HealthOutput`, ...) via `serde_json::json!`
5//! macros and ad-hoc map merging. The types in this module are the schema-side
6//! counterpart of those envelopes plus a small set of utility shapes
7//! (`SchemaVersion`, `Meta`, `BaselineDeltas`, ...) that the envelopes
8//! reference.
9//!
10//! Gated on the `schema` cargo feature so consumers that do not need the
11//! `schemars::JsonSchema` derive (every crate except `fallow-cli` with
12//! `--features schema-emit`) skip the schemars compile cost.
13
14use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18use crate::semantic::{
19    ApiSurfaceResult, SemanticAnalysisIdentity, SemanticCandidateDecision, SemanticGapReason,
20    SemanticQuerySummary, SemanticSymbolImpact, SemanticSymbolTrace, TypeCouplingReport,
21};
22
23/// Schema version for this output format (independent of tool version). Bump
24/// policy: Additive changes (new optional top-level fields, new optional struct
25/// fields, new array entries, new MCP tools, new CLI flags that map to new
26/// optional fields) do NOT bump the version; consumers receive new fields
27/// without breaking. Breaking changes (renamed fields, removed fields, type
28/// changes, enum-variant removals, semantic changes to existing fields) DO
29/// bump. Additions to existing enum-valued required fields bump the affected
30/// envelope version so strict JSON Schema consumers can migrate.
31/// `ComplexityContributionKind` is non-exhaustive so Rust consumers retain a
32/// wildcard. To
33/// detect newly-added fields without a bump, check field presence via
34/// JSON-key existence rather than gating on the version. v4 was introduced
35/// alongside fallow-cov-protocol 0.2 (per-finding verdict, stable IDs, evidence
36/// block, renamed summary fields); v5 introduced health_score formula_version 2
37/// with scale-invariant scoring semantics; v6 widened `AddToConfigAction.value`
38/// from a scalar string to `oneOf: [string, array]` so the new `ignoreExports`
39/// action can carry a paste-ready array of `{ file, exports }` rule objects
40/// (the legacy `ignoreDependencies` etc. variants still emit strings, so
41/// consumers that switch on `config_key` keep working unchanged). v8 added the
42/// required duplication `spread` field and changed `duplicated_tokens` to count
43/// redundant copies, excluding the retained copy in each group. Envelopes
44/// embedding health use their own version marker, so health-only contract
45/// changes do not advance dead-code or unrelated sibling envelopes. The
46/// runtime-coverage block is extended additively as the protocol evolves
47/// (currently 0.3, which adds an optional capture_quality summary field). Other
48/// additive examples: dupes --group-by adds optional grouped_by, total_issues,
49/// groups fields without bumping.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
51#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
52#[serde(transparent)]
53pub struct SchemaVersion(pub u32);
54
55/// Fallow CLI version that produced this envelope. Renders to the JSON wire as
56/// a bare string (e.g. `"2.74.0"`).
57#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(transparent)]
60pub struct ToolVersion(pub String);
61
62/// Analysis duration in milliseconds. Renders to the JSON wire as a bare
63/// integer.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66#[serde(transparent)]
67pub struct ElapsedMs(pub u64);
68
69/// Audit-mode marker emitted on each finding when `fallow audit --format json`
70/// runs with a base ref. `true` means the finding's structural key was not
71/// present at the base ref (introduced by the current changeset); `false`
72/// means it was inherited. Duplication findings carry one carve-out: a clone
73/// group whose structural key is new but whose instances contain no added line
74/// from the diff (a group re-shaped by removing duplication elsewhere) is
75/// demoted to inherited and serializes `false` (issue #2164). Such demoted
76/// groups additionally carry a `demotion_reason` field naming the rule, and
77/// are counted in `attribution.duplication_demoted` (issue #2220).
78///
79/// Outside of audit sub-results the field is omitted, so call sites typically
80/// hold `Option<AuditIntroduced>`. Renders to the JSON wire as a bare boolean.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
82#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
83#[serde(transparent)]
84pub struct AuditIntroduced(pub bool);
85
86/// Entry-point detection summary embedded in `CheckOutput` and the combined
87/// envelope.
88#[derive(Debug, Clone, Default, Serialize)]
89#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
90pub struct EntryPoints {
91    /// Total number of detected entry points.
92    pub total: usize,
93    /// Breakdown of entry points by detection source (e.g., `"package.json"`,
94    /// `"next.js"`, `"config entry"`). Underscored keys so dashboards can
95    /// drill into individual sources.
96    pub sources: BTreeMap<String, usize>,
97}
98
99#[expect(
100    clippy::trivially_copy_pass_by_ref,
101    reason = "serde skip_serializing_if requires a reference"
102)]
103const fn zero_count(count: &usize) -> bool {
104    *count == 0
105}
106
107/// Per-category issue counts for dead-code analysis. Always present in
108/// `CheckOutput`; when `--summary` is used the individual issue arrays are
109/// omitted but this object stays populated.
110#[derive(Debug, Clone, Default, Serialize)]
111#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
112pub struct CheckSummary {
113    /// Total number of issues across all categories.
114    pub total_issues: usize,
115    /// Prop chains whose saved effective severity explicitly enforces error policy.
116    #[serde(default, skip_serializing_if = "zero_count")]
117    pub prop_drilling_chains: usize,
118    /// Thin wrappers whose saved effective severity explicitly enforces error policy.
119    #[serde(default, skip_serializing_if = "zero_count")]
120    pub thin_wrappers: usize,
121    /// Duplicate prop shapes whose saved effective severity explicitly enforces error policy.
122    #[serde(default, skip_serializing_if = "zero_count")]
123    pub duplicate_prop_shapes: usize,
124    /// Unused source files.
125    pub unused_files: usize,
126    /// Unused value exports.
127    pub unused_exports: usize,
128    /// Unused type exports.
129    pub unused_types: usize,
130    /// Public exports whose signature references same-file private types.
131    pub private_type_leaks: usize,
132    /// Exports marked `@deprecated` that are still referenced.
133    pub deprecated_exports_in_use: usize,
134    /// Combined count of unused entries across `dependencies`,
135    /// `devDependencies`, and `optionalDependencies`. The per-section
136    /// breakdown lives in the individual issue arrays on `CheckOutput`.
137    pub unused_dependencies: usize,
138    /// Unused enum members.
139    pub unused_enum_members: usize,
140    /// Unused class members.
141    pub unused_class_members: usize,
142    /// Unused namespace members.
143    #[serde(default)]
144    pub unused_namespace_members: usize,
145    /// Unused protected class members. Omitted when zero, because the rule
146    /// is `off` by default.
147    #[serde(default, skip_serializing_if = "zero_count")]
148    pub unused_protected_class_members: usize,
149    /// Unused store members.
150    #[serde(default)]
151    pub unused_store_members: usize,
152    /// Vue/Svelte injects whose key is provided nowhere in the project.
153    #[serde(default)]
154    pub unprovided_injects: usize,
155    /// Vue/Svelte components reachable but rendered nowhere in the project.
156    #[serde(default)]
157    pub unrendered_components: usize,
158    /// Vue, Svelte, or React props referenced nowhere inside their own component.
159    #[serde(default)]
160    pub unused_component_props: usize,
161    /// Optional consumed props omitted by known reachable callers, for manual review.
162    #[serde(default)]
163    pub absent_component_props: usize,
164    /// Parameters that each visible call passes in one way, for manual review.
165    /// Absent while zero, so a run with the opt-in rule off keeps its shape.
166    #[serde(default, skip_serializing_if = "zero_count")]
167    pub constant_parameters: usize,
168    /// Vue `<script setup>` emits emitted nowhere inside their own SFC.
169    #[serde(default)]
170    pub unused_component_emits: usize,
171    /// Angular `@Input()` bindings referenced nowhere inside their own component.
172    #[serde(default)]
173    pub unused_component_inputs: usize,
174    /// Angular `@Output()` bindings emitted nowhere inside their own component.
175    #[serde(default)]
176    pub unused_component_outputs: usize,
177    /// Svelte components dispatching a custom event via `createEventDispatcher`
178    /// whose name is listened to nowhere in the project.
179    #[serde(default)]
180    pub unused_svelte_events: usize,
181    /// Effect layers composed only into layers that nothing uses.
182    #[serde(default)]
183    pub unused_effect_layers: usize,
184    /// Effect tagged error classes that no code constructs or fails with.
185    #[serde(default)]
186    pub unused_tagged_errors: usize,
187    /// `catchTag` handlers for a project tag that no code produces.
188    #[serde(default)]
189    pub unproduced_catch_tags: usize,
190    /// Next.js Server Actions (exports of `"use server"` files) referenced by no
191    /// code in the project.
192    #[serde(default)]
193    pub unused_server_actions: usize,
194    /// SvelteKit `load()` return-object keys read by no consumer.
195    #[serde(default)]
196    pub unused_load_data_keys: usize,
197    /// Imports that could not be resolved against the project's module graph.
198    pub unresolved_imports: usize,
199    /// Dependencies imported but absent from `package.json`.
200    pub unlisted_dependencies: usize,
201    /// Binaries that scripts or process calls run, but that no installed or
202    /// listed package provides.
203    #[serde(default)]
204    pub unlisted_binaries: usize,
205    /// Same-named exports declared in more than one module.
206    pub duplicate_exports: usize,
207    /// Bindings that one module exports under two or more names.
208    #[serde(default)]
209    pub duplicate_export_aliases: usize,
210    /// Production dependencies only used via type-only imports (could be
211    /// devDependencies). Only populated in production mode.
212    pub type_only_dependencies: usize,
213    /// Production dependencies only imported by test files (could be
214    /// devDependencies).
215    pub test_only_dependencies: usize,
216    /// devDependencies imported by production source code with a runtime/value
217    /// import (should be promoted to dependencies).
218    pub dev_dependencies_in_production: usize,
219    /// Cycles detected in the import graph.
220    pub circular_dependencies: usize,
221    /// Cycles or self-loops in the re-export edge subgraph (barrel files
222    /// re-exporting from each other in a loop).
223    #[serde(default)]
224    pub re_export_cycles: usize,
225    /// Dependency cycles between workspace packages.
226    #[serde(default)]
227    pub package_cycles: usize,
228    /// Imports that cross architecture boundary rules.
229    pub boundary_violations: usize,
230    /// Files that match no architecture boundary zone.
231    #[serde(default)]
232    pub boundary_coverage_violations: usize,
233    /// Calls from zoned files to callees forbidden for that zone.
234    #[serde(default)]
235    pub boundary_call_violations: usize,
236    /// Banned calls, imports, and catalogue-derived effects matched by
237    /// declarative rule packs.
238    #[serde(default)]
239    pub policy_violations: usize,
240    /// Suppression comments that no longer match a finding.
241    pub stale_suppressions: usize,
242    /// Unused pnpm-workspace catalog entries.
243    pub unused_catalog_entries: usize,
244    /// Empty named catalog groups.
245    pub empty_catalog_groups: usize,
246    /// Workspace package.json catalog references the workspace catalogs
247    /// do not declare.
248    pub unresolved_catalog_references: usize,
249    /// Package-manager overrides whose target package is not declared by any
250    /// workspace package and not present in the active readable lockfile.
251    pub unused_dependency_overrides: usize,
252    /// Package-manager overrides whose key or value cannot be parsed.
253    pub misconfigured_dependency_overrides: usize,
254    /// `"use client"` files that export a Next.js server-only / route-config name.
255    #[serde(default)]
256    pub invalid_client_exports: usize,
257    /// Barrel files that re-export both a `"use client"` origin and a
258    /// server-only origin.
259    #[serde(default)]
260    pub mixed_client_server_barrels: usize,
261    /// Misplaced `"use client"` / `"use server"` directives written as
262    /// expression statements after a non-directive statement.
263    #[serde(default)]
264    pub misplaced_directives: usize,
265    /// Next.js App Router route files that resolve to the same URL within one
266    /// app-root.
267    #[serde(default)]
268    pub route_collisions: usize,
269    /// Sibling Next.js dynamic route segments at one position using different
270    /// param spellings.
271    #[serde(default)]
272    pub dynamic_segment_name_conflicts: usize,
273}
274
275/// Per-category delta comparison against a saved baseline. Only present in
276/// `CheckOutput` when `--baseline` is used.
277#[derive(Debug, Clone, Default, Serialize)]
278#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
279pub struct BaselineDeltas {
280    /// Net change in total issues vs baseline (positive = more issues).
281    pub total_delta: i64,
282    /// Per-category breakdown of current, baseline, and delta counts.
283    pub per_category: BTreeMap<String, BaselineCategoryDelta>,
284}
285
286/// Single-category baseline delta entry inside [`BaselineDeltas::per_category`].
287#[derive(Debug, Clone, Copy, Default, Serialize)]
288#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
289pub struct BaselineCategoryDelta {
290    /// Current issue count for this category.
291    pub current: usize,
292    /// Baseline issue count for this category.
293    pub baseline: usize,
294    /// Change from baseline (current - baseline).
295    pub delta: i64,
296}
297
298/// Baseline match statistics. Shows how many baseline entries existed and how
299/// many matched current issues. Useful for detecting stale baselines
300/// programmatically. Only present in `CheckOutput` when `--baseline` is used.
301#[derive(Debug, Clone, Copy, Default, Serialize)]
302#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
303pub struct BaselineMatch {
304    /// Total number of entries in the loaded baseline file.
305    pub entries: usize,
306    /// Number of baseline entries that matched current issues and were
307    /// filtered.
308    pub matched: usize,
309}
310
311/// Result of regression detection (`--fail-on-regression`). Compares current
312/// issue counts against a baseline from config or an explicit file.
313#[derive(Debug, Clone, Serialize)]
314#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
315pub struct RegressionResult {
316    /// Outcome of the regression check.
317    pub status: RegressionStatus,
318    /// Baseline total before the change. Absent when status is `skipped`.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub baseline_total: Option<i64>,
321    /// Current total after the change. Absent when status is `skipped`.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub current_total: Option<i64>,
324    /// Difference current - baseline. Absent when status is `skipped`.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub delta: Option<i64>,
327    /// Configured tolerance, interpreted per [`RegressionToleranceKind`].
328    /// Absent when status is `skipped`.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub tolerance: Option<f64>,
331    /// Interpretation of the tolerance value.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub tolerance_kind: Option<RegressionToleranceKind>,
334    /// Whether the regression exceeded the tolerance.
335    pub exceeded: bool,
336    /// Only present when status is `skipped`.
337    #[serde(default, skip_serializing_if = "Option::is_none")]
338    pub reason: Option<String>,
339}
340
341/// Status of a regression-check pass.
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
343#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
344#[serde(rename_all = "lowercase")]
345pub enum RegressionStatus {
346    /// Issue count within tolerance.
347    Pass,
348    /// Issue count exceeded tolerance.
349    Exceeded,
350    /// Regression check did not run (missing baseline, etc.).
351    Skipped,
352}
353
354/// Interpretation of [`RegressionResult::tolerance`].
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
357#[serde(rename_all = "lowercase")]
358pub enum RegressionToleranceKind {
359    /// Tolerance is interpreted as an absolute issue-count delta.
360    Absolute,
361    /// Tolerance is interpreted as a percentage of the baseline total.
362    Percentage,
363}
364
365/// The `_meta` block of an envelope. A `--format json` run of the CLI always
366/// sets `telemetry.analysis_run_id`. With `--explain` (and in each MCP
367/// response), the block also holds the docs URL and the field, metric and
368/// rule definitions, so that a CI system can read the metric values without
369/// the docs site.
370#[derive(Debug, Clone, Default, Serialize)]
371#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
372pub struct Meta {
373    /// URL to the documentation page for this command.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub docs: Option<String>,
376    /// Local telemetry correlation metadata for agent follow-up runs.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub telemetry: Option<TelemetryMeta>,
379    /// Provenance for the opt-in TypeScript semantic analysis pass.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub type_aware: Option<TypeAwareMeta>,
382    /// Per-field definitions for envelope fields and action payload fields.
383    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
384    pub field_definitions: BTreeMap<String, String>,
385    /// Per-metric definitions: name, description, range, interpretation.
386    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
387    pub metrics: BTreeMap<String, MetaMetric>,
388    /// Per-rule definitions for check command output.
389    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
390    pub rules: BTreeMap<String, MetaRule>,
391}
392
393/// Bounded provenance emitted when the opt-in type-aware pass runs.
394#[derive(Debug, Clone, Default, Deserialize, Serialize)]
395#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
396pub struct TypeAwareMeta {
397    /// Compatibility identity used by audit, baselines, snapshots, and stores.
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub identity: Option<SemanticAnalysisIdentity>,
400    /// Effective CLI or repository policy for incomplete semantic evidence.
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub required_completeness: Option<crate::semantic::SemanticCompletenessRequirement>,
403    /// Compact status for every requested semantic query.
404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
405    pub queries: Vec<SemanticQuerySummary>,
406    /// Bounded decision and evidence for each semantic dead-code candidate.
407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
408    pub candidate_decisions: Vec<SemanticCandidateDecision>,
409    /// Checker-backed trace evidence requested by focused symbol queries.
410    #[serde(default, skip_serializing_if = "Vec::is_empty")]
411    pub symbol_traces: Vec<SemanticSymbolTrace>,
412    /// Package-public surface and confirmed private type leaks.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub api_surface: Option<ApiSurfaceResult>,
415    /// Exact-symbol blast radius and targeted-test recommendations.
416    #[serde(default, skip_serializing_if = "Vec::is_empty")]
417    pub symbol_impacts: Vec<SemanticSymbolImpact>,
418    /// Advisory project-local public-signature coupling.
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub type_coupling: Option<TypeCouplingReport>,
421    /// The call evidence of the `constant-parameter` rule. Present when the
422    /// rule sent candidates to the companion.
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub call_evidence: Option<TypeAwareCallEvidenceMeta>,
425    /// Whether the semantic companion executed at least one query.
426    pub executed: bool,
427    /// Version of Fallow's backend-neutral sidecar protocol.
428    pub protocol_version: u32,
429    /// Version of the sidecar package that executed the query.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub sidecar_version: Option<String>,
432    /// Semantic backend capability identifier.
433    pub backend: String,
434    /// Backend compiler or engine version that executed the query.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub backend_version: Option<String>,
437    /// TypeScript project configs selected for candidate files.
438    pub selected_tsconfigs: Vec<String>,
439    /// Number of candidate findings sent to the sidecar.
440    pub candidate_count: usize,
441    /// Number of candidates confirmed as used and removed.
442    pub confirmed_used_count: usize,
443    /// Number of candidates preserved because they implement or override a contract.
444    pub contract_preserved_count: usize,
445    /// Number of candidates with complete, closed-world no-static-reference evidence.
446    pub no_static_references_count: usize,
447    /// Number of retained class members eligible for a guarded type-aware fix.
448    pub fix_eligible_count: usize,
449    /// Number of candidates retained because semantic use was unresolved.
450    pub unresolved_count: usize,
451    /// Number of candidates retained because semantic analysis abstained.
452    pub abstained_count: usize,
453    /// Stable abstention reason counts for automation and diagnostics.
454    pub abstention_reasons: TypeAwareAbstentionCounts,
455    /// Per-project semantic refinement status and evidence.
456    pub projects: Vec<TypeAwareProjectMeta>,
457    /// Number of bounded warnings returned by the sidecar.
458    pub warning_count: usize,
459    /// Bounded semantic warnings. Findings mentioned here were retained.
460    pub warnings: Vec<String>,
461    /// Semantic pass duration as reported by the sidecar.
462    pub elapsed_ms: u64,
463    /// Bounded semantic phase timings reported by the sidecar.
464    pub phase_timings_ms: TypeAwarePhaseTimings,
465}
466
467/// The call evidence that the `constant-parameter` rule asked the companion
468/// for.
469#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
470#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
471pub struct TypeAwareCallEvidenceMeta {
472    /// Parameters with a default whose arguments the companion typed.
473    pub default_candidates: usize,
474    /// Methods of exported classes whose calls the companion read.
475    pub method_candidates: usize,
476    /// Findings that the evidence proved.
477    pub findings: usize,
478    /// The count of each reason that a candidate got no evidence, such as
479    /// `outside-program` or `decorator`. An open set: a later version can
480    /// add a reason.
481    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
482    pub abstention_reasons: std::collections::BTreeMap<String, usize>,
483    /// Duration of the request as reported by the companion.
484    pub elapsed_ms: u64,
485}
486
487/// Closed set of reasons for retaining a candidate without semantic scanning.
488#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
489#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
490#[serde(rename_all = "kebab-case")]
491pub enum TypeAwareAbstentionReason {
492    /// No selected TypeScript project contains the candidate file.
493    #[default]
494    NoProject,
495    /// Multiple explicit TypeScript projects contain the candidate file.
496    AmbiguousProject,
497    /// Structural TypeScript diagnostics make exact matching unsafe.
498    BlockingDiagnostics,
499}
500
501/// Closed abstention reason counts for stable machine consumption.
502#[derive(Debug, Clone, Default, Deserialize, Serialize)]
503#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
504pub struct TypeAwareAbstentionCounts {
505    /// Candidates not contained by a selected TypeScript project.
506    pub no_project: usize,
507    /// Candidates contained by more than one explicit TypeScript project.
508    pub ambiguous_project: usize,
509    /// Candidates retained because structural diagnostics block scanning.
510    pub blocking_diagnostics: usize,
511    /// Candidates retained because the raw TypeScript-Go host cannot expose
512    /// named exports from Svelte virtual modules.
513    pub svelte_virtual_module_exports: usize,
514    /// Candidates whose exact declaration identity could not be resolved.
515    pub unknown_symbol: usize,
516    /// Candidates using declaration syntax unsupported by the semantic backend.
517    pub unsupported_syntax: usize,
518    /// Candidates retained because the bounded semantic request reached capacity.
519    pub capacity: usize,
520}
521
522/// How a TypeScript project was selected for semantic refinement.
523#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
524#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
525#[serde(rename_all = "kebab-case")]
526pub enum TypeAwareProjectSource {
527    /// Fallow selected the nearest discovered project automatically.
528    #[default]
529    Auto,
530    /// The project was supplied with `--type-aware-project`.
531    Explicit,
532}
533
534/// Outcome of semantic refinement for one TypeScript project.
535#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
536#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
537#[serde(rename_all = "kebab-case")]
538pub enum TypeAwareProjectStatus {
539    /// The project was structurally safe and its candidates were scanned.
540    #[default]
541    Refined,
542    /// Structural diagnostics prevented candidate scanning.
543    Abstained,
544    /// All semantic queries assigned to this Program completed.
545    Complete,
546    /// The Program could not answer its assigned semantic queries safely.
547    Unavailable,
548}
549
550/// How a persistent semantic snapshot was refreshed.
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
552#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
553#[serde(rename_all = "kebab-case")]
554pub enum TypeAwareInvalidationKind {
555    /// The backend rebuilt project state from a clean snapshot.
556    Full,
557    /// The backend applied an explicit source-file change set.
558    Incremental,
559    /// No filesystem change was reported between compatible requests.
560    None,
561}
562
563/// Semantic sidecar timings, separated from Fallow's syntactic pipeline.
564#[derive(Debug, Clone, Default, Deserialize, Serialize)]
565#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
566pub struct TypeAwarePhaseTimings {
567    /// TypeScript API construction and project snapshot selection.
568    pub project_setup: u64,
569    /// TypeScript diagnostics collected before any candidate refinement.
570    pub diagnostics: u64,
571    /// Batched symbol lookup and exact declaration matching.
572    pub symbol_scan: u64,
573}
574
575/// Bounded provenance for one TypeScript project handled by the sidecar.
576#[derive(Debug, Clone, Default, Deserialize, Serialize)]
577#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
578pub struct TypeAwareProjectMeta {
579    /// Project config relative to the analysis root, or `<inferred>`.
580    pub config: String,
581    /// How the project was selected: `auto` or `explicit`.
582    pub source: TypeAwareProjectSource,
583    /// Project result: `refined`, `abstained`, `complete`, or `unavailable`.
584    pub status: TypeAwareProjectStatus,
585    /// Candidates assigned to this project.
586    pub candidate_count: usize,
587    /// Candidates confirmed as used and removed.
588    pub confirmed_used_count: usize,
589    /// Candidates retained because they implement or override a contract.
590    pub contract_preserved_count: usize,
591    /// Candidates with complete no-static-reference evidence.
592    pub no_static_references_count: usize,
593    /// Candidates eligible for a guarded class-member fix.
594    pub fix_eligible_count: usize,
595    /// Candidates whose exact semantic outcome remained unresolved.
596    pub unresolved_count: usize,
597    /// Candidates retained without scanning because the project was unsafe.
598    pub abstained_count: usize,
599    /// Config, program, syntactic, and bind diagnostics that block scanning.
600    pub blocking_diagnostic_count: usize,
601    /// Source files loaded into this TypeScript program.
602    pub source_file_count: usize,
603    /// Whether this Program served more than one semantic query in the batch.
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub program_reused: Option<bool>,
606    /// Whether this Program served more than one query in the current batch.
607    #[serde(default, skip_serializing_if = "Option::is_none")]
608    pub program_shared_across_queries: Option<bool>,
609    /// Whether the root-bound semantic session reused the prior snapshot.
610    #[serde(default, skip_serializing_if = "Option::is_none")]
611    pub program_reused_from_previous_snapshot: Option<bool>,
612    /// Monotonic revision within the root-bound semantic session.
613    #[serde(default, skip_serializing_if = "Option::is_none")]
614    pub snapshot_revision: Option<u64>,
615    /// Full, incremental, or no invalidation before this query.
616    #[serde(default, skip_serializing_if = "Option::is_none")]
617    pub invalidation_kind: Option<TypeAwareInvalidationKind>,
618    /// Stable project-level gap reason.
619    #[serde(default, skip_serializing_if = "Option::is_none")]
620    pub reason_code: Option<SemanticGapReason>,
621    /// Stable reason code when `status` is `abstained`.
622    #[serde(default, skip_serializing_if = "Option::is_none")]
623    #[cfg_attr(feature = "schema", schemars(with = "TypeAwareAbstentionReason"))]
624    pub abstain_reason: Option<TypeAwareAbstentionReason>,
625}
626
627/// Privacy-safe local run metadata emitted for JSON consumers.
628#[derive(Debug, Clone, Default, Serialize)]
629#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
630pub struct TelemetryMeta {
631    /// Ephemeral local token that may be passed to the hidden `--parent-run`
632    /// flag on a later command. It is not derived from repository, path, user,
633    /// machine, project, or cloud data.
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub analysis_run_id: Option<String>,
636}
637
638/// Single-metric definition inside [`Meta::metrics`].
639#[derive(Debug, Clone, Default, Serialize)]
640#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
641pub struct MetaMetric {
642    /// Human-readable metric name.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub name: Option<String>,
645    /// What this metric measures and how it is computed.
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub description: Option<String>,
648    /// Valid value range (e.g., `"[0, 100]"`).
649    #[serde(default, skip_serializing_if = "Option::is_none")]
650    pub range: Option<String>,
651    /// How to read the value (e.g., `"lower is better"`).
652    #[serde(default, skip_serializing_if = "Option::is_none")]
653    pub interpretation: Option<String>,
654}
655
656/// Single-rule definition inside [`Meta::rules`].
657#[derive(Debug, Clone, Default, Serialize)]
658#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
659pub struct MetaRule {
660    /// Human-readable rule name.
661    #[serde(default, skip_serializing_if = "Option::is_none")]
662    pub name: Option<String>,
663    /// What this rule detects.
664    #[serde(default, skip_serializing_if = "Option::is_none")]
665    pub description: Option<String>,
666    /// URL to the rule documentation.
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub docs: Option<String>,
669}