facett-core 0.1.19

facett — visual kernel: render a node/edge Scene into egui (wgpu fast path to come)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! **The DEV-ID badge** — every pane says who it is, in non-release builds only.
//!
//! Rickard's ask, verbatim: *"show an uniqe ID on each pane/component in non release
//! mode … make it easy to copy this one to claude and explain where i am"*.
//!
//! # Why this is the errcode scheme's other half
//!
//! [`crate::errcode`] already answers *"what went wrong"* with a stable
//! `facet-<component>-<n>`, and its [`REGISTRY`](crate::errcode::REGISTRY) maps a
//! component to the crate dir, the source file and a Codeberg URL. This module answers
//! the sibling question — ***"where am I"*** — with the same vocabulary, so a badge
//! pasted into a chat resolves to a crate and a file with no guessing on either side.
//! It is not an error; a pane showing its dev-id is perfectly healthy.
//!
//! # The trap this is built to avoid
//!
//! `facett-core/tests/errcode_raise_sites.rs` found that `facet_err!` **fabricates** its
//! code with `concat!` and never asks the registry whether it exists, so
//! `facet_err!(map, 99, …)` compiles and yields an authoritative-looking `facet-map-99`
//! that `lookup` cannot resolve. A dev-id badge has exactly that hole: an id that *looks*
//! canonical but names nothing wastes the time of whoever pastes it AND whoever reads it.
//!
//! So the badge is honest about its own confidence, and the two cases are rendered so
//! they cannot be mistaken for each other:
//!
//! * **registered** — `facet-geomap` in the registry's own colour. [`resolve`] hands back
//!   the crate dir + source file, so the id is actionable on arrival.
//! * **unregistered** — `⟨unregistered⟩ Some Title`, dimmed and bracketed. It still
//!   identifies the pane (better than nothing when you are staring at a bug), while
//!   saying plainly that it will not resolve to a file. Every one of these is a pane
//!   waiting to declare [`Facet::component`](crate::Facet::component) — the badge
//!   doubles as the to-do list.
//!
//! Two failures that render identically make a bug immortal (the ⚒ Build Thing
//! post-mortem, quoted in `errcode_raise_sites.rs`). The same reasoning applies to two
//! *confidences* that render identically.
//!
//! # When it shows
//!
//! ON in debug builds. In a RELEASE build it is off by default but can be switched on
//! with **`FACETT_DEVID=1`** — because the binaries people actually run on this fleet
//! are release builds. Gating on `debug_assertions` ALONE made the whole feature
//! invisible to the person who asked for it: every pane was wired, every test was
//! green, and the installed `korp-ui` painted nothing, because `badge` had compiled to
//! an empty function. A debug-only debugging aid is not a debugging aid. The function is
//! always *present* so no call site needs a `cfg`.

use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Ui};

/// The prefix every dev-id atom carries in the a11y tree, so a headless test can find
/// the chip among a pane's own atoms without matching on the id text itself.
pub const DEVID_ATOM: &str = "dev-id:";

/// The suffix the chip's atom carries when its pane is the one the pointer is in.
///
/// This is what makes FOCUS assertable rather than merely visible: a robot drive can ask
/// the AccessKit tree *which pane am I in* instead of inferring it from what it clicked
/// last. Rickard's ask — *"you could make it flash when in focus, that would be nice for
/// robot tests"* — with the flash made deterministic (see [`badge`]).
pub const FOCUSED_MARK: &str = "[focused]";

/// The marker a pane that has not declared a component renders instead of an id.
/// Deliberately not id-shaped — it can never be mistaken for a `facet-*` code.
pub const UNREGISTERED: &str = "⟨unregistered⟩";

/// **Normalise a raw dev-id to a registry component.**
///
/// The elm bridge macro fills [`Facet::component`](crate::Facet::component) with
/// `module_path!()`, which expands at the CALL site — so a pane in `facett-geomap`
/// reports `facett_geomap` (or `facett_geomap::inner`) with no per-pane code at all.
/// This maps that to the registry's vocabulary: take the crate segment, drop the
/// `facett_` prefix, and spell `_` as `-`. `facett_geomap::x` → `geomap`,
/// `facett_map3d` → `map3d`.
///
/// A hand-written `component()` returning a bare `"geomap"` passes through unchanged, so
/// both spellings are legal and neither needs to know about the other.
pub fn normalize(raw: &str) -> &str {
    let head = raw.split("::").next().unwrap_or(raw);
    head.strip_prefix("facett_").unwrap_or(head)
}

