domainforge-core 0.18.1

Rust core library implementing the SEA DSL primitives and validation engine.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Python DDD/CQRS renderer. Consumes [`crate::projection::domain::ir::DomainIr`]
//! and emits a complete, stdlib-only Python package up to the port boundary.
//!
//! `emit` = `DomainIr::from_graph` + pure render functions IR → Python source.
//! This renderer never touches [`crate::graph::Graph`].

use crate::graph::Graph;
use crate::projection::domain::ir::DomainIr;
use crate::projection::ids::slug;
use crate::projection::sink::ArtifactSink;
use std::collections::BTreeMap;

/// Emit the Python domain package 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 ir = DomainIr::from_graph(graph)?;
    let created_at = created_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
    let pkg = &ir.package_slug;
    let pkg_dir = format!("src/{pkg}_domain");
    let files: Vec<(String, String)> = vec![
        ("pyproject.toml".to_string(), pyproject(&ir)),
        ("README.md".to_string(), readme(&ir, model_ref, &created_at)),
        (format!("{pkg_dir}/__init__.py"), pkg_init(&ir)),
        (format!("{pkg_dir}/container.py"), container(&ir)),
        (format!("{pkg_dir}/domain/__init__.py"), domain_init(&ir)),
        (
            format!("{pkg_dir}/domain/value_objects.py"),
            value_objects(&ir),
        ),
        (format!("{pkg_dir}/domain/entities.py"), entities(&ir)),
        (format!("{pkg_dir}/domain/roles.py"), roles(&ir)),
        (format!("{pkg_dir}/domain/errors.py"), errors(&ir)),
        (format!("{pkg_dir}/domain/commands.py"), commands(&ir)),
        (format!("{pkg_dir}/domain/events.py"), events(&ir)),
        (format!("{pkg_dir}/domain/aggregates.py"), aggregates(&ir)),
        (format!("{pkg_dir}/ports/__init__.py"), String::new()),
        (
            format!("{pkg_dir}/ports/repositories.py"),
            repositories(&ir),
        ),
        (format!("{pkg_dir}/ports/bus.py"), bus(&ir)),
        (format!("{pkg_dir}/ports/read_model.py"), read_model(&ir)),
        ("tests/test_domain_smoke.py".to_string(), smoke_test(&ir)),
    ];
    let mut emitted = Vec::new();
    for (path, body) in &files {
        sink.write(path, body)?;
        emitted.push(path.clone());
    }
    Ok(emitted)
}

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

// ---------- file renderers (explicit indentation; no `\` line continuation) ----------

fn pyproject(ir: &DomainIr) -> String {
    format!(
        "[build-system]\nrequires = [\"setuptools>=68\"]\nbuild-backend = \"setuptools.build_meta\"\n\n\
[project]\nname = \"{pkg}-domain\"\nversion = \"0.1.0\"\n\
description = \"DomainForge-generated DDD/CQRS domain layer for the '{ns}' model.\"\n\
requires-python = \">=3.10\"\ndependencies = []\n\n\
[tool.setuptools.packages.find]\nwhere = [\"src\"]\n",
        pkg = ir.package_slug,
        ns = ir.namespace,
    )
}

fn readme(ir: &DomainIr, model_ref: &str, created_at: &str) -> String {
    format!(
        "# {ns} domain package\n\nGenerated by DomainForge from `{model_ref}` at {created_at}.\n\n\
A complete, stdlib-only DDD/CQRS domain layer up to the port boundary (aggregates,\n\
commands, events, value objects, repository/event/command bus ports). No infrastructure\n\
adapters are included — implement the ports to wire the domain to persistence and messaging.\n",
        ns = ir.namespace,
        model_ref = model_ref,
        created_at = created_at,
    )
}

fn pkg_init(_ir: &DomainIr) -> String {
    "from .container import Container\n".to_string()
}

