Skip to main content

domainforge_core/projection/devbox/
mod.rs

1//! Devbox activation projection: a SEA model becomes a [`devbox.json`] that
2//! pre-loads the domain manifest (namespace, entities, resources, flows) as
3//! environment variables and prints a banner on shell entry, so a developer
4//! running `devbox shell` lands in a reproducible environment that already
5//! knows what architecture it is hosting.
6//!
7//! `packages` is intentionally empty: the SEA model declares *what* exists in
8//! a domain, not the language/tooling needed to build it (that is
9//! stack-specific and inventing nix package names from `Buyer`/`Supplier`
10//! would make the file fail to install). Developers add the packages their
11//! stack needs on top of this manifest.
12//!
13//! Output is a single `devbox.json` (JSONC; Devbox parses the leading `//`
14//! comment). Serialization goes through `serde_json`'s sorted `Map`, so the
15//! output is byte-identical run-to-run for a fixed model.
16//!
17//! [`devbox.json`]: https://www.jetify.com/devbox/docs/configuration/
18
19use crate::graph::Graph;
20use crate::projection::flows::{collect_flows, model_namespace};
21use crate::projection::sink::ArtifactSink;
22use serde_json::{json, Map, Value};
23use std::collections::BTreeMap;
24
25/// The single emitted artifact's relative path.
26pub const OUTPUT_FILE: &str = "devbox.json";
27
28/// Emit the Devbox config into `sink`; returns the emitted relative paths.
29pub fn emit(
30    graph: &Graph,
31    model_ref: &str,
32    created_at: Option<String>,
33    sink: &mut ArtifactSink,
34) -> Result<Vec<String>, String> {
35    let created_at = created_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
36    let spec = build_spec(graph, model_ref, &created_at)?;
37    let mut body = format!(
38        "// devbox.json projected by DomainForge from {model_ref} at {created_at}.\n\
39         // Activation projection: a reproducible shell pre-loaded with the domain\n\
40         // manifest as env vars (namespace, entities, resources, flows) plus a\n\
41         // banner on entry. `packages` is intentionally empty — the SEA model\n\
42         // declares what exists, not the language/tooling to build it; add the\n\
43         // nix packages your stack needs.\n"
44    );
45    body.push_str(
46        &serde_json::to_string_pretty(&spec)
47            .map_err(|e| format!("failed to serialize devbox document: {e}"))?,
48    );
49    body.push('\n');
50    sink.write(OUTPUT_FILE, &body)?;
51    Ok(vec![OUTPUT_FILE.to_string()])
52}
53
54/// Binding surface: string in, path→content map out, no filesystem.
55pub fn project_devbox_in_memory(
56    graph: &Graph,
57    model_ref: &str,
58    created_at: Option<String>,
59) -> Result<BTreeMap<String, String>, String> {
60    let mut map = BTreeMap::new();
61    let mut sink = ArtifactSink::Memory {
62        prefix: String::new(),
63        map: &mut map,
64    };
65    emit(graph, model_ref, created_at, &mut sink)?;
66    Ok(map)
67}
68
69/// Build the devbox.json value.
70fn build_spec(graph: &Graph, model_ref: &str, _created_at: &str) -> Result<Value, String> {
71    // ponytail: model `@version` is parsed into the AST but not carried onto
72    // Graph; surfacing it is a cross-cutting graph change, out of scope here.
73    let ns = model_namespace(graph)?; // M5: errors on multi-namespace
74
75    let mut entities: Vec<String> = graph
76        .all_entities()
77        .iter()
78        .map(|e| e.name().to_string())
79        .collect();
80    entities.sort();
81    let mut resources: Vec<String> = graph
82        .all_resources()
83        .iter()
84        .map(|r| r.name().to_string())
85        .collect();
86    resources.sort();
87
88    // M4: use the shared flow resolver (loud dangling-ref policy).
89    let flows = collect_flows(graph)?;
90    let mut flow_strs: Vec<String> = flows
91        .iter()
92        .map(|f| format!("{}:{}->{}", f.resource, f.from, f.to))
93        .collect();
94
95    // serde_json::Map is BTreeMap-backed (no preserve_order), so env keys are
96    // emitted in sorted order regardless of insertion order.
97    let mut env: Map<String, Value> = Map::new();
98    env.insert("DOMAINFORGE_MODEL".to_string(), json!(model_ref));
99    env.insert("DOMAINFORGE_NAMESPACE".to_string(), json!(ns));
100    env.insert(
101        "DOMAINFORGE_ENTITIES".to_string(),
102        json!(entities.join(",")),
103    );
104    env.insert(
105        "DOMAINFORGE_RESOURCES".to_string(),
106        json!(resources.join(",")),
107    );
108    env.insert("DOMAINFORGE_FLOWS".to_string(), json!(flow_strs.join(",")));
109
110    // M2: the banner must not interpolate the namespace into a shell command
111    // (shell injection). Use the env var instead — it's already exported.
112    let init_hook = json!([
113        "echo \"DomainForge: $DOMAINFORGE_NAMESPACE namespace\"".to_string(),
114        "echo \"Entities: $DOMAINFORGE_ENTITIES\"".to_string(),
115        "echo \"Resources: $DOMAINFORGE_RESOURCES\"".to_string(),
116    ]);
117
118    let _ = &mut flow_strs; // silence unused-mut if flows is empty
119
120    Ok(json!({
121        "packages": [],
122        "env": env,
123        "shell": {
124            "init_hook": init_hook,
125            "scripts": {
126                "domainforge-context": "echo \"Namespace: $DOMAINFORGE_NAMESPACE\"; echo \"Model: $DOMAINFORGE_MODEL\"; echo \"Entities: $DOMAINFORGE_ENTITIES\"; echo \"Resources: $DOMAINFORGE_RESOURCES\"; echo \"Flows: $DOMAINFORGE_FLOWS\""
127            }
128        }
129    }))
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::parser::parse_to_graph;
136
137    const FIXED_TS: &str = "2026-07-02T00:00:00+00:00";
138
139    const SOURCE: &str = r#"
140@namespace "procurement"
141
142Entity "Buyer" in procurement
143Entity "Supplier" in procurement
144Resource "PurchaseOrder" units in procurement
145
146Flow "PurchaseOrder" from "Buyer" to "Supplier" quantity 1
147"#;
148
149    fn project(source: &str) -> BTreeMap<String, String> {
150        let graph = parse_to_graph(source).expect("fixture parses");
151        project_devbox_in_memory(&graph, "test.sea", Some(FIXED_TS.to_string()))
152            .expect("projection succeeds")
153    }
154
155    fn doc(files: &BTreeMap<String, String>) -> Value {
156        let body = &files["devbox.json"];
157        let lines: Vec<&str> = body.lines().collect();
158        let start = lines
159            .iter()
160            .position(|l| l.trim_start().starts_with('{'))
161            .unwrap();
162        serde_json::from_str(&lines[start..].join("\n")).expect("parses as JSON")
163    }
164
165    #[test]
166    fn emits_single_devbox_artifact() {
167        let files = project(SOURCE);
168        assert_eq!(files.keys().collect::<Vec<_>>(), vec!["devbox.json"]);
169    }
170
171    #[test]
172    fn document_is_a_valid_devbox_manifest() {
173        let files = project(SOURCE);
174        let d = doc(&files);
175        assert_eq!(d["packages"].as_array().unwrap(), &Vec::<Value>::new());
176        let env = d["env"].as_object().expect("env is an object");
177        assert_eq!(env["DOMAINFORGE_NAMESPACE"], "procurement");
178        assert_eq!(env["DOMAINFORGE_MODEL"], "test.sea");
179        assert_eq!(env["DOMAINFORGE_ENTITIES"], "Buyer,Supplier");
180        assert_eq!(env["DOMAINFORGE_RESOURCES"], "PurchaseOrder");
181        assert_eq!(env["DOMAINFORGE_FLOWS"], "PurchaseOrder:Buyer->Supplier");
182        let hook = d["shell"]["init_hook"]
183            .as_array()
184            .expect("init_hook is an array");
185        assert!(hook.len() >= 3);
186        // M2: banner must use the env var, not interpolate the namespace.
187        let banner = hook[0].as_str().expect("banner is a string");
188        assert!(
189            banner.contains("$DOMAINFORGE_NAMESPACE"),
190            "banner must not interpolate namespace directly (M2 shell injection): {banner}"
191        );
192        assert!(
193            !banner.contains("{ns}") && !banner.contains("procurement"),
194            "banner must not contain the raw namespace value (M2): {banner}"
195        );
196        let script = d["shell"]["scripts"]["domainforge-context"]
197            .as_str()
198            .expect("context script present");
199        assert!(script.contains("$DOMAINFORGE_NAMESPACE"));
200    }
201
202    #[test]
203    fn output_is_deterministic() {
204        assert_eq!(project(SOURCE), project(SOURCE));
205    }
206
207    #[test]
208    fn empty_model_emits_default_namespace_and_empty_lists() {
209        let files = project("@namespace \"empty\"\n");
210        let d = doc(&files);
211        assert_eq!(d["env"]["DOMAINFORGE_NAMESPACE"], "default");
212        assert_eq!(d["env"]["DOMAINFORGE_ENTITIES"], "");
213        assert_eq!(d["env"]["DOMAINFORGE_RESOURCES"], "");
214        assert_eq!(d["env"]["DOMAINFORGE_FLOWS"], "");
215        assert_eq!(d["packages"].as_array().unwrap().len(), 0);
216    }
217}