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