domainforge-core 0.18.2

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
//! OpenTelemetry SemConv projection (`--format otel-semconv`): the runtime-
//! observation operator.
//!
//! Domain entities, flows, and policy-decision points project to an OTel
//! semantic-convention **registry** (YAML) plus generated **attribute-constant**
//! files (Rust / Python / TypeScript). Every domain attribute is namespaced
//! under the model's own namespace; the OTel Resource carries DomainForge
//! correlation attributes (`domainforge.model.hash`, `domainforge.element.id`)
//! so runtime telemetry points back at model identity — the traceability
//! keystone this projection exists to provide.
//!
//! One IR ([`ir::TelemetryIR`]) drives every artifact: the registry and the
//! three constant files are renderings of the same attribute set, so they can
//! never disagree (a test asserts this "single-producer" property). The IR's
//! reserved-namespace guard refuses to mint any OTel-reserved attribute, so the
//! projection cannot collide with an upstream semantic convention.
//!
//! Emitted layout:
//! - `registry/telemetry.yaml` — the SemConv registry.
//! - `constants/attributes.rs` / `.py` / `.ts` — attribute-key constants.
//!
//! Output is byte-deterministic for a fixed `created_at`: all collections are
//! iterated in sorted order and no wall-clock or random data enters contents.

pub mod constants;
pub mod ir;
pub mod yaml;

use crate::graph::Graph;
use crate::projection::sink::ArtifactSink;
use ir::TelemetryIR;
use std::collections::BTreeMap;

/// Emit the OTel SemConv artifacts into `sink`; returns the emitted paths.
pub fn emit(
    graph: &Graph,
    model_ref: &str,
    created_at: Option<String>,
    sink: &mut ArtifactSink,
) -> Result<Vec<String>, String> {
    let created_at = created_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
    let telemetry = TelemetryIR::from_graph(graph, model_ref)?;

    let yaml_header = header('#', model_ref, &created_at);
    let files: Vec<(&str, String)> = vec![
        (
            "registry/telemetry.yaml",
            yaml::render(&telemetry, &yaml_header),
        ),
        (
            "constants/attributes.rs",
            constants::render_rust(&telemetry, &yaml_header),
        ),
        (
            "constants/attributes.py",
            constants::render_python(&telemetry, &yaml_header),
        ),
        (
            "constants/attributes.ts",
            constants::render_typescript(&telemetry, &yaml_header),
        ),
    ];

    let mut written = Vec::with_capacity(files.len());
    for (rel, content) in files {
        sink.write(rel, &content)?;
        written.push(rel.to_string());
    }
    Ok(written)
}

/// Binding surface: string in, path→content map out, no filesystem.
pub fn project_otel_semconv_in_memory(
    graph: &Graph,
    model_ref: &str,
    created_at: Option<String>,
) -> Result<BTreeMap<String, String>, String> {
    let mut map = BTreeMap::new();
    let mut sink = ArtifactSink::Memory {
        prefix: String::new(),
        map: &mut map,
    };
    emit(graph, model_ref, created_at, &mut sink)?;
    Ok(map)
}

/// Provenance comment block. `marker` is the line-comment character (`#`).
fn header(marker: char, model_ref: &str, created_at: &str) -> String {
    format!(
        "{marker} Generated by DomainForge (--format otel-semconv) from {}.\n\
         {marker} Created: {}. Do not edit by hand.\n\n",
        model_ref.replace(['\n', '\r'], " "),
        created_at.replace(['\n', '\r'], " ")
    )
}

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

    const FIXED_TS: &str = "2026-07-02T00:00:00+00:00";

    const SOURCE: &str = r#"
@namespace "demo"

Entity "Warehouse" in demo
Entity "Factory" in demo
Resource "CameraUnits" units in demo
Flow "CameraUnits" from "Warehouse" to "Factory" quantity 100
Policy positive_flow as: Flow.quantity > 0
"#;

    fn project(source: &str) -> BTreeMap<String, String> {
        let graph = parse_to_graph(source).expect("fixture parses");
        project_otel_semconv_in_memory(&graph, "test.sea", Some(FIXED_TS.to_string()))
            .expect("projection succeeds")
    }

    #[test]
    fn emits_registry_and_three_constant_files() {
        let files = project(SOURCE);
        assert_eq!(
            files.keys().collect::<Vec<_>>(),
            vec![
                "constants/attributes.py",
                "constants/attributes.rs",
                "constants/attributes.ts",
                "registry/telemetry.yaml",
            ]
        );
    }

    #[test]
    fn registry_and_constants_agree_on_attribute_set() {
        let files = project(SOURCE);
        let yaml = &files["registry/telemetry.yaml"];
        // Attribute definition ids in the YAML (lines `      - id: "..."`).
        let mut yaml_keys: Vec<String> = yaml
            .lines()
            .filter_map(|l| l.trim().strip_prefix("- id: "))
            .map(|q| q.trim_matches('"').to_string())
            .filter(|k| !k.starts_with("registry.") && !k.starts_with("span."))
            .collect();
        yaml_keys.sort();
        yaml_keys.dedup();

        let mut const_keys: Vec<String> = files["constants/attributes.rs"]
            .lines()
            .filter_map(|l| l.split("= \"").nth(1))
            .map(|q| q.trim_end_matches("\";").trim_matches('"').to_string())
            .collect();
        const_keys.sort();

        assert_eq!(yaml_keys, const_keys, "YAML and constants disagree");
        assert!(yaml_keys.iter().any(|k| k == "domainforge.model.hash"));
    }

    #[test]
    fn output_is_deterministic() {
        assert_eq!(project(SOURCE), project(SOURCE));
    }
}