Skip to main content

ftui_runtime/
telemetry_schema.rs

1#![forbid(unsafe_code)]
2
3//! Canonical telemetry schema for the FrankenTUI runtime (bd-17ar5).
4//!
5//! Defines the unified vocabulary of tracing targets, event names, metric
6//! names, and structured field contracts used across the runtime, effect
7//! system, subscription manager, and harness infrastructure.
8//!
9//! # Purpose
10//!
11//! Without a shared schema, telemetry becomes fragmented across modules.
12//! This module provides:
13//! - Named constants for tracing targets (e.g., `TARGET_RUNTIME`)
14//! - Canonical event names for structured log correlation
15//! - Metric name constants for counter/gauge telemetry
16//! - A schema manifest for validation and documentation
17//!
18//! # Usage
19//!
20//! ```ignore
21//! use ftui_runtime::telemetry_schema::{TARGET_RUNTIME, event};
22//!
23//! tracing::info!(
24//!     target: TARGET_RUNTIME,
25//!     event = event::RUNTIME_STARTUP,
26//!     "runtime started"
27//! );
28//! ```
29
30// ============================================================================
31// Tracing targets
32// ============================================================================
33
34/// Runtime lifecycle events (startup, shutdown, lane resolution).
35pub const TARGET_RUNTIME: &str = "ftui.runtime";
36
37/// Terminal log emission policy and byte counts.
38pub const TARGET_RUNTIME_LOG: &str = "ftui.runtime.log";
39
40/// Effect/command execution and queue telemetry.
41pub const TARGET_EFFECT: &str = "ftui.effect";
42
43/// Process subscription lifecycle (spawn, exit, restart).
44pub const TARGET_PROCESS: &str = "ftui.process";
45
46/// Resize coalescer decisions.
47pub const TARGET_RESIZE: &str = "ftui.decision.resize";
48
49/// Value-of-information sampling decisions.
50pub const TARGET_VOI: &str = "ftui.voi";
51
52/// Bayesian online change-point detection.
53pub const TARGET_BOCPD: &str = "ftui.bocpd";
54
55/// E-process throttle decisions.
56pub const TARGET_EPROCESS: &str = "ftui.eprocess";
57
58/// Frame guardrails (memory / effect-queue budgets): soft trims, emergency
59/// frame drops.
60pub const TARGET_GUARDRAILS: &str = "ftui.guardrails";
61
62/// Accessibility: per-frame tree diffs and screen-reader announcements
63/// (emitted only when `ProgramConfig::accessibility` is set).
64pub const TARGET_A11Y: &str = "ftui.a11y";
65
66/// Grapheme width cache operations and misses.
67pub const TARGET_WIDTH_CACHE: &str = "ftui.text.width_cache";
68
69/// Runtime locale and text direction changes.
70pub const TARGET_LOCALE: &str = "ftui.runtime.locale";
71
72// ============================================================================
73// Span names
74// ============================================================================
75
76/// Names of the tracing spans the runtime opens (see
77/// `docs/spec/telemetry-events.md`, sections 3.1 and 3.2). Every
78/// `info_span!` / `debug_span!` site uses these constants; the
79/// `no_stray_target_literals` test keeps it that way.
80pub mod span {
81    /// Model initialization (`Model::init`).
82    pub const PROGRAM_INIT: &str = "ftui.program.init";
83    /// One update cycle (`Model::update`, gesture and accessibility hooks).
84    pub const PROGRAM_UPDATE: &str = "ftui.program.update";
85    /// View rendering (`Model::view`).
86    pub const PROGRAM_VIEW: &str = "ftui.program.view";
87    /// Subscription reconciliation.
88    pub const PROGRAM_SUBSCRIPTIONS: &str = "ftui.program.subscriptions";
89    /// Program shutdown (`Model::on_shutdown`).
90    pub const PROGRAM_SHUTDOWN: &str = "ftui.program.shutdown";
91    /// Error handling (`Model::on_error`).
92    pub const PROGRAM_ERROR: &str = "ftui.program.error";
93
94    /// Complete frame cycle.
95    pub const RENDER_FRAME: &str = "ftui.render.frame";
96    /// Buffer diff computation (strategy selection).
97    pub const RENDER_DIFF: &str = "ftui.render.diff";
98    /// Diff computation inside a present.
99    pub const RENDER_DIFF_COMPUTE: &str = "ftui.render.diff_compute";
100    /// ANSI emission of a frame.
101    pub const RENDER_PRESENT: &str = "ftui.render.present";
102    /// Emission of the diff runs.
103    pub const RENDER_EMIT: &str = "ftui.render.emit";
104    /// Output flush.
105    pub const RENDER_FLUSH: &str = "ftui.render.flush";
106    /// Inline-mode scroll region activation.
107    pub const RENDER_SCROLL_REGION: &str = "ftui.render.scroll_region";
108
109    /// Input event processing.
110    pub const INPUT_EVENT: &str = "ftui.input.event";
111    /// Macro playback.
112    pub const INPUT_MACRO: &str = "ftui.input.macro";
113}
114
115/// Point-in-time decision event names (section 3.3 of the spec).
116pub mod decision {
117    /// Degradation level change.
118    pub const DEGRADATION: &str = "ftui.decision.degradation";
119    /// Capability fallback.
120    pub const FALLBACK: &str = "ftui.decision.fallback";
121    /// Resize handling decision (same string as [`super::TARGET_RESIZE`]).
122    pub const RESIZE: &str = "ftui.decision.resize";
123    /// Screen mode selection.
124    pub const SCREEN_MODE: &str = "ftui.decision.screen_mode";
125}
126
127// ============================================================================
128// Canonical event names
129// ============================================================================
130
131/// Structured event names emitted by the runtime.
132///
133/// These are the `event` field values in structured logs. Using constants
134/// ensures CI can verify event coverage and dashboards can filter reliably.
135pub mod event {
136    /// Program startup with lane and rollout policy.
137    pub const RUNTIME_STARTUP: &str = "runtime.startup";
138
139    /// Effect queue shutdown completed (fast or slow path).
140    pub const EFFECT_QUEUE_SHUTDOWN: &str = "effect_queue.shutdown";
141
142    /// Spawn executor shutdown completed.
143    pub const SPAWN_EXECUTOR_SHUTDOWN: &str = "spawn_executor.shutdown";
144
145    /// Subscription manager stop_all completed.
146    pub const SUBSCRIPTION_STOP_ALL: &str = "subscription.stop_all";
147
148    /// Individual subscription stopped.
149    pub const SUBSCRIPTION_STOP: &str = "subscription.stop";
150
151    /// Command effect started/completed.
152    pub const EFFECT_COMMAND: &str = "effect.command";
153
154    /// Subscription effect started/stopped.
155    pub const EFFECT_SUBSCRIPTION: &str = "effect.subscription";
156
157    /// Effect queue task dropped (backpressure or post-shutdown).
158    pub const QUEUE_DROP: &str = "effect_queue.drop";
159
160    /// Effect timeout exceeded deadline.
161    pub const EFFECT_TIMEOUT: &str = "effect.timeout";
162
163    /// Effect panicked during execution.
164    pub const EFFECT_PANIC: &str = "effect.panic";
165}
166
167// ============================================================================
168// Canonical evidence event names
169// ============================================================================
170
171/// Structured evidence events emitted through the evidence sink.
172pub mod evidence {
173    /// Screen reader announcement.
174    pub const A11Y_ANNOUNCEMENT: &str = "a11y_announcement";
175    /// Accessibility tree snapshot/diff.
176    pub const A11Y_TREE: &str = "a11y_tree";
177    /// Bayesian online changepoint detection.
178    pub const BOCPD: &str = "bocpd";
179    /// Frame budget PID controller decision.
180    pub const BUDGET_DECISION: &str = "budget_decision";
181    /// Terminal capability query decision.
182    pub const CAPABILITY_DECISION: &str = "capability_decision";
183    /// Degradation certificate decision.
184    pub const CERTIFICATE_DECISION: &str = "certificate_decision";
185    /// Resize coalescer configuration.
186    pub const CONFIG: &str = "config";
187    /// Event loop cycle time percentiles.
188    pub const CYCLE_TIME_PERCENTILES: &str = "cycle_time_percentiles";
189    /// Resize coalescer decision.
190    pub const DECISION: &str = "decision";
191    /// Detailed Bayesian decision evidence.
192    pub const DECISION_EVIDENCE: &str = "decision_evidence";
193    /// Diff strategy selection decision.
194    pub const DIFF_DECISION: &str = "diff_decision";
195    /// Diff regime change transition.
196    pub const DIFF_REGIME_TRANSITION: &str = "diff_regime_transition";
197    /// Scheduler effect queue selection.
198    pub const EFFECT_QUEUE_SELECT: &str = "effect_queue_select";
199    /// Scheduler fairness configuration.
200    pub const FAIRNESS_CONFIG: &str = "fairness_config";
201    /// Scheduler fairness dispatch decision.
202    pub const FAIRNESS_DECISION: &str = "fairness_decision";
203    /// Frame guardrails state snapshot.
204    pub const GUARDRAIL_SNAPSHOT: &str = "guardrail_snapshot";
205    /// Inline render strategy selection.
206    pub const INLINE_STRATEGY: &str = "inline_strategy";
207    /// Inline strategy fallback event.
208    pub const INLINE_STRATEGY_FALLBACK: &str = "inline_strategy_fallback";
209    /// Regime transition in coalescer.
210    pub const REGIME_TRANSITION: &str = "regime_transition";
211    /// Session lifecycle summary.
212    pub const SUMMARY: &str = "summary";
213    /// Task executor backend configuration.
214    pub const TASK_EXECUTOR_BACKEND: &str = "task_executor_backend";
215    /// Task executor backpressure event.
216    pub const TASK_EXECUTOR_BACKPRESSURE: &str = "task_executor_backpressure";
217    /// Task executor task completion.
218    pub const TASK_EXECUTOR_COMPLETE: &str = "task_executor_complete";
219    /// Task executor panic report.
220    pub const TASK_EXECUTOR_PANIC: &str = "task_executor_panic";
221    /// Value of information sampling decision.
222    pub const VOI_DECISION: &str = "voi_decision";
223    /// Value of information observation.
224    pub const VOI_OBSERVE: &str = "voi_observe";
225    /// Widget tree refresh notification.
226    pub const WIDGET_REFRESH: &str = "widget_refresh";
227    /// Grapheme width cache statistics.
228    pub const WIDTH_CACHE_STATS: &str = "width_cache_stats";
229}
230
231// ============================================================================
232// Metric names
233// ============================================================================
234
235/// Monotonic counter and gauge metric names.
236///
237/// These correspond to the `AtomicU64` counters in `effect_system.rs` and
238/// are the canonical names for dashboards and CI gates.
239pub mod metric {
240    /// Total command effects executed.
241    pub const EFFECTS_COMMAND_TOTAL: &str = "effects_command_total";
242
243    /// Total subscription effects started.
244    pub const EFFECTS_SUBSCRIPTION_TOTAL: &str = "effects_subscription_total";
245
246    /// Total effects executed (command + subscription).
247    pub const EFFECTS_EXECUTED_TOTAL: &str = "effects_executed_total";
248
249    /// Total tasks enqueued to the effect queue.
250    pub const EFFECTS_QUEUE_ENQUEUED: &str = "effects_queue_enqueued";
251
252    /// Total tasks processed by the effect queue.
253    pub const EFFECTS_QUEUE_PROCESSED: &str = "effects_queue_processed";
254
255    /// Total tasks dropped (backpressure or shutdown).
256    pub const EFFECTS_QUEUE_DROPPED: &str = "effects_queue_dropped";
257
258    /// Maximum queue depth observed (ratchet-only).
259    pub const EFFECTS_QUEUE_HIGH_WATER: &str = "effects_queue_high_water";
260
261    /// Current in-flight tasks (enqueued - processed - dropped).
262    pub const EFFECTS_QUEUE_IN_FLIGHT: &str = "effects_queue_in_flight";
263}
264
265// ============================================================================
266// Structured field contracts
267// ============================================================================
268
269/// Common structured field names used in tracing spans and events.
270///
271/// Using named constants prevents typos and enables grep-based schema auditing.
272pub mod field {
273    /// Elapsed time in microseconds.
274    pub const ELAPSED_US: &str = "elapsed_us";
275
276    /// Duration in microseconds (for effect timing).
277    pub const DURATION_US: &str = "duration_us";
278
279    /// Subscription or task identifier.
280    pub const SUB_ID: &str = "sub_id";
281
282    /// Command type label.
283    pub const COMMAND_TYPE: &str = "command_type";
284
285    /// Requested runtime lane (before resolution).
286    pub const REQUESTED_LANE: &str = "requested_lane";
287
288    /// Resolved runtime lane (after fallback).
289    pub const RESOLVED_LANE: &str = "resolved_lane";
290
291    /// Rollout policy label.
292    pub const ROLLOUT_POLICY: &str = "rollout_policy";
293
294    /// Timeout in milliseconds.
295    pub const TIMEOUT_MS: &str = "timeout_ms";
296
297    /// Number of pending handles at shutdown.
298    pub const PENDING_HANDLES: &str = "pending_handles";
299
300    /// Drop reason (backpressure, post_shutdown, etc.).
301    pub const REASON: &str = "reason";
302}
303
304// ============================================================================
305// Schema manifest
306// ============================================================================
307
308/// Schema version for forward compatibility.
309pub const SCHEMA_VERSION: &str = "1.0.0";
310
311/// Complete list of registered tracing targets.
312pub const ALL_TARGETS: &[&str] = &[
313    TARGET_RUNTIME,
314    TARGET_RUNTIME_LOG,
315    TARGET_EFFECT,
316    TARGET_PROCESS,
317    TARGET_RESIZE,
318    TARGET_VOI,
319    TARGET_BOCPD,
320    TARGET_EPROCESS,
321    TARGET_GUARDRAILS,
322    TARGET_A11Y,
323    TARGET_WIDTH_CACHE,
324    TARGET_LOCALE,
325];
326
327/// Complete list of registered span names.
328pub const ALL_SPANS: &[&str] = &[
329    span::PROGRAM_INIT,
330    span::PROGRAM_UPDATE,
331    span::PROGRAM_VIEW,
332    span::PROGRAM_SUBSCRIPTIONS,
333    span::PROGRAM_SHUTDOWN,
334    span::PROGRAM_ERROR,
335    span::RENDER_FRAME,
336    span::RENDER_DIFF,
337    span::RENDER_DIFF_COMPUTE,
338    span::RENDER_PRESENT,
339    span::RENDER_EMIT,
340    span::RENDER_FLUSH,
341    span::RENDER_SCROLL_REGION,
342    span::INPUT_EVENT,
343    span::INPUT_MACRO,
344];
345
346/// Complete list of registered decision event names.
347pub const ALL_DECISIONS: &[&str] = &[
348    decision::DEGRADATION,
349    decision::FALLBACK,
350    decision::RESIZE,
351    decision::SCREEN_MODE,
352];
353
354/// Complete list of registered event names.
355pub const ALL_EVENTS: &[&str] = &[
356    event::RUNTIME_STARTUP,
357    event::EFFECT_QUEUE_SHUTDOWN,
358    event::SPAWN_EXECUTOR_SHUTDOWN,
359    event::SUBSCRIPTION_STOP_ALL,
360    event::SUBSCRIPTION_STOP,
361    event::EFFECT_COMMAND,
362    event::EFFECT_SUBSCRIPTION,
363    event::QUEUE_DROP,
364    event::EFFECT_TIMEOUT,
365    event::EFFECT_PANIC,
366];
367
368/// Complete list of registered metric names.
369pub const ALL_METRICS: &[&str] = &[
370    metric::EFFECTS_COMMAND_TOTAL,
371    metric::EFFECTS_SUBSCRIPTION_TOTAL,
372    metric::EFFECTS_EXECUTED_TOTAL,
373    metric::EFFECTS_QUEUE_ENQUEUED,
374    metric::EFFECTS_QUEUE_PROCESSED,
375    metric::EFFECTS_QUEUE_DROPPED,
376    metric::EFFECTS_QUEUE_HIGH_WATER,
377    metric::EFFECTS_QUEUE_IN_FLIGHT,
378];
379
380/// Complete list of registered evidence event names.
381pub const ALL_EVIDENCE_EVENTS: &[&str] = &[
382    evidence::A11Y_ANNOUNCEMENT,
383    evidence::A11Y_TREE,
384    evidence::BOCPD,
385    evidence::BUDGET_DECISION,
386    evidence::CAPABILITY_DECISION,
387    evidence::CERTIFICATE_DECISION,
388    evidence::CONFIG,
389    evidence::CYCLE_TIME_PERCENTILES,
390    evidence::DECISION,
391    evidence::DECISION_EVIDENCE,
392    evidence::DIFF_DECISION,
393    evidence::DIFF_REGIME_TRANSITION,
394    evidence::EFFECT_QUEUE_SELECT,
395    evidence::FAIRNESS_CONFIG,
396    evidence::FAIRNESS_DECISION,
397    evidence::GUARDRAIL_SNAPSHOT,
398    evidence::INLINE_STRATEGY,
399    evidence::INLINE_STRATEGY_FALLBACK,
400    evidence::REGIME_TRANSITION,
401    evidence::SUMMARY,
402    evidence::TASK_EXECUTOR_BACKEND,
403    evidence::TASK_EXECUTOR_BACKPRESSURE,
404    evidence::TASK_EXECUTOR_COMPLETE,
405    evidence::TASK_EXECUTOR_PANIC,
406    evidence::VOI_DECISION,
407    evidence::VOI_OBSERVE,
408    evidence::WIDGET_REFRESH,
409    evidence::WIDTH_CACHE_STATS,
410];
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn schema_version_is_semver() {
418        let parts: Vec<&str> = SCHEMA_VERSION.split('.').collect();
419        assert_eq!(parts.len(), 3, "schema version must be semver");
420        for part in &parts {
421            assert!(
422                part.parse::<u32>().is_ok(),
423                "each semver component must be a number: {part}"
424            );
425        }
426    }
427
428    #[test]
429    fn all_targets_are_dotted() {
430        for target in ALL_TARGETS {
431            assert!(
432                target.contains('.'),
433                "target should be dotted namespace: {target}"
434            );
435            assert!(
436                target.starts_with("ftui."),
437                "target should start with ftui.: {target}"
438            );
439        }
440    }
441
442    #[test]
443    fn all_events_have_dotted_names() {
444        for event in ALL_EVENTS {
445            assert!(event.contains('.'), "event name should be dotted: {event}");
446        }
447    }
448
449    #[test]
450    fn all_metrics_are_snake_case() {
451        for metric in ALL_METRICS {
452            assert!(
453                metric.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
454                "metric name should be snake_case: {metric}"
455            );
456        }
457    }
458
459    #[test]
460    fn no_duplicate_targets() {
461        let mut seen = std::collections::HashSet::new();
462        for target in ALL_TARGETS {
463            assert!(seen.insert(target), "duplicate target: {target}");
464        }
465    }
466
467    #[test]
468    fn no_duplicate_events() {
469        let mut seen = std::collections::HashSet::new();
470        for event in ALL_EVENTS {
471            assert!(seen.insert(event), "duplicate event: {event}");
472        }
473    }
474
475    #[test]
476    fn no_duplicate_metrics() {
477        let mut seen = std::collections::HashSet::new();
478        for metric in ALL_METRICS {
479            assert!(seen.insert(metric), "duplicate metric: {metric}");
480        }
481    }
482
483    #[test]
484    fn all_spans_are_dotted_and_unique() {
485        let mut seen = std::collections::HashSet::new();
486        for span in ALL_SPANS {
487            assert!(
488                span.starts_with("ftui."),
489                "span should start with ftui.: {span}"
490            );
491            assert!(seen.insert(span), "duplicate span: {span}");
492        }
493        for decision in ALL_DECISIONS {
494            assert!(
495                decision.starts_with("ftui.decision."),
496                "decision event should start with ftui.decision.: {decision}"
497            );
498        }
499    }
500
501    /// Every tracing target and span name in the runtime, core, render and
502    /// showcase crates must come from this module (or, for the showcase's
503    /// own targets, from its constants block), never from a string literal
504    /// at the call site: a typo would otherwise create a target that no
505    /// subscriber filters on and nothing would notice.
506    ///
507    /// Scans the sources at test time. A literal is any `"ftui.` followed by
508    /// a name character outside a comment; the prefix check `"ftui."` (quote
509    /// right after the dot) is allowed. `const NAME: &str = "ftui...."`
510    /// definitions are allowed in this file and in the showcase's
511    /// `crates/ftui-demo-showcase/src/app.rs`. Files listed in
512    /// `docs/telemetry-target-literal-allowlist.txt` (one path per line,
513    /// relative to the workspace root) are skipped; that list may only
514    /// shrink.
515    #[test]
516    fn no_stray_target_literals() {
517        use std::path::{Path, PathBuf};
518
519        let root = Path::new(env!("CARGO_MANIFEST_DIR"))
520            .join("../..")
521            .canonicalize()
522            .expect("workspace root");
523        let allowlist_path = root.join("docs/telemetry-target-literal-allowlist.txt");
524        let allowlist: Vec<PathBuf> = std::fs::read_to_string(&allowlist_path)
525            .map(|text| {
526                text.lines()
527                    .map(str::trim)
528                    .filter(|line| !line.is_empty() && !line.starts_with('#'))
529                    .map(|line| root.join(line))
530                    .collect()
531            })
532            .unwrap_or_default();
533        let this_file = root.join("crates/ftui-runtime/src/telemetry_schema.rs");
534        let showcase_app = root.join("crates/ftui-demo-showcase/src/app.rs");
535        let core_lib = root.join("crates/ftui-core/src/lib.rs");
536
537        fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
538            let Ok(entries) = std::fs::read_dir(dir) else {
539                return;
540            };
541            for entry in entries.flatten() {
542                let path = entry.path();
543                if path.is_dir() {
544                    collect(&path, out);
545                } else if path.extension().is_some_and(|ext| ext == "rs") {
546                    out.push(path);
547                }
548            }
549        }
550
551        let mut files = Vec::new();
552        for dir in [
553            "crates/ftui-runtime/src",
554            "crates/ftui-runtime/tests",
555            "crates/ftui-core/src",
556            "crates/ftui-render/src",
557            "crates/ftui-demo-showcase/src",
558        ] {
559            collect(&root.join(dir), &mut files);
560        }
561        assert!(
562            files.len() > 50,
563            "source scan found too few files: {}",
564            files.len()
565        );
566
567        // A stray literal is a *complete* schema-style name string:
568        // `"ftui.<dotted.name>"` where the run of name characters is closed
569        // immediately by the quote. This flags `"ftui.bocpd"` and
570        // `info_span!("ftui.program.init")` but not a human message that
571        // merely starts with a name, like `"ftui.program.init should exist"`
572        // (a space follows the name), which is not a schema reference.
573        let is_literal = |line: &str| -> bool {
574            let trimmed = line.trim_start();
575            if trimmed.starts_with("//") {
576                return false;
577            }
578            let mut rest = trimmed;
579            while let Some(idx) = rest.find("\"ftui.") {
580                let after = &rest[idx + "\"".len()..];
581                let name_len = after
582                    .bytes()
583                    .take_while(|b| {
584                        b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'.' || *b == b'_'
585                    })
586                    .count();
587                if after.as_bytes().get(name_len) == Some(&b'"') {
588                    return true;
589                }
590                rest = &after[name_len..];
591            }
592            false
593        };
594        let is_definition = |line: &str| -> bool {
595            let trimmed = line.trim_start();
596            // `pub(crate)` counts too: a target shared with one of the
597            // showcase's screen modules has to be visible to it, and scoping
598            // it to the crate is the narrower choice than making it `pub`
599            // purely to match this check.
600            (trimmed.starts_with("pub const ")
601                || trimmed.starts_with("pub(crate) const ")
602                || trimmed.starts_with("const "))
603                && trimmed.contains(": &str = \"ftui.")
604        };
605
606        let mut offenders = Vec::new();
607        for file in files {
608            if file == this_file || allowlist.contains(&file) {
609                continue;
610            }
611            let Ok(text) = std::fs::read_to_string(&file) else {
612                continue;
613            };
614            for (idx, line) in text.lines().enumerate() {
615                if !is_literal(line) {
616                    continue;
617                }
618                if (file == showcase_app || file == core_lib) && is_definition(line) {
619                    continue;
620                }
621                offenders.push(format!(
622                    "{}:{}: {}",
623                    file.strip_prefix(&root).unwrap_or(&file).display(),
624                    idx + 1,
625                    line.trim()
626                ));
627            }
628        }
629        assert!(
630            offenders.is_empty(),
631            "tracing targets and span names must use telemetry_schema constants:\n{}",
632            offenders.join("\n")
633        );
634    }
635
636    #[test]
637    fn core_width_cache_target_matches_schema() {
638        assert_eq!(
639            TARGET_WIDTH_CACHE,
640            ftui_core::text_width::TARGET_WIDTH_CACHE
641        );
642    }
643
644    #[test]
645    fn all_targets_include_guardrails_and_a11y() {
646        assert!(ALL_TARGETS.contains(&TARGET_GUARDRAILS));
647        assert!(ALL_TARGETS.contains(&TARGET_A11Y));
648    }
649
650    #[test]
651    fn all_targets_unique_and_prefixed() {
652        let mut seen = std::collections::HashSet::new();
653        for target in ALL_TARGETS {
654            assert!(
655                target.starts_with("ftui."),
656                "target must start with ftui.: {target}"
657            );
658            assert!(seen.insert(target), "duplicate target: {target}");
659        }
660    }
661
662    #[test]
663    fn all_evidence_events_unique_and_snake_case() {
664        let mut seen = std::collections::HashSet::new();
665        for event in ALL_EVIDENCE_EVENTS {
666            assert!(
667                event
668                    .chars()
669                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
670                "evidence event must be snake_case: {event}"
671            );
672            assert!(seen.insert(event), "duplicate evidence event: {event}");
673        }
674    }
675
676    #[test]
677    fn schema_events_match_constants() {
678        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
679            .join("../..")
680            .canonicalize()
681            .expect("workspace root");
682        let schema_path = root.join("tests/e2e/lib/e2e_evidence_schema.json");
683        let text = std::fs::read_to_string(&schema_path).expect("e2e_evidence_schema.json");
684        let json: serde_json::Value = serde_json::from_str(&text).expect("valid json");
685        let events_obj = json
686            .get("events")
687            .and_then(|v| v.as_object())
688            .expect("events object");
689        let schema_keys: std::collections::BTreeSet<&str> =
690            events_obj.keys().map(String::as_str).collect();
691        let const_keys: std::collections::BTreeSet<&str> =
692            ALL_EVIDENCE_EVENTS.iter().copied().collect();
693        assert_eq!(
694            schema_keys, const_keys,
695            "evidence schema events must match ALL_EVIDENCE_EVENTS"
696        );
697    }
698}