domainforge-core 0.18.1

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
//! BPMN 2.0 projection: flows and their branching project to a single,
//! XSD-valid BPMN 2.0 XML file (`--format bpmn`).
//!
//! Declared v1 subset (see `docs/bpmn-projections.md`): a non-executable
//! process with lanes (from roles), start/end events, tasks (from the entities
//! that participate in flows), parallel gateways (from flow fan-out/fan-in),
//! sequence flows (from flow edges), and data objects (from resources). BPMNDI
//! visual layout is **out of scope v1** — import tools (bpmn.io, Camunda)
//! auto-layout on open.
//!
//! One IR module ([`ir`]) + one renderer ([`xml`]) + one [`emit`] + one
//! [`project_bpmn_in_memory`] binding surface, per the shared projection pattern
//! (`projection/lean/mod.rs`). 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).

pub mod ir;
pub mod xml;

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

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

/// Emit the BPMN process 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 process = ProcessIR::from_graph(graph, model_ref);
    // Self-check: never write a structurally broken process (the XSD cannot see
    // QName dangling refs — see ProcessIR::validate_references).
    process.validate_references()?;

    let body = xml::render(&process);
    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_bpmn_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 bpmn) 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;

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

    // Warehouse fans out to two consumers (a diverging parallel gateway); both
    // feed Assembly (a converging parallel gateway) — exercises every node kind.
    const SOURCE: &str = r#"
@namespace "demo"

Entity "Warehouse" in demo
Entity "LineA" in demo
Entity "LineB" in demo
Entity "Assembly" in demo

Role "Operator" in demo
Role "Supervisor" in demo

Resource "CameraUnits" units in demo

Flow "CameraUnits" from "Warehouse" to "LineA" quantity 40
Flow "CameraUnits" from "Warehouse" to "LineB" quantity 60
Flow "CameraUnits" from "LineA" to "Assembly" quantity 40
Flow "CameraUnits" from "LineB" to "Assembly" quantity 60
"#;

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

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

    #[test]
    fn contains_process_tasks_and_gateways() {
        let bpmn = &project(SOURCE)["model.bpmn"];
        assert!(bpmn.contains("<process"));
        assert!(bpmn.contains("isExecutable=\"false\""));
        assert!(bpmn.contains("<startEvent"));
        assert!(bpmn.contains("<endEvent"));
        assert!(bpmn.contains("name=\"Warehouse\""));
        assert!(bpmn.contains("gatewayDirection=\"Diverging\""));
        assert!(bpmn.contains("gatewayDirection=\"Converging\""));
        assert!(bpmn.contains("<sequenceFlow"));
        assert!(bpmn.contains("name=\"CameraUnits\"")); // data object
        assert!(bpmn.contains("<laneSet"));
        assert!(bpmn.contains("name=\"Operator\"")); // lane from declared role
        assert!(bpmn.contains("Generated by DomainForge"));
    }

    // The `.sea` surface declares roles but does not bind them to entities, so
    // lanes are empty by default. When the graph *does* carry a binding, the
    // owning entity's task appears as a `flowNodeRef` in that role's lane.
    #[test]
    fn bound_roles_populate_lane_flow_node_refs() {
        let mut graph = parse_to_graph(SOURCE).expect("parses");
        let role = graph.find_role_by_name("Operator").expect("role exists");
        let entity = graph
            .find_entity_by_name("Warehouse")
            .expect("entity exists");
        graph
            .assign_role_to_entity(entity, role)
            .expect("assignment succeeds");
        let files = project_bpmn_in_memory(&graph, "test.sea", Some(FIXED_TS.to_string())).unwrap();
        assert!(files["model.bpmn"].contains("<flowNodeRef>"));
    }

    #[test]
    fn straight_line_model_has_no_gateways() {
        let src = r#"
@namespace "demo"
Entity "A" in demo
Entity "B" in demo
Resource "R" units in demo
Flow "R" from "A" to "B" quantity 1
"#;
        let bpmn = &project(src)["model.bpmn"];
        assert!(!bpmn.contains("<parallelGateway"));
        assert!(bpmn.contains("<task"));
    }

    #[test]
    fn empty_model_emits_start_to_end_process() {
        let bpmn = &project("@namespace \"empty\"\n")["model.bpmn"];
        assert!(bpmn.contains("<startEvent"));
        assert!(bpmn.contains("<endEvent"));
        assert!(bpmn.contains("<sequenceFlow"));
        assert!(!bpmn.contains("<task"));
    }

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

    // Teeth-check: dropping a sequence flow leaves dangling QName refs the BPMN
    // XSD cannot catch, but the structural validator does.
    #[test]
    fn deleting_a_sequence_flow_fails_structural_validation() {
        let graph = parse_to_graph(SOURCE).expect("parses");
        let mut ir = ProcessIR::from_graph(&graph, "test.sea");
        ir.validate_references().expect("intact IR is valid");
        ir.sequence_flows.pop().expect("has sequence flows");
        assert!(
            ir.validate_references().is_err(),
            "removing a sequence flow must break reference integrity"
        );
    }
}