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