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