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