fn container(ir: &DomainIr) -> String {
    let mut s = String::from("from dataclasses import dataclass\n\n");
    s.push_str("from .ports.bus import CommandBus, EventBus\n");
    s.push_str(&format!(
        "from .ports.read_model import {nsp}ReadModel\n",
        nsp = ir.package_pascal
    ));
    if !ir.aggregates.is_empty() {
        let names: Vec<String> = ir
            .aggregates
            .iter()
            .map(|a| format!("{}Repository", a.name))
            .collect();
        s.push_str(&format!(
            "from .ports.repositories import {}\n",
            names.join(", ")
        ));
    }
    s.push_str("\n@dataclass(frozen=True)\nclass Container:\n");
    if ir.aggregates.is_empty() && ir.queries.is_empty() {
        s.push_str("    pass\n");
        return s;
    }
    for agg in &ir.aggregates {
        s.push_str(&format!(
            "    {slug}_repository: {name}Repository\n",
            slug = slug(&agg.name),
            name = agg.name
        ));
    }
    s.push_str("    event_bus: EventBus\n");
    s.push_str("    command_bus: CommandBus\n");
    s.push_str(&format!("    read_model: {}ReadModel\n", ir.package_pascal));
    s
}

fn domain_init(_ir: &DomainIr) -> String {
    "# Domain layer: value objects, entities, roles, errors, commands, events, aggregates.\n"
        .to_string()
}

fn value_objects(ir: &DomainIr) -> String {
    let mut s = String::from(
        "from __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass\n",
    );
    if !ir.value_objects.is_empty() {
        let errs: Vec<String> = ir
            .value_objects
            .iter()
            .map(|vo| vo.error_name.clone())
            .collect();
        s.push_str(&format!("\nfrom .errors import {}\n", errs.join(", ")));
    }
    s.push_str("\n\n@dataclass(frozen=True)\nclass Quantity:\n    \"\"\"A measured amount with a unit. amount is float for v1 (integer fixture values).\"\"\"\n    amount: float\n    unit: str\n");
    for vo in &ir.value_objects {
        s.push_str(&format!(
            "\n\n@dataclass(frozen=True)\nclass {name}:\n    \"\"\"Value object matching `{regex}`.\"\"\"\n    value: str\n\n    def __post_init__(self) -> None:\n        if re.match(r\"{regex}\", self.value) is None:\n            raise {err}(self.value)\n",
            name = vo.name,
            regex = vo.regex,
            err = vo.error_name,
        ));
    }
    s
}

fn entities(ir: &DomainIr) -> String {
    let mut s = String::from("from dataclasses import dataclass\n");
    for e in &ir.entities {
        s.push_str(&format!(
            "\n\n@dataclass\nclass {name}:\n    \"\"\"Entity.\"\"\"\n    id: str\n    name: str\n",
            name = e.name
        ));
        for (fname, ftype) in &e.fields {
            s.push_str(&format!("    {fname}: {ftype} | None = None\n"));
        }
    }
    s
}

fn roles(ir: &DomainIr) -> String {
    let mut s = String::from("from enum import Enum\n\n\nclass Role(Enum):\n");
    if ir.relations_doc.is_empty() {
        s.push_str("    \"\"\"Authority roles for the domain.\"\"\"\n");
    } else {
        s.push_str("    \"\"\"Authority roles for the domain.\n\n    Relations:\n");
        for line in &ir.relations_doc {
            s.push_str(&format!("    {line}\n"));
        }
        s.push_str("    \"\"\"\n");
    }
    for (i, role) in ir.roles.iter().enumerate() {
        s.push_str(&format!("    {role} = {i}\n"));
    }
    s
}

fn errors(ir: &DomainIr) -> String {
    let mut s = String::from(
        "class DomainError(Exception):\n    \"\"\"Base for all domain errors.\"\"\"\n    pass\n",
    );
    for e in &ir.errors {
        let doc = e.rationale.as_deref().unwrap_or("Policy violation.");
        s.push_str(&format!(
            "\n\nclass {name}(DomainError):\n    \"\"\"{doc}\"\"\"\n    pass\n",
            name = e.name,
            doc = doc
        ));
    }
    for vo in &ir.value_objects {
        s.push_str(&format!(
            "\n\nclass {err}(DomainError):\n    \"\"\"Value object validation error.\"\"\"\n    def __init__(self, value: str) -> None:\n        super().__init__(f\"Invalid {vo}: {{value}}\")\n",
            err = vo.error_name,
            vo = vo.name
        ));
    }
    s
}

