facett-core 0.1.0

facett — visual kernel: render a node/edge Scene into egui (wgpu fast path to come)
Documentation
//! Headless test harness — **fire up a `Facet`, inject data, render it offscreen,
//! and capture what it drew**: its `state_json` + a vertex count (a "it drew
//! something" proxy) + a stderr activity trail. No display, no GPU. This is the
//! basis of facett's auto test matrix, and mirrors nornir viz's
//! `NORNIR_VIZ_STATE` introspection — every component is observable from outside.

use crate::Facet;

/// What a headless render of one facet looked like.
#[derive(Debug, Clone)]
pub struct RenderReport {
    pub title: String,
    /// The component's observable state (its `Facet::state_json`).
    pub state: serde_json::Value,
    /// Tessellated mesh vertices — a proxy for "it actually drew something".
    pub vertices: usize,
}

impl RenderReport {
    pub fn drew(&self) -> bool {
        self.vertices > 0
    }
}

/// Render `facet` once into the given context at `size`, capturing its state +
/// a vertex count. A panic in `ui` propagates — that's the point of the test.
#[allow(deprecated)] // ctx.run / CentralPanel::show are the headless-render path
fn capture(ctx: &egui::Context, facet: &mut dyn Facet, size: (f32, f32)) -> RenderReport {
    let title = facet.title().to_string();
    // Structured trace IN: which facet + at what size this render was handed
    // (the typed sibling of the `trail`/`log` lines below — see `trace`).
    crate::trace::emit_in(
        "facet.render",
        &serde_json::json!({ "title": title, "size": [size.0, size.1] }),
    );
    let input = egui::RawInput {
        screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(size.0, size.1))),
        ..Default::default()
    };
    let output = ctx.run(input, |ctx| {
        egui::CentralPanel::default().show(ctx, |ui| facet.ui(ui));
    });
    let prims = ctx.tessellate(output.shapes, output.pixels_per_point);
    let vertices = prims
        .iter()
        .map(|p| match &p.primitive {
            egui::epaint::Primitive::Mesh(m) => m.vertices.len(),
            _ => 0,
        })
        .sum();
    let report = RenderReport { title, state: facet.state_json(), vertices };
    log(&report);
    trail(Kind::Render, format!("{} size={}x{}{} verts", report.title, size.0 as i32, size.1 as i32, vertices));
    dump_state(&report);
    // Structured trace OUT: the real data the facet rendered — its full
    // observable state + the vertex proof — so an agent reads back exactly what
    // was drawn, no screenshot. (`state` is the same Value `dump_state` prints.)
    crate::trace::emit_out(
        "facet.render",
        &serde_json::json!({
            "title": report.title,
            "vertices": report.vertices,
            "drew": report.drew(),
            "state": report.state,
        }),
    );
    report
}

/// Headless render at `size` (default theme).
pub fn render_sized(facet: &mut dyn Facet, size: (f32, f32)) -> RenderReport {
    capture(&egui::Context::default(), facet, size)
}

/// `render_sized` at a default 800×600.
pub fn headless_render(facet: &mut dyn Facet) -> RenderReport {
    render_sized(facet, (800.0, 600.0))
}

/// Headless render with a theme applied (asserts the themed paint path works).
pub fn render_themed(facet: &mut dyn Facet, theme: crate::Theme) -> RenderReport {
    let ctx = egui::Context::default();
    crate::set_theme(&ctx, theme);
    capture(&ctx, facet, (800.0, 600.0))
}

/// Stderr activity trail (one line per render), like nornir viz's. The state is
/// capped so a large component can't flood the log.
pub fn log(r: &RenderReport) {
    let full = r.state.to_string();
    let shown: String = if full.chars().count() > 160 {
        full.chars().take(159).chain(std::iter::once('')).collect()
    } else {
        full
    };
    eprintln!("facett: {:<14} {:>7} verts · {}", r.title, r.vertices, shown);
}

// ── action-log-style trail (mirrors nornir viz `action_log`) ─────────────────
//
// Nornir's viz emits a timestamped, kinded, sequenced trail
// (`HH:MM:SS.mmm  <seq> [KIND] detail`) on stderr + a greppable file so a human
// can follow "what the headless run did". These give facett's matrices the same
// observability. Dep-free: the stamp is derived from `SystemTime` and the seq
// from a process-global atomic — no chrono, no extra crate.

/// Coarse, greppable category for a trail entry — facett's analogue of nornir's
/// `action_log::Kind`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// A facet was rendered headlessly.
    Render,
    /// A facet's full observable state was captured.
    State,
    /// A per-case matrix summary (component × theme × size).
    Case,
}

impl Kind {
    pub fn tag(self) -> &'static str {
        match self {
            Kind::Render => "RENDER",
            Kind::State => "STATE",
            Kind::Case => "CASE",
        }
    }
}

