domainforge-core 0.18.2

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
//! ArchiMate 3.0 projection: roles, entities, resources, flows, and policies
//! project to a single, XSD-valid ArchiMate Model Exchange File
//! (`--format archimate`).
//!
//! Declared v1 subset (see `docs/archimate-projections.md`): a business-layer
//! architecture — business roles (from roles), business objects (from entities
//! and resources), business processes (from flows) — plus motivation
//! requirements (from authority policies), wired with **only spec-legal
//! relations**. Legality is enforced *by construction*: the IR builder consults a
//! static allowed-relations table ([`ir::ALLOWED_RELATIONS`]) and cannot emit a
//! triple absent from it (see [`ir::Relation::build`]). One auto-generated
//! business-layer view lists the business-layer elements; per-stakeholder views
//! are a **Non-goal v1**.
//!
//! One IR module ([`ir`]) + one renderer ([`xml`]) + one [`emit`] + one
//! [`project_archimate_in_memory`] binding surface, per the shared projection
//! pattern (`projection/lean/mod.rs`), reusing the BPMN [`Xml`](xml) writer.
//! Output is byte-deterministic for a fixed `created_at`: every collection is
//! sorted and no wall-clock or random data enters file contents (the timestamp
//! is caller-supplied; flow ids — which are random UUIDs — never reach output,
//! process ids being derived from the flows' deterministic endpoint ids).

pub mod ir;
pub mod xml;

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

/// The single emitted artifact's relative path.
pub const OUTPUT_FILE: &str = "model.xml";

/// Emit the ArchiMate model into `sink`; returns the emitted relative 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 model = ArchitectureIR::from_graph(graph, model_ref)?;
    // Self-check: never write a model with dangling IDREFs or an illegal relation
    // (the XSD resolves neither reliably — see validate_references).
    model.validate_references()?;

    let body = xml::render(&model);
    let content = with_provenance(&body, model_ref, &created_at);

    sink.write(OUTPUT_FILE, &content)?;
    Ok(vec![OUTPUT_FILE.to_string()])
}

/// Binding surface: string in, path→content map out, no filesystem.
pub fn project_archimate_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)
}

/// Insert a provenance XML comment directly after the XML declaration line.
/// `--` is illegal inside XML comments, so it is broken up.
fn with_provenance(body: &str, model_ref: &str, created_at: &str) -> String {
    let safe = |s: &str| s.replace("--", "- -").replace(['\n', '\r'], " ");
    let comment = format!(
        "<!-- Generated by DomainForge (format archimate) from {}. Created: {}. Do not edit by hand. -->\n",
        safe(model_ref),
        safe(created_at)
    );
    match body.split_once('\n') {
        Some((decl, rest)) => format!("{decl}\n{comment}{rest}"),
        None => format!("{body}\n{comment}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_to_graph;
    use ir::{ElemKind, RelKind, Relation};

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

    // A model with roles (→ business roles), entities + resources (→ business
    // objects), and two policies (→ requirements) whose expressions reference an
    // object (→ associations).
    const SOURCE: &str = r#"
@namespace "demo"

Entity "PurchaseOrder" in demo
Entity "Invoice" in demo

Role "Approver" in demo
Role "Clerk" in demo

Resource "Budget" units in demo

Policy positive_budget as: Budget.quantity > 0
Policy within_limit as: Budget.quantity < 500
"#;

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

    #[test]
    fn emits_single_model_file() {
        let files = project(SOURCE);
        assert_eq!(files.keys().collect::<Vec<_>>(), vec!["model.xml"]);
    }

    #[test]
    fn contains_business_elements() {
        let xml = &project(SOURCE)["model.xml"];
        assert!(xml.contains("<model"));
        assert!(xml.contains("xsi:type=\"BusinessRole\""));
        assert!(xml.contains("name=\"Approver\"") || xml.contains(">Approver<"));
        assert!(xml.contains("xsi:type=\"BusinessObject\""));
        assert!(xml.contains(">PurchaseOrder<"));
        assert!(xml.contains(">Budget<"));
        assert!(xml.contains("xsi:type=\"Requirement\""));
        assert!(xml.contains("<views"));
        assert!(xml.contains("xsi:type=\"Diagram\""));
        assert!(xml.contains("Generated by DomainForge"));
    }

    // A policy expression referencing "Budget" produces an Association from the
    // requirement to the Budget business object.
    #[test]
    fn policy_associates_with_referenced_object() {
        let xml = &project(SOURCE)["model.xml"];
        assert!(xml.contains("xsi:type=\"Association\""));
    }

    // Teeth-check (the whole point of the task): feeding a forbidden relation
    // triple into the IR builder is rejected.
    #[test]
    fn forbidden_relation_tuple_is_rejected() {
        // BusinessObject --Assignment--> BusinessObject is not in the matrix.
        let err = Relation::build(
            "Relation_x".to_string(),
            "Element_a".to_string(),
            ElemKind::BusinessObject,
            RelKind::Assignment,
            "Element_b".to_string(),
            ElemKind::BusinessObject,
        );
        assert!(
            err.is_err(),
            "an illegal ArchiMate relation must be rejected by construction"
        );

        // A legal triple still builds.
        let ok = Relation::build(
            "Relation_y".to_string(),
            "Element_p".to_string(),
            ElemKind::BusinessProcess,
            RelKind::Access,
            "Element_o".to_string(),
            ElemKind::BusinessObject,
        );
        assert!(ok.is_ok(), "a legal ArchiMate relation must build");
    }

    #[test]
    fn empty_model_emits_minimal_model() {
        let xml = &project("@namespace \"empty\"\n")["model.xml"];
        assert!(xml.contains("<model"));
        assert!(!xml.contains("<relationships"));
    }

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

    // Teeth-check: mutating a held relation to an illegal triple is caught by the
    // structural validator (defence in depth beyond the XSD).
    #[test]
    fn mutating_a_relation_to_illegal_fails_validation() {
        let graph = parse_to_graph(SOURCE).expect("parses");
        let mut ir = ArchitectureIR::from_graph(&graph, "test.sea").expect("builds");
        ir.validate_references().expect("intact IR is valid");
        if let Some(rel) = ir.relations.first_mut() {
            rel.kind = RelKind::Assignment;
            rel.source_kind = ElemKind::BusinessObject;
            rel.target_kind = ElemKind::BusinessObject;
        }
        assert!(
            ir.validate_references().is_err(),
            "an illegal relation must fail structural validation"
        );
    }
}