/// **Resolve a dev-id to its source** — `(crate_dir, src_file)` for a component that the
/// [`errcode`](crate::errcode) registry knows, `None` otherwise.
///
/// This is what makes a pasted badge actionable rather than decorative: the component
/// carried by every `facet-<component>-<n>` code is the same string the badge shows, so
/// one lookup turns *"I am here"* into a file to open. `None` is the honest answer for a
/// pane that has not registered — the badge renders [`UNREGISTERED`] in that case rather
/// than inventing a path.
pub fn resolve(component: &str) -> Option<(&'static str, &'static str)> {
    let want = normalize(component);
    crate::errcode::REGISTRY
        .iter()
        .find(|e| e.component == want)
        .map(|e| (e.crate_dir, e.src_file))
}

/// Is this component known to the [`errcode`](crate::errcode) registry?
pub fn is_registered(component: &str) -> bool {
    resolve(component).is_some()
}

/// **What the badge should say** for a pane — the pure decision, split out from any
/// painting so it is testable without a GPU (and so the release build's no-op cannot
/// silently diverge from what debug shows).
///
/// Returns `(text, registered)`. An empty `component` falls back to the pane title, and
/// so does a component the registry does not know: claiming an unregistered string is a
/// valid dev-id is exactly the `facet-map-99` failure.
pub fn badge_text(component: &str, title: &str) -> (String, bool) {
    if !component.is_empty() && is_registered(component) {
        let comp = normalize(component);
        // `component/pane` — the component alone is not enough to locate a human. korp
        // draws every one of its panes from ONE `SceneHost::slot` dispatch, so a chip
        // reading just "korp" would be identical on all of them, which is no better
        // than no chip. With the slot it reads `korp/ingest_load`, and for a facett
        // deck it reads `map3d/OSM 3D` — a crate to open AND the pane inside it.
        let t = title.trim();
        if t.is_empty() { (comp.to_string(), true) } else { (format!("{comp}/{t}"), true) }
    } else {
        let what = if component.is_empty() { title } else { normalize(component) };
        (format!("{UNREGISTERED} {what}"), false)
    }
}

/// **The chip's colours** — `(foreground, background plate)`, split out so the OPACITY of
/// the plate is assertable without a GPU.
///
/// The plate must be **fully opaque**, and that is not a style preference. The chip is
/// painted over the top-right corner of a pane that has already drawn there, so a
/// translucent plate does not put the id *on* the pane, it superimposes two strings in the
/// same pixels. Measured on a real release window (facett-demo, `FACETT_DEVID=1`): the
/// chip `⟨unregistered⟩ Velo L1` landed on the pane's own header
/// `L0 + L1 — vello off (feature off / no GPU)` and both became hard to read through each
/// other, with the old `from_black_alpha(120)` plate letting the text underneath bleed
/// straight through. An id you have to decode is an id you do not paste.
///
/// Registered ids read as actionable (bright blue); unregistered ones stay deliberately
/// dim in the FOREGROUND, so the two confidences are still tellable apart at a glance —
/// the dimming lives in the text colour, never in the plate.
pub fn chip_colors(registered: bool) -> (Color32, Color32) {
    if registered {
        (Color32::from_rgb(150, 200, 255), Color32::from_rgb(12, 14, 20))
    } else {
        (Color32::from_gray(150), Color32::from_rgb(20, 20, 22))
    }
}

/// **The chip's colours when its pane HAS focus** — brighter foreground, a lifted plate.
///
/// Same shape as [`chip_colors`] so the registered/unregistered distinction survives being
/// focused: a focused unregistered pane must still read as unregistered, or the marker
/// stops meaning anything.
pub fn chip_colors_focused(registered: bool) -> (Color32, Color32) {
    if registered {
        (Color32::from_rgb(235, 245, 255), Color32::from_rgb(24, 48, 90))
    } else {
        (Color32::from_rgb(225, 225, 230), Color32::from_rgb(52, 52, 58))
    }
}