/// Process-global monotonic sequence — stable ordering even within one ms.
fn next_seq() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);
    SEQ.fetch_add(1, Ordering::Relaxed) + 1
}

/// `HH:MM:SS.mmm` local-ish wall stamp from `SystemTime` (UTC, no tz dep). Only
/// the time-of-day matters for following a trail, so this is intentionally
/// dependency-free rather than chrono-accurate.
fn now_stamp() -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let total_ms = now.as_millis();
    let ms = (total_ms % 1000) as u64;
    let secs = (total_ms / 1000) as u64;
    let h = (secs / 3600) % 24;
    let m = (secs / 60) % 60;
    let s = secs % 60;
    format!("{h:02}:{m:02}:{s:02}.{ms:03}")
}

/// Emit one greppable, timestamped, kinded trail line — facett's analogue of
/// nornir viz's `action_log` stderr sink:
///   `facett ACTION HH:MM:SS.mmm  <seq> [KIND] detail`
/// If `$FACETT_TRAIL` is set, the same line is appended to that file (greppable,
/// externally observable — mirrors how nornir mirrors `$NORNIR_VIZ_ACTIONLOG`).
pub fn trail(kind: Kind, detail: impl AsRef<str>) {
    let stamp = now_stamp();
    let seq = next_seq();
    let detail = detail.as_ref();
    let line = format!("facett ACTION {stamp} {seq:>5} [{}] {detail}", kind.tag());
    eprintln!("{line}");
    if let Ok(path) = std::env::var("FACETT_TRAIL") {
        use std::io::Write;
        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
            let _ = writeln!(f, "{line}");
        }
    }
}

/// Dump a facet's FULL observable `state_json` as a single greppable line
/// (`facett STATE <title> = {…}`), the per-component analogue of viz_matrix's
/// `eprintln!("state_json = {pretty}")`. Untruncated so a Facet's rendered
/// contents are greppable in test output the way viz's are.
pub fn dump_state(r: &RenderReport) {
    eprintln!("facett STATE {} = {}", r.title, r.state);
    trail(Kind::State, format!("{} state={}", r.title, r.state));
}

/// Emit a uniform per-case matrix summary line + trail entry for one
/// component × axis case (e.g. a theme or a size), mirroring viz_matrix's
/// `[ws] releases=… tables=…` per-workspace summary. `axis` is a free-form
/// label like `theme=sci_fi` or `size=10000`.
pub fn case_summary(component: &str, axis: &str, r: &RenderReport) {
    eprintln!(
        "facett CASE  {:<14} {:<16} → {:>8} verts  drew={}  state={}",
        component,
        axis,
        r.vertices,
        r.drew(),
        r.state,
    );
    trail(Kind::Case, format!("{component} {axis} verts={} drew={}", r.vertices, r.drew()));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Scene, hash_color};

    struct Tiny(Scene);
    impl Facet for Tiny {
        fn title(&self) -> &str {
            "tiny"
        }
        fn ui(&mut self, ui: &mut egui::Ui) {
            crate::draw(ui, &self.0, crate::Layout::Circular, "empty");
        }
        fn state_json(&self) -> serde_json::Value {
            serde_json::json!({ "nodes": self.0.nodes.len() })
        }
    }

    #[test]
    fn now_stamp_is_hms_millis_shaped() {
        let s = now_stamp();
        // HH:MM:SS.mmm — 12 chars, two ':' and one '.'.
        assert_eq!(s.len(), 12, "stamp `{s}` should be HH:MM:SS.mmm");
        assert_eq!(s.matches(':').count(), 2, "stamp `{s}` needs two colons");
        assert_eq!(s.matches('.').count(), 1, "stamp `{s}` needs one dot");
    }

    #[test]
    fn seq_is_monotonic() {
        let a = next_seq();
        let b = next_seq();
        assert!(b > a, "seq must strictly increase: {a} then {b}");
    }

    #[test]
    fn kind_tags_are_distinct() {
        let tags = [Kind::Render.tag(), Kind::State.tag(), Kind::Case.tag()];
        for (i, t) in tags.iter().enumerate() {
            assert!(!t.is_empty());
            assert!(!tags[..i].contains(t), "duplicate tag {t}");
        }
    }

    #[test]
    fn headless_render_captures_state_and_draws() {
        let mut scene = Scene::new();
        let a = scene.node("a", hash_color("a"));
        let b = scene.node("b", hash_color("b"));
        scene.edge(a, b);
        let mut t = Tiny(scene);
        let r = headless_render(&mut t);
        assert_eq!(r.title, "tiny");
        assert_eq!(r.state["nodes"], 2);
        assert!(r.drew(), "a 2-node graph should tessellate to vertices");
    }
}