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
//! Lower a [`LearningPipelineIR`] to a runnable ZenML pipeline package.
//!
//! One producer for every artifact: the CLI, the language bindings, and the
//! tests all render through this module, so their output is byte-identical.
//! Output is deterministic — the IR is already sorted, and no wall-clock or
//! random data enters file contents (only the caller-supplied `created_at`).
//!
//! Generated Python imports only `zenml` and the Python standard library, so it
//! is import-clean and `ast.parse`-valid with `pip install zenml`. The pipeline
//! *definition* is emitted; DomainForge never runs training — that is the
//! user's compute on the user's ZenML stack. `run.py --dry-run` constructs the
//! pipeline object without executing it.

use super::ir::{LearningPipelineIR, ZENML_PIP_SPEC, ZENML_TARGET_VERSION};

/// Collapse embedded newlines (a docstring stays readable line-by-line) and
/// neutralize the two sequences that could break out of a `"""` docstring: a
/// backslash escape and a literal triple-quote.
fn doc_safe(s: &str) -> String {
    s.replace(['\n', '\r'], " ")
        .replace('\\', "\\\\")
        .replace("\"\"\"", "\\\"\\\"\\\"")
}

/// A Python `# ...` comment-safe rendering (no embedded newlines).
fn comment_safe(s: &str) -> String {
    s.replace(['\n', '\r'], " ")
}

fn header(ir: &LearningPipelineIR, what: &str) -> String {
    format!(
        "# Generated by DomainForge (`--format zenml`) from {}.\n\
         # {}\n\
         # Created: {}. Target ZenML API: {}. Do not edit by hand.\n",
        comment_safe(&ir.model_ref),
        comment_safe(what),
        comment_safe(&ir.created_at),
        ZENML_TARGET_VERSION,
    )
}

/// Render a Python list literal of string labels, e.g. `["allow", "deny"]`.
fn label_list(labels: &[String]) -> String {
    let items = labels
        .iter()
        .map(|l| format!("\"{}\"", l.replace('\\', "\\\\").replace('"', "\\\"")))
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{items}]")
}

/// Look up a step's deterministic output-artifact id by step name.
fn artifact_id(ir: &LearningPipelineIR, step: &str) -> String {
    ir.steps
        .iter()
        .find(|s| s.name == step)
        .map(|s| s.artifact_id.clone())
        .unwrap_or_default()
}