/// **Paint the dev-id chip** in the top-right of `rect`. The full id rides the hover
/// tooltip (with the `dir/file` to open).
///
/// The chip senses **hover only — never click**. It is an OVERLAY painted onto a pane's
/// own top-right, and a pane's own controls can live exactly there: measured 2026-08-21,
/// the Git pane's `Tree`/`Log` toggles sit in the chip's band (the pane's columns are
/// narrow, so `rect.right()` is just past them), and with `Sense::click()` the chip —
/// registered AFTER the pane — ate every click on `Log` in every devid-enabled build
/// while the robot reported `expected "log", got "tree"`. A debug overlay must never
/// steal input from the pane it labels; hover-sensing keeps the tooltip and the a11y
/// atom while clicks fall through to the real widget underneath. (The old click-to-copy
/// convenience is gone with it — deliberately: a copy shortcut that breaks the pane's
/// own buttons costs more than retyping an id.)
///
/// A no-op in release builds. `rect` is the pane's own rect — the caller passes it rather
/// than reading `ui.max_rect()` after the pane drew, because a pane that consumed the
/// whole `Ui` leaves the cursor somewhere unhelpful.
pub fn badge(ui: &mut Ui, rect: Rect, component: &str, title: &str) {
    if !enabled() {
        return;
    }
    let (text, registered) = badge_text(component, title);
    let font = FontId::monospace(10.0);
    // FOCUS: the pane the pointer is in. Deliberately NOT an animated pulse — the render
    // oracle compares snapshot images, so anything time-based would make every snapshot
    // differ from the last and the oracle would be worthless. Pointer containment is
    // deterministic under a driver (the pointer is scripted) and reads as a highlight to a
    // human watching a visible drive, which was the point of the request.
    let focused = ui.rect_contains_pointer(rect);
    let (fg, bg) = if focused { chip_colors_focused(registered) } else { chip_colors(registered) };

    let galley = ui.painter().layout_no_wrap(text.clone(), font, fg);
    let size = galley.size();
    let anchor = egui::pos2(rect.right() - 4.0, rect.top() + 4.0);
    let chip = Rect::from_min_size(egui::pos2(anchor.x - size.x - 6.0, anchor.y), size)
        .expand2(egui::vec2(4.0, 2.0));

    // Emitted as a proper a11y ATOM, not bare painted glyphs: a headless test (and the
    // robot driver) reads the id off the AccessKit tree, so "the chip is really on
    // screen" is assertable rather than assumed. Painted-only text is invisible to every
    // check we have — which is how a badge ships green and never appears.
    let resp = crate::a11y::node(
        ui,
        ui.id(),
        ("devid", &text),
        Sense::hover(),
        chip,
        // The atom carries the focus mark too, so `label_contains("[focused]")` answers
        // "which pane is the robot in" off the tree — no guessing from the last click.
        crate::a11y::Semantics::button(if focused {
            format!("{DEVID_ATOM} {text} {FOCUSED_MARK}")
        } else {
            format!("{DEVID_ATOM} {text}")
        }),
    );
    let p = ui.painter();
    p.rect_filled(chip, 3.0, bg);
    if resp.hovered() {
        p.rect_stroke(chip, 3.0, Stroke::new(1.0, fg), egui::StrokeKind::Inside);
    }
    p.text(chip.center(), Align2::CENTER_CENTER, &text, FontId::monospace(10.0), fg);

    let hover = match resolve(component) {
        Some((dir, file)) => format!("{text}\n{dir}/{file}"),
        None => format!("{text}\nthis pane has not declared Facet::component()"),
    };
    resp.on_hover_text(hover);
}

/// **The gate decision, as a pure function** — `$FACETT_DEVID` (if set and understood)
/// wins, otherwise the build profile decides.
///
/// Split out from [`enabled`] for one reason: `debug_assertions` is a *compile-time*
/// fact, and under `cargo test` it is always `true`. A test calling `enabled()` can
/// therefore never observe the release branch — which is precisely how the badge shipped
/// invisible to every release binary on this fleet with five green tests behind it. With
/// the profile as a PARAMETER the release branch is reachable from a debug test, and
/// there is still exactly ONE copy of the rule (LAW 5): [`enabled`] is a one-liner over
/// this, so a table test here cannot drift from what ships.
///
/// It does NOT replace a real release build — a rule that is right and a function that
/// got compiled away are different failures. See `facett-app/tests/devid_release_profile.rs`
/// for the guard that actually runs `--release`.
pub fn resolve_enabled(var: Option<&str>, debug_assertions: bool) -> bool {
    match var {
        Some("1" | "true" | "on" | "yes") => true,
        Some("0" | "false" | "off" | "no") => false,
        // Unset, empty, or a value we do not understand: the profile decides. An
        // unrecognised value must never read as "on" — a typo'd `FACETT_DEVID=yes!`
        // silently enabling a debug overlay in production is the wrong default.
        _ => debug_assertions,
    }
}