fn commands(ir: &DomainIr) -> String {
    let mut s = String::from(
        "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Union\n\nfrom .roles import Role\nfrom .value_objects import Quantity\n",
    );
    for c in &ir.commands {
        s.push_str(&format!(
            "\n\n@dataclass(frozen=True)\nclass {name}:\n    \"\"\"Command: transfer {agg} from {frm} to {to}.\"\"\"\n    aggregate_id: str\n    quantity: Quantity\n    issued_by: Role\n",
            name = c.name,
            agg = c.aggregate,
            frm = c.from_entity,
            to = c.to_entity,
        ));
    }
    s.push_str("\n\n");
    if ir.commands.is_empty() {
        s.push_str("Command = object  # no commands\n");
    } else {
        let names: Vec<String> = ir.commands.iter().map(|c| c.name.clone()).collect();
        s.push_str(&format!("Command = Union[{}]\n", names.join(", ")));
    }
    s
}

fn events(ir: &DomainIr) -> String {
    let mut s = String::from(
        "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Union\n\nfrom .value_objects import Quantity\n",
    );
    for e in &ir.events {
        s.push_str(&format!(
            "\n\n@dataclass(frozen=True)\nclass {name}:\n    \"\"\"Event: {agg} transferred from {frm} to {to}.\"\"\"\n    aggregate_id: str\n    quantity: Quantity\n    occurred_at: str\n",
            name = e.name,
            agg = e.aggregate,
            frm = e.from_entity,
            to = e.to_entity,
        ));
    }
    s.push_str("\n\n");
    if ir.events.is_empty() {
        s.push_str("DomainEvent = object  # no events\n");
    } else {
        let names: Vec<String> = ir.events.iter().map(|e| e.name.clone()).collect();
        s.push_str(&format!("DomainEvent = Union[{}]\n", names.join(", ")));
    }
    s
}

fn aggregates(ir: &DomainIr) -> String {
    let mut s = String::from("from dataclasses import dataclass\n\n");
    let event_names: Vec<String> = ir.events.iter().map(|e| e.name.clone()).collect();
    if !event_names.is_empty() {
        s.push_str(&format!("from .events import {}\n", event_names.join(", ")));
    }
    s.push_str("from .roles import Role\nfrom .value_objects import Quantity\n");
    for agg in &ir.aggregates {
        s.push_str(&format!(
            "\n\n@dataclass\nclass {name}:\n    \"\"\"Aggregate root for resource '{res}' (unit: {unit}).\"\"\"\n    id: str\n    name: str\n",
            name = agg.name,
            res = agg.resource_name,
            unit = agg.unit
        ));
        for m in &agg.methods {
            let rationale = m
                .guard_checks
                .iter()
                .filter_map(|g| {
                    ir.errors
                        .iter()
                        .find(|e| e.name == g.error)
                        .and_then(|e| e.rationale.clone())
                })
                .collect::<Vec<_>>()
                .join("; ");
            let method_doc = if rationale.is_empty() {
                format!("Transfer to {}.", m.to_entity)
            } else {
                format!("Transfer to {}. {}", m.to_entity, rationale)
            };
            match &m.event {
                Some(ret) => {
                    s.push_str(&format!(
                        "    def {mname}(self, quantity: Quantity, issued_by: Role, occurred_at: str) -> {ret}:\n        \"\"\"{doc}\"\"\"\n",
                        mname = m.name, ret = ret, doc = method_doc
                    ));
                    for g in &m.guard_checks {
                        s.push_str(&format!("        self.{}()\n", g.check_method));
                    }
                    s.push_str(&format!(
                        "        return {ret}(self.id, quantity, occurred_at)\n",
                        ret = ret
                    ));
                }
                None => {
                    s.push_str(&format!(
                        "    def {mname}(self, quantity: Quantity, issued_by: Role) -> None:\n        \"\"\"{doc}\"\"\"\n",
                        mname = m.name, doc = method_doc
                    ));
                    for g in &m.guard_checks {
                        s.push_str(&format!("        self.{}()\n", g.check_method));
                    }
                    s.push_str("        return None\n");
                }
            }
        }
        // Guard hook methods (no-op in v1; the policy expression is not compiled).
        let mut seen: Vec<String> = Vec::new();
        for g in agg.methods.iter().flat_map(|m| m.guard_checks.iter()) {
            if seen.contains(&g.check_method) {
                continue;
            }
            seen.push(g.check_method.clone());
            let rationale = ir
                .errors
                .iter()
                .find(|e| e.name == g.error)
                .and_then(|e| e.rationale.clone())
                .unwrap_or_else(|| "Policy guard.".to_string());
            s.push_str(&format!(
                "\n    def {c}(self) -> None:\n        \"\"\"{rationale}\"\"\"\n        return None\n",
                c = g.check_method,
                rationale = rationale
            ));
        }
    }
    s
}