/// `steps.py`: the four `@step` functions (load_dataset → train_model →
/// evaluate_model → register_model). The training step is a documented,
/// deterministic majority-class baseline the user replaces with real training;
/// DomainForge emits the pipeline, not the user's compute. Step outputs are
/// named by deterministic artifact ids.
pub fn steps(ir: &LearningPipelineIR) -> String {
    let mut s = header(
        ir,
        "@step functions: load the referenced ai-learning dataset, train, evaluate, register.",
    );
    s.push_str(
        "import json\n\
         import os\n\
         from typing import Annotated\n\n\
         from zenml import step\n\n\n",
    );
    s.push_str(&format!(
        "# The closed set of decision labels the pipeline scores agreement over.\n\
         DECISION_LABELS = {labels}\n\
         # ai-learning dataset references (paths into the `--format ai-learning`\n\
         # output; the rows are REFERENCED, never copied).\n\
         DATASET_ROOT = {root:?}\n\
         TRAIN_REF = {train:?}\n\
         DEV_REF = {dev:?}\n\
         SOURCE_FAMILY = {family:?}\n\
         METRIC_NAME = {metric:?}\n\
         # Model version keyed to the source model hash: every run of this model\n\
         # groups under one ZenML model version.\n\
         MODEL_VERSION = {version:?}\n\
         PROMOTION_THRESHOLD = {threshold}\n\n\n",
        labels = label_list(&ir.decision_labels),
        root = ir.dataset.root,
        train = ir.dataset.train,
        dev = ir.dataset.dev,
        family = ir.dataset.family,
        metric = ir.metric_name,
        version = ir.model_version,
        threshold = ir.promotion_threshold,
    ));
    s.push_str(
        "def _user_question(record):\n\
         \x20   for message in record.get(\"messages\", []):\n\
         \x20       if message.get(\"role\") == \"user\":\n\
         \x20           return message.get(\"content\", \"\")\n\
         \x20   return \"\"\n\n\n\
         def _read_examples(path):\n\
         \x20   \"\"\"Build (question, decision) rows from an ai-learning LLM-dataset JSONL file.\n\n\
         \x20   The rows are REFERENCED, never copied: run `domainforge project --format\n\
         \x20   ai-learning` to produce them at the path recorded in zenml.config.json.\n\
         \x20   \"\"\"\n\
         \x20   rows = []\n\
         \x20   with open(path, \"r\", encoding=\"utf-8\") as handle:\n\
         \x20       for line in handle:\n\
         \x20           line = line.strip()\n\
         \x20           if not line:\n\
         \x20               continue\n\
         \x20           record = json.loads(line)\n\
         \x20           metadata = record.get(\"metadata\", {})\n\
         \x20           if metadata.get(\"family\") != SOURCE_FAMILY:\n\
         \x20               continue\n\
         \x20           label = metadata.get(\"label\")\n\
         \x20           if label is None:\n\
         \x20               continue\n\
         \x20           rows.append({\"question\": _user_question(record), \"decision\": label})\n\
         \x20   return rows\n\n\n",
    );
    // load_dataset
    s.push_str(&format!(
        "@step\n\
         def load_dataset() -> Annotated[dict, {load_art:?}]:\n\
         \x20   \"\"\"Load the referenced ai-learning train/dev splits (referenced, never copied).\"\"\"\n\
         \x20   base = os.path.join(os.path.dirname(__file__), DATASET_ROOT)\n\
         \x20   return {{\n\
         \x20       \"train\": _read_examples(os.path.join(base, TRAIN_REF)),\n\
         \x20       \"dev\": _read_examples(os.path.join(base, DEV_REF)),\n\
         \x20   }}\n\n\n",
        load_art = artifact_id(ir, "load_dataset"),
    ));
    // train_model
    s.push_str(&format!(
        "@step\n\
         def train_model(dataset: dict) -> Annotated[dict, {train_art:?}]:\n\
         \x20   \"\"\"Fit a deterministic majority-class baseline over the train split.\n\n\
         \x20   REPLACE THIS with your real training. DomainForge emits the pipeline\n\
         \x20   DEFINITION and a runnable baseline; the actual model training is your\n\
         \x20   compute on your ZenML stack, not DomainForge's.\n\
         \x20   \"\"\"\n\
         \x20   labels = [row[\"decision\"] for row in dataset[\"train\"]]\n\
         \x20   if labels:\n\
         \x20       prediction = max(sorted(set(labels)), key=labels.count)\n\
         \x20   else:\n\
         \x20       prediction = \"unknown\"\n\
         \x20   return {{\"strategy\": \"majority_class\", \"prediction\": prediction, \"model_version\": MODEL_VERSION}}\n\n\n",
        train_art = artifact_id(ir, "train_model"),
    ));
    // evaluate_model
    s.push_str(&format!(
        "@step\n\
         def evaluate_model(dataset: dict, model: dict) -> Annotated[dict, {eval_art:?}]:\n\
         \x20   \"\"\"Score decision-label agreement of the trained model on the dev split.\"\"\"\n\
         \x20   dev = dataset[\"dev\"]\n\
         \x20   prediction = model[\"prediction\"]\n\
         \x20   correct = sum(1 for row in dev if row[\"decision\"] == prediction)\n\
         \x20   score = correct / len(dev) if dev else 0.0\n\
         \x20   return {{METRIC_NAME: score, \"evaluated\": len(dev)}}\n\n\n",
        eval_art = artifact_id(ir, "evaluate_model"),
    ));
    // register_model
    s.push_str(&format!(
        "@step\n\
         def register_model(model: dict, metrics: dict) -> Annotated[dict, {reg_art:?}]:\n\
         \x20   \"\"\"Apply the promotion gate and carry the metric back into the model version.\n\n\
         \x20   Promotion succeeds only when the decision-agreement score meets the\n\
         \x20   declared threshold; the returned artifact records the outcome so the\n\
         \x20   metric flows back into the run's model version (closing the loop).\n\
         \x20   \"\"\"\n\
         \x20   score = metrics[METRIC_NAME]\n\
         \x20   promoted = score >= PROMOTION_THRESHOLD\n\
         \x20   return {{\n\
         \x20       \"model_version\": model[\"model_version\"],\n\
         \x20       \"promoted\": promoted,\n\
         \x20       \"promotion_threshold\": PROMOTION_THRESHOLD,\n\
         \x20       METRIC_NAME: score,\n\
         \x20   }}\n",
        reg_art = artifact_id(ir, "register_model"),
    ));
    s
}