/// The decided gate: `(enabled, who decided)`. Process-global and decided ONCE, because
/// [`badge`] asks per pane per frame. `source` travels with the answer rather than being
/// re-derived in [`gate_json`], so the reported *reason* can never disagree with the
/// answer [`badge`] acts on — including when [`force_gate`] decided it.
static GATE: std::sync::OnceLock<(bool, &'static str)> = std::sync::OnceLock::new();

fn gate() -> (bool, &'static str) {
    *GATE.get_or_init(|| {
        let env = std::env::var("FACETT_DEVID").ok();
        let understood = matches!(
            env.as_deref(),
            Some("1" | "true" | "on" | "yes" | "0" | "false" | "off" | "no")
        );
        (
            resolve_enabled(env.as_deref(), cfg!(debug_assertions)),
            if understood { "env" } else { "profile" },
        )
    })
}

/// **Is the dev-id chip switched on?** Debug builds: yes. Release builds: only with
/// `FACETT_DEVID=1`, so the aid is reachable in the binaries that actually ship.
/// `FACETT_DEVID=0` turns it off even in debug. Read once and cached — this is called
/// per pane per frame.
pub fn enabled() -> bool {
    gate().0
}

/// **Decide the gate from inside the process, before anything reads it** — the seam a
/// test needs to assert on the CHIP in a build profile where the chip is off by default.
///
/// # Why this exists
///
/// `facett-app/tests/devid_scene_slots.rs` asserts that `scene::render` really paints a
/// chip per pane — the container wiring, off the AccessKit tree. That is a property of
/// the CONTAINER, not of the build profile, but the tests could only observe it while the
/// gate happened to be open, so the whole file went red under `cargo test --release`
/// (measured 2026-08-31: 4 of its 5 tests failed, purely because `debug_assertions` was
/// off). The two honest-looking repairs are both worse: gating the file to
/// `debug_assertions` makes it a dark file in exactly the profile that ships, and making
/// each assertion conditional on `enabled()` turns four positive proofs into "assert
/// nothing when the gate is closed" — a green produced by looking at nothing, which is
/// LAW 2's named failure. This seam keeps the assertions positive in BOTH profiles.
///
/// It does not weaken the DEFAULT, which is the thing that shipped wrong: nothing here
/// changes what an unforced binary does, and the profile rule keeps its own guards —
/// [`resolve_enabled`]'s table below, and `facett-app/tests/devid_release_profile.rs`,
/// which builds a real `--release` binary and proves the chip is off until
/// `FACETT_DEVID=1` opens it. Forcing is visible in [`gate_json`] as `source: "forced"`,
/// so a dump can never present a forced gate as the profile's own answer.
///
/// # Panics
///
/// If the gate was already decided as something else — a read (or an earlier
/// `force_gate`) that got there first. A silent no-op would hand the caller a gate it did
/// not ask for and the assertions built on it would prove nothing, so this is loud.
/// Callers in one test binary must therefore agree on the value; they all want `true`.
pub fn force_gate(on: bool) {
    let _ = GATE.set((on, "forced"));
    let (now, source) = gate();
    assert_eq!(
        now, on,
        "the dev-id gate was already decided as {now} (by {source}) before force_gate({on}) \
         ran — every assertion about the chip after this point would be about the wrong \
         gate. Call force_gate() before anything renders or reads the gate."
    );
}

/// **The gate, as observable data** — folded into `FacetDeck::state_json` and
/// `facett_app::scene::render`'s state under the key `devid`, so a headless oracle can
/// report *why* there are no chips without anyone opening a window.
///
/// ```json
/// { "enabled": true, "env": "1", "debug_assertions": false, "source": "env" }
/// ```
///
/// * `enabled` — the resolved answer [`badge`] acts on.
/// * `env` — the raw `$FACETT_DEVID`, or `null`. Distinguishes *"nobody set it"* from
///   *"it was set to something I did not understand"*, which look identical in `enabled`.
/// * `debug_assertions` — the profile this binary was compiled in. This is the field that
///   would have named the third failure on sight.
/// * `source` — `"env"` when the variable decided, `"profile"` when it did not, and
///   `"forced"` when a test called [`force_gate`]. The third value is not decoration: a
///   forced gate that reported `"profile"` would be a dump claiming this build's profile
///   says something it does not, which is the confident-wrong-answer this field exists to
///   prevent.
///
/// # This does NOT mean a chip is on screen
///
/// It reports the GATE, nothing more. `enabled: true` is consistent with a badge wired
/// into a draw path nobody calls (miss #1), with a container that never calls it at all
/// (miss #2), and with a chip painted off-screen or behind another pane. Each of those
/// shipped, and each would have reported `enabled: true` here. This field narrows a
/// diagnosis; only a screenshot of the real window on the real build profile closes it.
/// See `facett-app/tests/devid_release_profile.rs` for the assertion on applied output.
pub fn gate_json() -> serde_json::Value {
    let (enabled, source) = gate();
    serde_json::json!({
        "enabled": enabled,
        "env": std::env::var("FACETT_DEVID").ok(),
        "debug_assertions": cfg!(debug_assertions),
        "source": source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// **A badge must never claim an id the registry cannot resolve.** This is the
    /// `facet-map-99` hole from `errcode_raise_sites.rs`, applied to identity rather
    /// than to errors: an authoritative-looking id that names nothing costs the reader
    /// more than showing no id at all.
    #[test]
    fn an_unknown_component_is_marked_unregistered_not_rendered_as_an_id() {
        let (text, ok) = badge_text("definitely-not-a-registered-component", "Some Pane");
        assert!(!ok, "an unknown component must NOT report as registered");
        assert!(text.starts_with(UNREGISTERED), "must be visibly marked, got {text:?}");
        assert!(resolve("definitely-not-a-registered-component").is_none());

        // The empty case (a pane that never declared one) falls back to the title, and
        // is marked just the same — no component is not the same as a valid component.
        let (text, ok) = badge_text("", "Some Pane");
        assert!(!ok);
        assert!(text.contains("Some Pane"), "the fallback still identifies the pane: {text:?}");
        assert!(text.starts_with(UNREGISTERED));
    }

    /// **The elm bridge fills `component()` with `module_path!()`** — so the mapping
    /// from a crate path to a registry component has to hold, or every bridged pane
    /// silently renders ⟨unregistered⟩ despite being registered all along.
    #[test]
    fn a_module_path_normalises_to_its_registry_component() {
        assert_eq!(normalize("facett_geomap"), "geomap");
        assert_eq!(normalize("facett_map3d::inner::deep"), "map3d");
        assert_eq!(normalize("geomap"), "geomap", "a hand-written bare component passes through");
        assert!(is_registered("facett_geomap"), "the bridged spelling must resolve");
        let (text, ok) = badge_text("facett_map3d", "3-D Map");
        assert!(ok);
        assert_eq!(text, "map3d/3-D Map", "the chip shows the registry name + the pane");
        // Two panes of the SAME crate must be tellable apart — the korp case, where
        // every pane shares one component.
        let (a, _) = badge_text("korp", "ingest_load");
        let (b, _) = badge_text("korp", "map");
        assert_ne!(a, b, "same component, different pane, identical chip: {a} vs {b}");
    }

    /// **The RELEASE branch of the gate, reached from a debug test.**
    ///
    /// This is the hole that let the feature ship invisible: `cargo test` compiles with
    /// `debug_assertions` ON, so every test saw the debug branch and none of them could
    /// see that a release binary showed nothing. Passing the profile as a parameter makes
    /// both branches reachable. The `debug = false` rows are the ones that matter — they
    /// are the build Rickard actually runs.
    #[test]
    fn the_gate_honours_the_env_var_in_a_release_profile_too() {
        // RELEASE (debug_assertions off): off unless explicitly switched on.
        assert!(!resolve_enabled(None, false), "release + unset must be OFF");
        for on in ["1", "true", "on", "yes"] {
            assert!(
                resolve_enabled(Some(on), false),
                "FACETT_DEVID={on} must switch the chip ON in a RELEASE build — that is \
                 the whole escape hatch, and without it the aid is invisible to the \
                 binaries people run"
            );
        }
        for off in ["0", "false", "off", "no"] {
            assert!(!resolve_enabled(Some(off), false), "FACETT_DEVID={off} must stay OFF");
        }
        // An unrecognised value must fall back to the profile, never to "on".
        assert!(!resolve_enabled(Some("banana"), false), "an unknown value must not enable it");
        assert!(!resolve_enabled(Some(""), false), "an empty value must not enable it");

        // DEBUG: on by default, and switchable off — so a developer can silence it.
        assert!(resolve_enabled(None, true), "debug + unset must be ON");
        assert!(!resolve_enabled(Some("0"), true), "FACETT_DEVID=0 must silence it in debug");
        assert!(resolve_enabled(Some("banana"), true), "an unknown value falls back to profile");

        // And the SHIPPED entry point must agree with the rule for THIS build, or the
        // table above is testing a function nothing calls (the tautology this replaced).
        // `enabled()` caches, so this only reads it — the env cases live above.
        if std::env::var_os("FACETT_DEVID").is_none() {
            assert_eq!(
                enabled(),
                cfg!(debug_assertions),
                "enabled() disagrees with resolve_enabled for this build profile"
            );
        }
    }

    /// **The chip's plate must OCCLUDE, not tint.**
    ///
    /// The chip is drawn over a corner the pane has already painted. With a translucent
    /// plate that is not a badge on a pane, it is two strings sharing pixels — seen on a
    /// real release window, where `⟨unregistered⟩ Velo L1` sat on top of the pane's own
    /// header and neither was readable. "The chip is there" and "the chip is legible" are
    /// different claims and this asserts the second.
    #[test]
    fn the_chip_plate_is_opaque_so_it_does_not_superimpose_two_strings() {
        for registered in [true, false] {
            let (fg, bg) = chip_colors(registered);
            assert_eq!(
                bg.a(),
                255,
                "the chip plate is translucent (alpha {}) for registered={registered} — the \
                 pane's own text bleeds through it and the id becomes unreadable",
                bg.a()
            );
            // A plate that occludes is worthless if the text on it does not stand out.
            let lum = |c: Color32| 0.299 * c.r() as f32 + 0.587 * c.g() as f32 + 0.114 * c.b() as f32;
            assert!(
                (lum(fg) - lum(bg)).abs() > 60.0,
                "chip fg/bg are too close to read (registered={registered}): {fg:?} on {bg:?}"
            );
        }
        // The two CONFIDENCES must still be tellable apart — that distinction was the
        // point of the ⟨unregistered⟩ marker, and it must survive the opacity fix.
        assert_ne!(chip_colors(true).0, chip_colors(false).0, "registered/unregistered look identical");
    }

    /// **The gate must be REPORTED, not just obeyed.** A headless oracle reads this off
    /// `state_json`; if it disagreed with what `badge` acts on it would be worse than
    /// absent — a confident wrong answer during a hunt.
    #[test]
    fn the_reported_gate_matches_the_one_the_badge_acts_on() {
        let g = gate_json();
        assert_eq!(
            g["enabled"], enabled(),
            "state_json reports a different gate than badge() obeys: {g}"
        );
        assert_eq!(
            g["debug_assertions"], cfg!(debug_assertions),
            "the reported profile is not this binary's profile: {g}"
        );
        // `source` must name who decided, so "unset" and "set to nonsense" are tellable
        // apart — they resolve identically in `enabled` and mean very different things.
        let by_env = std::env::var("FACETT_DEVID")
            .map(|v| matches!(v.as_str(), "1" | "true" | "on" | "yes" | "0" | "false" | "off" | "no"))
            .unwrap_or(false);
        assert_eq!(g["source"], if by_env { "env" } else { "profile" }, "wrong source: {g}");
    }

    /// The happy path, driven off a component the registry really carries — so this test
    /// cannot pass by the lookup being dead (the identity-value trap: a resolver that
    /// always returns `None` would pass the test above alone).
    #[test]
    fn a_registered_component_resolves_to_its_crate_and_file() {
        let known = crate::errcode::REGISTRY.first().expect("the registry is not empty");
        let (text, ok) = badge_text(known.component, "ignored title");
        assert!(ok, "{} is in the registry but did not report registered", known.component);
        assert_eq!(text, format!("{}/ignored title", known.component), "registered ⇒ component/pane");
        let (dir, file) = resolve(known.component).expect("resolves");
        assert!(!dir.is_empty() && !file.is_empty(), "a resolved id must name a real place");
    }
}