fn repositories(ir: &DomainIr) -> String {
    let mut s = String::from(
        "from __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import Optional\n\n",
    );
    let names: Vec<String> = ir.aggregates.iter().map(|a| a.name.clone()).collect();
    if !names.is_empty() {
        s.push_str(&format!(
            "from ..domain.aggregates import {}\n",
            names.join(", ")
        ));
    }
    for agg in &ir.aggregates {
        s.push_str(&format!(
            "\n\nclass {name}Repository(ABC):\n    \"\"\"Repository port for the {name} aggregate.\"\"\"\n\n    @abstractmethod\n    def get(self, id: str) -> Optional[{name}]:\n        ...\n\n    @abstractmethod\n    def save(self, aggregate: {name}) -> None:\n        ...\n",
            name = agg.name
        ));
    }
    s
}

fn bus(_ir: &DomainIr) -> String {
    "from __future__ import annotations\n\nfrom abc import ABC, abstractmethod\n\n\
from ..domain.commands import Command\n\
from ..domain.events import DomainEvent\n\n\n\
class EventBus(ABC):\n    \"\"\"Port: publishes domain events.\"\"\"\n\n    @abstractmethod\n    def publish(self, event: DomainEvent) -> None:\n        ...\n\n\n\
class CommandBus(ABC):\n    \"\"\"Port: dispatches domain commands.\"\"\"\n\n    @abstractmethod\n    def dispatch(self, command: Command) -> None:\n        ...\n"
    .to_string()
}

fn read_model(ir: &DomainIr) -> String {
    let mut s = String::from(
        "from __future__ import annotations\n\nfrom abc import ABC, abstractmethod\n\n",
    );
    if !ir.queries.is_empty() {
        s.push_str("from ..domain.value_objects import Quantity\n");
    }
    s.push_str("\n\n");
    s.push_str(&format!(
        "class {ns}ReadModel(ABC):\n    \"\"\"CQRS read model: query ports for derived metrics.\"\"\"\n",
        ns = ir.package_pascal
    ));
    for q in &ir.queries {
        let mut doc = format!("Metric '{}'", q.metric_name);
        if let Some(u) = &q.unit {
            doc.push_str(&format!(" (unit: {u})"));
        }
        if let Some(t) = &q.threshold {
            doc.push_str(&format!(", threshold: {t}"));
        }
        doc.push('.');
        s.push_str(&format!(
            "\n    @abstractmethod\n    def {mname}(self) -> Quantity:\n        \"\"\"{doc}\"\"\"\n        ...\n",
            mname = q.name,
            doc = doc
        ));
    }
    s
}