/// `pipeline.py`: the `@pipeline` function wiring the four steps into the DAG,
/// versioned under a ZenML `Model` whose version is keyed to the model hash.
pub fn pipeline(ir: &LearningPipelineIR) -> String {
    let mut policies = String::new();
    if ir.policy_lines.is_empty() {
        policies.push_str("    (no authority policies were declared)\n");
    } else {
        for line in &ir.policy_lines {
            policies.push_str(&format!("    - {}\n", doc_safe(line)));
        }
    }

    let mut s = header(
        ir,
        "@pipeline DAG: load_dataset -> train_model -> evaluate_model -> register_model.",
    );
    s.push_str(
        "from zenml import Model, pipeline\n\n\
         from steps import evaluate_model, load_dataset, register_model, train_model\n\n\n",
    );
    s.push_str(&format!(
        "# The ZenML Model the runs version under. The VERSION is keyed to the\n\
         # source model hash, so every run of this domain model groups together.\n\
         MODEL = Model(name={model_name:?}, version={model_version:?})\n\n\n",
        model_name = ir.model_name,
        model_version = ir.model_version,
    ));
    s.push_str(&format!(
        "@pipeline(model=MODEL, enable_cache=False)\n\
         def {pipe}():\n\
         \x20   \"\"\"Authority-decision learning loop for the \"{model}\" domain model.\n\n\
         \x20   Consumes the ai-learning dataset this model emits, trains and\n\
         \x20   evaluates a decision model, and registers it under a model version\n\
         \x20   keyed to the model hash. Governing policies:\n\
         {policies}\
         \x20   \"\"\"\n\
         \x20   dataset = load_dataset()\n\
         \x20   model = train_model(dataset)\n\
         \x20   metrics = evaluate_model(dataset, model)\n\
         \x20   return register_model(model, metrics)\n",
        pipe = ir.pipeline_name,
        model = doc_safe(&ir.model_ref),
        policies = policies,
    ));
    s
}

/// `run.py`: construct or run the pipeline. `--dry-run` (the default-safe path)
/// constructs the pipeline object and prints its name WITHOUT executing it, so
/// it works with no ZenML stack configured.
pub fn run(ir: &LearningPipelineIR) -> String {
    let mut s = header(
        ir,
        "Entry point. `python run.py --dry-run` constructs the pipeline without executing it.",
    );
    s.push_str(&format!(
        "import argparse\n\n\
         from pipeline import {pipe}\n\n\n\
         def main():\n\
         \x20   parser = argparse.ArgumentParser(description=\"Run the DomainForge ZenML learning pipeline.\")\n\
         \x20   parser.add_argument(\n\
         \x20       \"--dry-run\",\n\
         \x20       action=\"store_true\",\n\
         \x20       help=\"Construct the pipeline object without executing it (no ZenML stack needed).\",\n\
         \x20   )\n\
         \x20   args = parser.parse_args()\n\
         \x20   pipeline_def = {pipe}\n\
         \x20   if args.dry_run:\n\
         \x20       print(\"Constructed ZenML pipeline:\", pipeline_def.name)\n\
         \x20       return\n\
         \x20   # Executing needs a configured ZenML stack; this is your compute.\n\
         \x20   pipeline_def()\n\n\n\
         if __name__ == \"__main__\":\n\
         \x20   main()\n",
        pipe = ir.pipeline_name,
    ));
    s
}

/// `requirements.txt`: pins ZenML to the targeted API line (the `LEAN_TOOLCHAIN`
/// precedent — the projection targets a pinned version).
pub fn requirements(ir: &LearningPipelineIR) -> String {
    format!(
        "# Generated by DomainForge (`--format zenml`) from {}.\n\
         # Pinned to the ZenML API line the emitted pipeline targets.\n\
         {}\n",
        comment_safe(&ir.model_ref),
        ZENML_PIP_SPEC,
    )
}

