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