fn smoke_test(ir: &DomainIr) -> String {
    let pkg = &ir.package_slug;
    let mut imports = String::new();
    let mut checks: Vec<String> = Vec::new();

    for c in &ir.commands {
        imports.push_str(&format!(
            "from {pkg}_domain.domain.commands import {name}\n",
            pkg = pkg,
            name = c.name
        ));
        checks.push(format!(
            "        cmd = {name}(aggregate_id=\"sample\", quantity=Quantity(1.0, \"{unit}\"), issued_by=Role.{role})\n        self.assertEqual(cmd.aggregate_id, \"sample\")",
            name = c.name,
            unit = aggregate_unit(ir, &c.aggregate),
            role = ir.roles.first().cloned().unwrap_or_else(|| "Requester".to_string())
        ));
    }
    for e in &ir.events {
        imports.push_str(&format!(
            "from {pkg}_domain.domain.events import {name}\n",
            pkg = pkg,
            name = e.name
        ));
        checks.push(format!(
            "        ev = {name}(aggregate_id=\"sample\", quantity=Quantity(1.0, \"{unit}\"), occurred_at=\"now\")\n        self.assertEqual(ev.occurred_at, \"now\")",
            name = e.name,
            unit = aggregate_unit(ir, &e.aggregate),
        ));
    }
    for vo in &ir.value_objects {
        imports.push_str(&format!(
            "from {pkg}_domain.domain.errors import {err}\nfrom {pkg}_domain.domain.value_objects import {name}\n",
            pkg = pkg,
            err = vo.error_name,
            name = vo.name
        ));
        checks.push(format!(
            "        with self.assertRaises({err}):\n            {name}(\"bad\")",
            err = vo.error_name,
            name = vo.name
        ));
    }
    // Instance example: construct the entity from its instance fields.
    if let Some(inst) = ir.instances.first() {
        imports.push_str(&format!(
            "from {pkg}_domain.domain.entities import {ent}\n",
            pkg = pkg,
            ent = inst.entity
        ));
        let mut kwargs = vec![format!("id=\"{}\"", inst.name)];
        for (k, v) in &inst.fields {
            kwargs.push(format!("{k}={lit}", k = k, lit = py_str_lit(v)));
        }
        checks.push(format!(
            "        ex = {ent}({kwargs})\n        self.assertEqual(ex.id, \"{id}\")",
            ent = inst.entity,
            kwargs = kwargs.join(", "),
            id = inst.name
        ));
    }
    if !ir.roles.is_empty() {
        imports.push_str(&format!(
            "from {pkg}_domain.domain.roles import Role\n",
            pkg = pkg
        ));
    }
    imports.push_str(&format!(
        "from {pkg}_domain.domain.value_objects import Quantity\n",
        pkg = pkg
    ));

    let body = if checks.is_empty() {
        "        pass\n".to_string()
    } else {
        format!("{}\n", checks.join("\n"))
    };
    format!(
        "import unittest\n\n{imports}\n\nclass DomainSmokeTest(unittest.TestCase):\n    def test_constructs(self) -> None:\n{body}\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
        imports = imports,
        body = body,
    )
}

fn aggregate_unit(ir: &DomainIr, aggregate: &str) -> String {
    ir.aggregates
        .iter()
        .find(|a| a.name == aggregate)
        .map(|a| a.unit.clone())
        .unwrap_or_else(|| "units".to_string())
}

/// Quote a string literal for Python source.
fn py_str_lit(s: &str) -> String {
    format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}

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

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

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

    fn fixture_files() -> BTreeMap<String, String> {
        let src = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../fixtures/projection_cell/basic/model.sea"),
        )
        .expect("fixture");
        project(&src)
    }

    #[test]
    fn emits_expected_file_set() {
        let files = fixture_files();
        let keys: Vec<&str> = files.keys().map(|s| s.as_str()).collect();
        assert!(keys.contains(&"pyproject.toml"), "missing pyproject.toml");
        assert!(
            keys.contains(&"src/procurement_domain/domain/aggregates.py"),
            "missing aggregates"
        );
        assert!(
            keys.contains(&"src/procurement_domain/ports/repositories.py"),
            "missing repositories"
        );
        assert!(
            keys.contains(&"tests/test_domain_smoke.py"),
            "missing smoke"
        );
    }

    #[test]
    fn key_content_present() {
        let files = fixture_files();
        let repos = &files["src/procurement_domain/ports/repositories.py"];
        assert!(
            repos.contains("class PurchaseOrderRepository(ABC)"),
            "missing PurchaseOrderRepository"
        );
        let aggs = &files["src/procurement_domain/domain/aggregates.py"];
        assert!(aggs.contains("def transfer_to_supplier"), "missing method");
        let errs = &files["src/procurement_domain/domain/errors.py"];
        assert!(
            errs.contains("class RequireApprovalViolation(DomainError)"),
            "missing error"
        );
    }

    #[test]
    fn deterministic() {
        assert_eq!(fixture_files(), fixture_files());
    }

    #[test]
    fn no_third_party_runtime_deps() {
        let files = fixture_files();
        let pp = &files["pyproject.toml"];
        assert!(pp.contains("dependencies = []"), "must declare zero deps");
    }
}