/// `zenml.config.json`: the machine-readable stamp — pipeline id, dataset
/// references (paths into the ai-learning output, never copies), the steps and
/// their DAG edges, the metric + promotion gate, the model-version key, and the
/// provenance carried verbatim from the ai-learning family.
pub fn config(ir: &LearningPipelineIR) -> Result<String, String> {
    let steps: Vec<serde_json::Value> = ir
        .steps
        .iter()
        .map(|s| {
            serde_json::json!({
                "name": s.name,
                "inputs": s.inputs,
                "artifact_id": s.artifact_id,
            })
        })
        .collect();
    let edges: Vec<serde_json::Value> = ir
        .dag_edges()
        .into_iter()
        .map(|(from, to)| serde_json::json!({ "from": from, "to": to }))
        .collect();
    let value = serde_json::json!({
        "pipeline_id": ir.pipeline_id,
        "pipeline_name": ir.pipeline_name,
        "target_zenml_version": ZENML_TARGET_VERSION,
        "generator_version": ir.generator_version,
        "created_at": ir.created_at,
        "model": {
            "name": ir.model_name,
            "version": ir.model_version,
            "version_keyed_to": "source_model_hash",
        },
        "steps": steps,
        "dag_edges": edges,
        "metric": {
            "name": ir.metric_name,
            "kind": "decision_label_agreement",
        },
        "promotion_gate": {
            "metric": ir.metric_name,
            "threshold": ir.promotion_threshold,
        },
        "decision_labels": ir.decision_labels,
        "dataset": {
            "root": ir.dataset.root,
            "train": ir.dataset.train,
            "dev": ir.dataset.dev,
            "family": ir.dataset.family,
            "note": "Paths reference the `--format ai-learning` output; generate it first. \
                     DomainForge never copies example data.",
        },
        "provenance": ir.provenance,
    });
    serde_json::to_string_pretty(&value)
        .map(|s| s + "\n")
        .map_err(|e| format!("zenml config serialization failed: {e}"))
}

/// `README.md`: package layout and the scope boundary the plan requires.
pub fn readme(ir: &LearningPipelineIR) -> String {
    let mut policies = String::new();
    if ir.policy_lines.is_empty() {
        policies.push_str("- (no authority policies were declared)\n");
    } else {
        for line in &ir.policy_lines {
            policies.push_str(&format!("- {}\n", line));
        }
    }
    format!(
        "# DomainForge ZenML learning pipeline\n\n\
         Generated from `{model}` at {created} (target ZenML API `{version}`).\n\n\
         This package turns the model's authority policies into a runnable\n\
         [ZenML](https://zenml.io/) pipeline that closes the learning loop the\n\
         ai-learning datasets open: dataset emission → a pipeline that consumes\n\
         it → metrics carried back into the run's model version. DomainForge\n\
         emits the *pipeline definition* only: it does **not** run training.\n\
         Training, evaluation, and promotion happen when **you** run the emitted\n\
         pipeline on **your** ZenML stack.\n\n\
         ## Layout\n\n\
         - `pipeline.py` — the `{pipe}` `@pipeline` wiring `load_dataset ->\n  \
         train_model -> evaluate_model -> register_model`, versioned under a\n  \
         ZenML `Model` whose version (`{mversion}`) is keyed to the model hash.\n\
         - `steps.py` — the four `@step` functions. `train_model` is a\n  \
         deterministic majority-class baseline you REPLACE with real training.\n\
         - `run.py` — `python run.py --dry-run` constructs the pipeline without\n  \
         executing it; `python run.py` runs it on your configured stack.\n\
         - `requirements.txt` — pins ZenML to `{pin}`.\n\
         - `zenml.config.json` — pipeline id, dataset references, steps + DAG\n  \
         edges, metric, promotion gate, model-version key, and provenance.\n\n\
         ## Governing policies\n\n\
         {policies}\n\
         ## Examples are referenced, never copied\n\n\
         `zenml.config.json` records the dataset paths under `dataset.root`\n\
         (default `{root}`): `{train}` (train) and `{dev}` (dev). These are the\n\
         exact files `domainforge project --format ai-learning` emits for the\n\
         same model, so the pipeline's inputs and the LLM dataset can never\n\
         diverge. Generate them first:\n\n\
         ```bash\n\
         domainforge project --format ai-learning --recipe <recipe.json> model.sea {root}\n\
         ```\n\n\
         ## Scope boundary\n\n\
         DomainForge emits the pipeline definition and a runnable baseline. The\n\
         real training, the evaluation on your data, and the promotion decision\n\
         are **your** compute on **your** ZenML stack — the same posture as the\n\
         DSPy projection's `optimize.py`. The promotion gate\n\
         (`{metric} >= {threshold}`) is enforced inside the emitted\n\
         `register_model` step when you run the pipeline.\n\n\
         Provenance: pipeline id `{pid}`, source model hash `{hash}`, generator\n\
         `domainforge {gen}`.\n",
        model = ir.model_ref,
        created = ir.created_at,
        version = ZENML_TARGET_VERSION,
        pipe = ir.pipeline_name,
        mversion = ir.model_version,
        pin = ZENML_PIP_SPEC,
        policies = policies,
        root = ir.dataset.root,
        train = ir.dataset.train,
        dev = ir.dataset.dev,
        metric = ir.metric_name,
        threshold = ir.promotion_threshold,
        pid = ir.pipeline_id,
        hash = ir.model_hash,
        gen = ir.generator_version,
    )
}