Skip to main content

domainforge_core/projection/cell/
mod.rs

1//! Cell environment projection: `.sea` -> Cell IR -> {Devbox, Mise,
2//! dependency-set, sandbox/network, authority, evidence, `cell.lock`}.
3//!
4//! Renderers only translate `ir::CellIr`; all semantics are decided once in
5//! `ir::CellIr::build` (see that module's doc comment for the documented
6//! deviation from the plan's Graph-centric architecture: this projection
7//! reads the parsed `Ast` directly rather than `Graph`, because none of its
8//! ten new declaration kinds are consumed by any other projection).
9
10pub mod authority;
11pub mod deps;
12pub mod devbox;
13pub mod evidence;
14pub mod ir;
15pub mod lock;
16pub mod mise;
17pub mod network;
18pub mod overrides;
19pub mod profiles;
20pub mod sandbox;
21
22use crate::formatter::{format as format_source, FormatConfig};
23use crate::parser::ast::Ast;
24use crate::projection::sink::ArtifactSink;
25use ir::CellIr;
26use overrides::CellOverrides;
27use serde_json::json;
28use std::collections::BTreeMap;
29use std::path::Path;
30
31/// Which component directories `--only` selects. The IR and `cell.lock`
32/// always cover every category regardless of this filter — `--only` is a
33/// fast-iteration UX convenience, not a semantic subset.
34#[derive(Debug, Clone, Copy)]
35pub struct CellComponents {
36    pub devbox: bool,
37    pub mise: bool,
38    pub dependencies: bool,
39    pub sandbox: bool,
40    pub authority: bool,
41    pub evidence: bool,
42}
43
44impl Default for CellComponents {
45    fn default() -> Self {
46        CellComponents {
47            devbox: true,
48            mise: true,
49            dependencies: true,
50            sandbox: true,
51            authority: true,
52            evidence: true,
53        }
54    }
55}
56
57impl CellComponents {
58    /// Parse a comma-separated `--only` value. Unknown component names fail
59    /// closed with the list of accepted names.
60    pub fn parse_only(spec: &str) -> Result<Self, String> {
61        let mut c = CellComponents {
62            devbox: false,
63            mise: false,
64            dependencies: false,
65            sandbox: false,
66            authority: false,
67            evidence: false,
68        };
69        for part in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
70            match part {
71                "devbox" => c.devbox = true,
72                "mise" => c.mise = true,
73                "dependencies" => c.dependencies = true,
74                "sandbox" => c.sandbox = true,
75                "authority" => c.authority = true,
76                "evidence" => c.evidence = true,
77                other => {
78                    return Err(format!(
79                        "unknown --only component '{other}'; expected one of: devbox, mise, dependencies, sandbox, authority, evidence"
80                    ))
81                }
82            }
83        }
84        Ok(c)
85    }
86}
87
88/// Render the full cell-environment projection into `sink`. `source_dir` is
89/// the directory containing the `.sea` file, used to resolve
90/// `DependencySet` lockfile paths for hashing. Pass `None` for in-memory /
91/// binding callers (lockfile hashing is skipped and `lockfile_sha256` is
92/// emitted as null); pass `Some(dir)` from filesystem-backed CLI callers.
93#[allow(clippy::too_many_arguments)]
94pub fn emit(
95    ast: &Ast,
96    source: &str,
97    model_ref: &str,
98    source_dir: Option<&Path>,
99    created_at: Option<String>,
100    overrides: Option<&CellOverrides>,
101    overrides_source: Option<&str>,
102    components: &CellComponents,
103    sink: &mut ArtifactSink,
104) -> Result<Vec<String>, String> {
105    let created_at = created_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
106    let ir = CellIr::build(ast, model_ref, &created_at, overrides)?;
107
108    let canonical_source = format_source(source, FormatConfig::default())
109        .map_err(|e| format!("failed to canonicalize source for cell.lock hashing: {e}"))?;
110
111    let mut files: BTreeMap<String, String> = BTreeMap::new();
112    if components.devbox {
113        files.extend(devbox::render(&ir));
114    }
115    if components.mise {
116        files.extend(mise::render(&ir));
117    }
118    if components.dependencies && !ir.dependency_sets.is_empty() {
119        files.extend(deps::render(&ir, source_dir)?);
120    }
121    if components.sandbox {
122        files.extend(sandbox::render(&ir));
123        files.extend(network::render(&ir));
124    }
125    if components.authority {
126        files.extend(authority::render(&ir));
127    }
128    if components.evidence {
129        files.extend(evidence::render(&ir));
130    }
131
132    files.insert(
133        "semantic/cell-ir.json".to_string(),
134        format!("{}\n", serde_json::to_string_pretty(&ir).unwrap()),
135    );
136    files.insert(
137        "semantic/canonical-model.json".to_string(),
138        format!(
139            "{}\n",
140            serde_json::to_string_pretty(&json!({
141                "model_ref": model_ref,
142                "namespace": ir.identity.namespace,
143                "canonical_source": canonical_source,
144            }))
145            .unwrap()
146        ),
147    );
148
149    // Computed from `files` before insertion, so every other emitted file is
150    // captured by construction — there is no code path that can produce a
151    // file the lock doesn't hash (the plan's CELL030 concern).
152    let lock_doc = lock::build(
153        &ir,
154        &created_at,
155        &canonical_source,
156        overrides_source,
157        &files,
158    );
159    files.insert("cell.lock".to_string(), lock_doc);
160    files.insert("README.md".to_string(), build_readme(&ir, &files));
161
162    let mut written = Vec::new();
163    for (path, content) in &files {
164        sink.write(path, content)?;
165        written.push(path.clone());
166    }
167    Ok(written)
168}
169
170/// Binding surface: string in, path->content map out, no filesystem (mirrors
171/// `devbox::project_devbox_in_memory`).
172pub fn project_cell_in_memory(
173    source: &str,
174    model_ref: &str,
175    created_at: Option<String>,
176    overrides_source: Option<&str>,
177    only: Option<&str>,
178) -> Result<BTreeMap<String, String>, String> {
179    let ast = crate::parser::parse(source).map_err(|e| format!("parse failed: {e}"))?;
180    let overrides = overrides_source.map(overrides::parse).transpose()?;
181    let components = match only {
182        Some(spec) => CellComponents::parse_only(spec)?,
183        None => CellComponents::default(),
184    };
185    let mut map = BTreeMap::new();
186    let mut sink = ArtifactSink::Memory {
187        prefix: String::new(),
188        map: &mut map,
189    };
190    emit(
191        &ast,
192        source,
193        model_ref,
194        None,
195        created_at,
196        overrides.as_ref(),
197        overrides_source,
198        &components,
199        &mut sink,
200    )?;
201    Ok(map)
202}
203
204fn build_readme(ir: &CellIr, files: &BTreeMap<String, String>) -> String {
205    let mut file_list: Vec<&String> = files.keys().collect();
206    file_list.sort();
207    let mut body = format!(
208        "# {} — cell environment\n\n\
209         Projected from a DomainForge `.sea` Cell declaration using profile \
210         `{}` (v{}).\n\n\
211         ## Generated files\n\n",
212        ir.identity.name, ir.profile_id, ir.profile_version
213    );
214    for f in file_list {
215        body.push_str(&format!("- `{f}`\n"));
216    }
217    body.push_str(
218        "\n## Next steps\n\n\
219         ```bash\n\
220         devbox shell\n\
221         mise install\n\
222         mise run prove-environment\n\
223         ```\n",
224    );
225    body
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    const FIXED_TS: &str = "2026-07-11T00:00:00+00:00";
233
234    const SOURCE: &str = r#"
235@namespace "godspeed.cells.repair"
236@version "1.0.0"
237@owner "godspeed-platform"
238
239Cell "RepairAgent"
240    @architecture "x86_64"
241    @network_default "deny"
242    @runtime_user "agent"
243    @profile "python-agent-v1"
244
245SystemDependency "git" version "2.45"
246SystemDependency "pkg-config"
247
248Runtime "python" version "3.13"
249
250Tool "uv" version "0.9"
251
252DependencySet "python-application"
253    @ecosystem "python"
254    @manifest "pyproject.toml"
255    @lockfile "uv.lock"
256    @install "uv sync --frozen"
257    @mutation "escalate"
258
259Mount "workspace"
260    @source "."
261    @target "/workspace"
262    @mode "read-write"
263
264Endpoint "package-mirror"
265    @host "pypi.godspeed.internal"
266    @port "443"
267    @protocol "https"
268
269NetworkFlow "resolve-python-packages" from "RepairAgent" to "package-mirror"
270    @operation "read"
271
272Credential "package-mirror-token"
273    @provider "broker"
274    @scope "package-mirror:read"
275    @delivery "ephemeral"
276
277Policy dependency_files_immutable per Constraint Prohibition priority 5
278    @rationale "Agents may not modify dependency manifests or lockfiles without escalation."
279    as: true
280
281Metric "environment-proof" as: count(entities) >= 0
282"#;
283
284    fn project(source: &str) -> BTreeMap<String, String> {
285        project_cell_in_memory(
286            source,
287            "repair-agent/model.sea",
288            Some(FIXED_TS.to_string()),
289            None,
290            None,
291        )
292        .expect("projection succeeds")
293    }
294
295    #[test]
296    fn emits_the_documented_tree() {
297        let files = project(SOURCE);
298        for expected in [
299            "devbox/devbox.json",
300            "devbox/projection-manifest.json",
301            "mise/mise.toml",
302            "mise/projection-manifest.json",
303            "dependencies/dependency-sets.json",
304            "sandbox/template.json",
305            "sandbox/resources.json",
306            "sandbox/mounts.json",
307            "sandbox/network.json",
308            "sandbox/lifecycle.json",
309            "authority/dependency-mutation-policy.json",
310            "authority/runtime-upgrade-policy.json",
311            "authority/credential-contracts.json",
312            "evidence/environment-proof-contract.json",
313            "evidence/event-schema.json",
314            "semantic/cell-ir.json",
315            "semantic/canonical-model.json",
316            "cell.lock",
317            "README.md",
318        ] {
319            assert!(files.contains_key(expected), "missing {expected}");
320        }
321    }
322
323    #[test]
324    fn devbox_has_only_os_dependencies() {
325        let files = project(SOURCE);
326        let doc: serde_json::Value = extract_json(&files["devbox/devbox.json"]);
327        let packages = doc["packages"].as_array().unwrap();
328        let names: Vec<&str> = packages.iter().map(|p| p.as_str().unwrap()).collect();
329        assert!(names.iter().any(|p| p.starts_with("git")));
330        assert!(names.iter().any(|p| p.starts_with("pkg-config")));
331        assert!(!names.iter().any(|p| p.starts_with("python")));
332        assert!(!names.iter().any(|p| p.starts_with("uv")));
333    }
334
335    #[test]
336    fn mise_has_only_runtime_and_tools() {
337        let files = project(SOURCE);
338        let toml = &files["mise/mise.toml"];
339        assert!(toml.contains("python = \"3.13\""));
340        assert!(toml.contains("uv = \"0.9\""));
341        assert!(!toml.contains("git ="));
342    }
343
344    #[test]
345    fn dependency_set_references_native_files() {
346        let files = project(SOURCE);
347        let doc: serde_json::Value = extract_json(&files["dependencies/dependency-sets.json"]);
348        let set = &doc["dependency_sets"]["python-application"];
349        assert_eq!(set["manifest"], "pyproject.toml");
350        assert_eq!(set["lockfile"], "uv.lock");
351    }
352
353    #[test]
354    fn sandbox_is_deny_by_default() {
355        let files = project(SOURCE);
356        let doc: serde_json::Value = extract_json(&files["sandbox/template.json"]);
357        assert_eq!(doc["network_default"], "deny");
358        assert_ne!(doc["runtime_user"], "root");
359    }
360
361    #[test]
362    fn only_declared_endpoint_appears_in_egress() {
363        let files = project(SOURCE);
364        let doc: serde_json::Value = extract_json(&files["sandbox/network.json"]);
365        let endpoints = doc["endpoints"].as_array().unwrap();
366        assert_eq!(endpoints.len(), 1);
367        assert_eq!(endpoints[0]["name"], "package-mirror");
368    }
369
370    #[test]
371    fn no_credential_value_in_any_output() {
372        let files = project(SOURCE);
373        for (path, content) in &files {
374            assert!(
375                !content.contains("ephemeral-secret-value"),
376                "unexpected secret literal in {path}"
377            );
378        }
379        let doc: serde_json::Value = extract_json(&files["authority/credential-contracts.json"]);
380        let cred = &doc["credentials"][0];
381        assert_eq!(cred["scope"], "package-mirror:read");
382        assert!(cred.get("value").is_none());
383    }
384
385    #[test]
386    fn repeated_generation_is_byte_identical() {
387        assert_eq!(project(SOURCE), project(SOURCE));
388    }
389
390    #[test]
391    fn missing_cell_declaration_fails_closed() {
392        let err = project_cell_in_memory(
393            "@namespace \"x\"\nEntity \"Foo\"\n",
394            "x.sea",
395            Some(FIXED_TS.to_string()),
396            None,
397            None,
398        )
399        .unwrap_err();
400        assert!(err.starts_with("CELL002"), "{err}");
401    }
402
403    #[test]
404    fn unknown_profile_fails_closed() {
405        let src = "Cell \"X\"\n    @profile \"nonexistent-v1\"\n";
406        let err = project_cell_in_memory(src, "x.sea", Some(FIXED_TS.to_string()), None, None)
407            .unwrap_err();
408        assert!(err.starts_with("CELL001"), "{err}");
409    }
410
411    #[test]
412    fn undeclared_network_flow_endpoint_fails_closed() {
413        let src = r#"
414Cell "X"
415    @profile "python-agent-v1"
416NetworkFlow "bad" from "X" to "nowhere"
417"#;
418        let err = project_cell_in_memory(src, "x.sea", Some(FIXED_TS.to_string()), None, None)
419            .unwrap_err();
420        assert!(err.starts_with("CELL020"), "{err}");
421    }
422
423    #[test]
424    fn only_filters_component_directories() {
425        let files = project_cell_in_memory(
426            SOURCE,
427            "repair-agent/model.sea",
428            Some(FIXED_TS.to_string()),
429            None,
430            Some("devbox"),
431        )
432        .unwrap();
433        assert!(files.contains_key("devbox/devbox.json"));
434        assert!(!files.contains_key("mise/mise.toml"));
435        // The IR/lock always cover every category regardless of --only.
436        assert!(files.contains_key("cell.lock"));
437    }
438
439    #[test]
440    fn duplicate_system_dependency_declaration_fails_closed() {
441        // Two SEA SystemDependency declarations of the same name must hit
442        // CELL005 even though upsert would otherwise let the second
443        // silently overwrite the first.
444        let src = r#"
445Cell "X"
446    @profile "python-agent-v1"
447SystemDependency "git" version "2.45"
448SystemDependency "git" version "2.46"
449"#;
450        let err = project_cell_in_memory(src, "x.sea", Some(FIXED_TS.to_string()), None, None)
451            .unwrap_err();
452        assert!(err.starts_with("CELL005"), "{err}");
453        assert!(err.contains("git"), "{err}");
454    }
455
456    #[test]
457    fn wildcard_host_override_without_unsafe_authorization_fails() {
458        // A network endpoint override that introduces a wildcard host must
459        // re-run CELL021 validation and require an authorized unsafe
460        // override (CELL015/016), not bypass it.
461        let src = r#"
462Cell "X"
463    @profile "python-agent-v1"
464Endpoint "egress" @host "registry.example.com"
465"#;
466        let overrides = r#"
467schema = "domainforge-cell-overrides/v1"
468
469[network.endpoints.egress]
470host = "*"
471"#;
472        let err = project_cell_in_memory(
473            src,
474            "x.sea",
475            Some(FIXED_TS.to_string()),
476            Some(overrides),
477            None,
478        )
479        .unwrap_err();
480        assert!(err.starts_with("CELL021"), "{err}");
481        assert!(err.contains("wildcard"), "{err}");
482    }
483
484    #[test]
485    fn install_command_override_updates_evidence_probe() {
486        // The depset's evidence probe must reflect the *effective* install
487        // command after an override, not the originally declared one.
488        let overrides = r#"
489schema = "domainforge-cell-overrides/v1"
490
491[dependency_sets.python-application]
492install_command = "uv sync --frozen --override-probe"
493"#;
494        let files = project_cell_in_memory(
495            SOURCE,
496            "repair-agent/model.sea",
497            Some(FIXED_TS.to_string()),
498            Some(overrides),
499            None,
500        )
501        .unwrap();
502        let ir: serde_json::Value = extract_json(&files["semantic/cell-ir.json"]);
503        let probes = ir["evidence_probes"].as_array().unwrap();
504        let install_probe = probes
505            .iter()
506            .find(|p| p["source"].as_str() == Some("dependency-set"))
507            .unwrap();
508        assert_eq!(
509            install_probe["command"], "uv sync --frozen --override-probe",
510            "evidence probe must mirror the overridden install command"
511        );
512    }
513
514    fn extract_json(body: &str) -> serde_json::Value {
515        serde_json::from_str(body).expect("valid JSON")
516    }
517}