use super::ir::{LearningPipelineIR, ZENML_PIP_SPEC, ZENML_TARGET_VERSION};
fn doc_safe(s: &str) -> String {
s.replace(['\n', '\r'], " ")
.replace('\\', "\\\\")
.replace("\"\"\"", "\\\"\\\"\\\"")
}
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,
)
}
fn label_list(labels: &[String]) -> String {
let items = labels
.iter()
.map(|l| format!("\"{}\"", l.replace('\\', "\\\\").replace('"', "\\\"")))
.collect::<Vec<_>>()
.join(", ");
format!("[{items}]")
}
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()
}
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",
);
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"),
));
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"),
));
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"),
));
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
}
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
}
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
}
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,
)
}
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}"))
}
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,
)
}