Skip to main content

brep_render/engine_state/
batch.rs

1//! Native batch authoring. Validation works on a cloned recipe; execution uses
2//! a native runner barrier so the transaction cannot expose pending results.
3use super::*;
4use serde_json::{json, Value};
5use std::collections::{BTreeMap, BTreeSet};
6
7fn alias_ref(text: &str) -> Option<(&str, &str)> {
8    let rest = text.strip_prefix('@')?;
9    let n = rest.find(['/', ':']).unwrap_or(rest.len());
10    Some((&rest[..n], &rest[n..]))
11}
12
13/// Validate reference grammar without requiring an output to exist yet.
14fn validate_reference(text: &str, aliases: &BTreeMap<String, String>) -> Result<(), String> {
15    if let Some((alias, suffix)) = alias_ref(text) {
16        if !aliases.contains_key(alias) {
17            return Err(format!("missing alias @{alias}"));
18        }
19        if !suffix.is_empty()
20            && !suffix.starts_with(':')
21            && suffix
22                .strip_prefix('/')
23                .and_then(|s| s.split_once('/'))
24                .filter(|(kind, _)| matches!(*kind, "output" | "face" | "edge"))
25                .and_then(|(_, index)| index.parse::<usize>().ok())
26                .is_none()
27        {
28            return Err(format!("invalid reference {text}"));
29        }
30    }
31    Ok(())
32}
33
34fn validate_references(
35    value: &Value,
36    aliases: &BTreeMap<String, String>,
37    path: &str,
38) -> Result<(), String> {
39    let mut refs = Vec::new();
40    strings(value, &mut refs);
41    for reference in refs {
42        validate_reference(&reference, aliases).map_err(|error| format!("{path}: {error}"))?;
43    }
44    Ok(())
45}
46
47fn strings(value: &Value, out: &mut Vec<String>) {
48    match value {
49        Value::String(s) => out.push(s.clone()),
50        Value::Array(a) => a.iter().for_each(|v| strings(v, out)),
51        Value::Object(o) => o.values().for_each(|v| strings(v, out)),
52        _ => (),
53    }
54}
55
56fn resolve(
57    value: &mut Value,
58    aliases: &BTreeMap<String, String>,
59    outputs: &BTreeMap<String, Vec<String>>,
60) -> Result<(), String> {
61    match value {
62        Value::String(s) => {
63            if let Some((alias, suffix)) = alias_ref(s) {
64                let id = aliases
65                    .get(alias)
66                    .ok_or_else(|| format!("missing alias @{alias}"))?;
67                *s = if let Some((kind, index)) =
68                    suffix.strip_prefix('/').and_then(|s| s.split_once('/'))
69                {
70                    if !matches!(kind, "output" | "face" | "edge") {
71                        return Err(format!("invalid output kind in {s}"));
72                    }
73                    let index: usize = index
74                        .parse()
75                        .map_err(|_| format!("invalid output index in {s}"))?;
76                    let key = if kind == "output" {
77                        id.clone()
78                    } else {
79                        format!("{id}/{kind}")
80                    };
81                    outputs
82                        .get(&key)
83                        .and_then(|o| o.get(index))
84                        .cloned()
85                        .ok_or_else(|| format!("{kind} {index} of @{alias} was not generated"))?
86                } else if suffix.is_empty() || suffix.starts_with(':') {
87                    format!("{id}{suffix}")
88                } else {
89                    return Err(format!("invalid alias reference {s}"));
90                };
91            }
92        }
93        Value::Array(a) => {
94            for v in a {
95                resolve(v, aliases, outputs)?;
96            }
97        }
98        Value::Object(o) => {
99            for v in o.values_mut() {
100                resolve(v, aliases, outputs)?;
101            }
102        }
103        _ => (),
104    }
105    Ok(())
106}
107
108fn merge(base: &mut Value, patch: &Value) {
109    if let (Some(b), Some(p)) = (base.as_object_mut(), patch.as_object()) {
110        for (k, v) in p {
111            if let Some(old) = b.get_mut(k) {
112                merge(old, v);
113            } else {
114                b.insert(k.clone(), v.clone());
115            }
116        }
117    } else {
118        *base = patch.clone();
119    }
120}
121
122fn prepare(
123    catalogue: &Value,
124    items: &[Value],
125    history: &mut History,
126    aliases: &mut BTreeMap<String, String>,
127) -> Result<Vec<Value>, String> {
128    let mut ids: BTreeSet<String> = history
129        .features()
130        .iter()
131        .filter_map(|f| f["inputParams"]["id"].as_str().map(str::to_owned))
132        .collect();
133    ids.extend(aliases.values().cloned());
134    let mut features = Vec::new();
135    for (i, item) in items.iter().enumerate() {
136        let ty = item["type"]
137            .as_str()
138            .ok_or_else(|| format!("features[{i}].type is required"))?;
139        let schema = catalogue["features"].as_array().and_then(|fs| fs.iter().find(|f| f["type"] == ty || (!f["type"].as_str().unwrap_or("").contains('/') && f["shortName"] == ty))).cloned()
140            .ok_or_else(|| format!("features[{i}].type: unknown type {ty}"))?;
141        let mut params = json!({});
142        if let Some(properties) = schema["inputParamsSchema"].as_object() {
143            for (key, spec) in properties { params[key] = spec["default_value"].clone(); }
144        }
145        params["id"] = Value::Null;
146        let patch = item
147            .get("inputParams")
148            .or_else(|| item.get("params"))
149            .cloned()
150            .unwrap_or(json!({}));
151        let object = patch
152            .as_object()
153            .ok_or_else(|| format!("features[{i}].params must be an object"))?;
154        for key in object.keys() {
155            // Programmatic payloads a feature's form never shows but its
156            // builder reads: ACOMP's occurrence attributes, and IMPORT3D's
157            // `stepText` (the STEP document an import bakes in — undeclared
158            // so no form renders it, kernel `import3d::schema`).
159            if params.get(key).is_none()
160                && !(super::components::is_acomp_feature_type(ty) && key == "occurrenceAttributes")
161                && !(ty == "IMPORT3D" && key == "stepText")
162            {
163                return Err(format!("features[{i}].params.{key}: unknown field"));
164            }
165        }
166        merge(&mut params, &patch);
167        let id = item["id"]
168            .as_str()
169            .or_else(|| params["id"].as_str())
170            .map(str::to_owned)
171            .unwrap_or_else(|| loop {
172                let id = history.next_feature_id(schema["shortName"].as_str().unwrap_or(ty));
173                if !ids.contains(&id) {
174                    break id;
175                }
176            });
177        if id.is_empty() || !ids.insert(id.clone()) {
178            return Err(format!("features[{i}].id: empty or duplicate id `{id}`"));
179        }
180        if matches!(ty, "ACOMP" | "ASSEMBLY COMPONENT") && !brep_kernel::is_component_reference(&id)
181        {
182            return Err(format!(
183                "features[{i}].id: component ids must be ACOMP<digits>"
184            ));
185        }
186        params["id"] = json!(id);
187        if super::components::is_acomp_feature_type(ty) {
188            if !object.contains_key("isFixed") {
189                params.as_object_mut().unwrap().remove("isFixed");
190            }
191            if let Some(attributes) = item.get("attributes") {
192                if !attributes.is_object() {
193                    return Err(format!("features[{i}].attributes must be an object"));
194                }
195                merge(&mut params["occurrenceAttributes"], attributes);
196            }
197            if let Some(name) = item.get("display_name") {
198                params["occurrenceAttributes"]["Name"] = name.clone();
199            }
200            if let Some(material) = item.get("material") {
201                params["occurrenceAttributes"]["Material"] = material.clone();
202            }
203        }
204        if let Some(alias) = item.get("alias") {
205            let alias = alias
206                .as_str()
207                .filter(|s| !s.is_empty() && !s.contains(['@', '/', ':']))
208                .ok_or_else(|| format!("features[{i}].alias: invalid alias"))?;
209            if aliases.insert(alias.into(), id.clone()).is_some() {
210                return Err(format!("features[{i}].alias: duplicate alias {alias}"));
211            }
212        }
213        brep_kernel::feature_pipeline::validate_literal_feature_params(schema["type"].as_str().unwrap_or_default(), &params)?;
214        features.push(json!({"type":schema["type"], "inputParams":params, "persistentData":item.get("persistent_data").or_else(|| item.get("persistentData")).cloned().unwrap_or(json!({}))}));
215    }
216    Ok(features)
217}
218
219/// Stable topological order; dependencies include explicit `depends_on` aliases
220/// and alias references anywhere in parameters or persistent data.
221fn plan(
222    items: &[Value],
223    features: &[Value],
224    aliases: &BTreeMap<String, String>,
225) -> Result<(Vec<usize>, Vec<Vec<usize>>), String> {
226    let positions: BTreeMap<&str, usize> = features
227        .iter()
228        .enumerate()
229        .map(|(i, f)| (f["inputParams"]["id"].as_str().unwrap(), i))
230        .collect();
231    let mut deps = vec![Vec::new(); features.len()];
232    for (i, feature) in features.iter().enumerate() {
233        let mut refs = Vec::new();
234        strings(&feature["inputParams"], &mut refs);
235        strings(&feature["persistentData"], &mut refs);
236        if let Some(explicit) = items[i].get("depends_on") {
237            let a = explicit
238                .as_array()
239                .ok_or_else(|| format!("features[{i}].depends_on must be an array"))?;
240            for r in a {
241                refs.push(format!(
242                    "@{}",
243                    r.as_str().ok_or("depends_on entries must be aliases")?
244                ));
245            }
246        }
247        for r in refs {
248            validate_reference(&r, aliases).map_err(|error| format!("features[{i}]: {error}"))?;
249            if let Some((a, _)) = alias_ref(&r) {
250                let id = &aliases[a];
251                if let Some(&p) = positions.get(id.as_str()) {
252                    deps[i].push(p);
253                }
254            }
255        }
256        deps[i].sort_unstable();
257        deps[i].dedup();
258    }
259    let mut order = Vec::new();
260    while order.len() < features.len() {
261        let Some(i) = (0..features.len())
262            .find(|i| !order.contains(i) && deps[*i].iter().all(|d| order.contains(d)))
263        else {
264            return Err(format!(
265                "dependency cycle among feature positions {:?}",
266                (0..features.len())
267                    .filter(|i| !order.contains(i))
268                    .collect::<Vec<_>>()
269            ));
270        };
271        order.push(i);
272    }
273    Ok((order, deps))
274}
275
276/// What [`EngineState::stage_feature_begin`] keeps until the run lands.
277#[derive(Debug, Clone)]
278pub(crate) struct StagedFeature {
279    id: String,
280    before: History,
281    metadata: crate::metadata::MetadataStore,
282    library: brep_kernel::PartsLibraryMap,
283    staged: History,
284    /// `History::edit_serial` right after the staged feature was appended.
285    edit_serial: u64,
286}
287
288fn failed(report: &Value) -> bool {
289    report.get("error").is_some()
290        || [
291            "featureErrors",
292            "displayErrors",
293            "unresolved",
294            "featureFulfilment",
295        ]
296        .iter()
297        .any(|key| match &report[*key] {
298            Value::Object(o) => !o.is_empty(),
299            Value::Array(a) => !a.is_empty(),
300            _ => false,
301        })
302}
303
304fn refusal_category(refusal: &Value) -> &'static str {
305    match refusal["class"].as_str() {
306        Some("degenerate_arrangement" | "non_integral_genus" | "invalid_result_topology") => {
307            "invalid_topology"
308        }
309        Some("tangent_node_singularity" | "conservative_empty_overlap") => "contact_related",
310        Some("non_convergence") => "numerical_nonconvergence",
311        Some("invalid_input") => "invalid_input",
312        Some("unsupported_geometry") => "unsupported_geometry",
313        _ => "geometry_execution_failure",
314    }
315}
316
317impl EngineState {
318    /// Full diagnostics from the last batch, including a rolled-back attempt.
319    pub fn geometry_diagnostics(&self, id: &str) -> Option<Value> {
320        self.geometry_diagnostics.get(id).cloned()
321    }
322
323    /// Wait on the installed native runner, preserving its resident geometry
324    /// and delta baseline. A transaction is one app command, so other commands
325    /// cannot observe its intermediate recipes. Kernel operations are not
326    /// preemptible inside a feature.
327    /// Stage ONE feature without waiting for it (an agent's `cad.*` write,
328    /// contract §5.1/§6): snapshot the recipe, metadata and parts library,
329    /// append the seeded, validated feature and hand its run to the runner,
330    /// then return. [`Self::stage_feature_poll`] finishes it on the frame the
331    /// run lands — committing it as one undo checkpoint, or restoring the
332    /// snapshot if it failed — so no frame waits for geometry. One stage at a
333    /// time per document; `item` is a batch item (`{type, params, …}`).
334    pub fn stage_feature_begin(&mut self, item: &Value) -> Result<String, String> {
335        if self.staged_feature.is_some() {
336            return Err("document_busy: a staged feature is still evaluating".into());
337        }
338        if self.run_pending() || self.queries_pending() || self.mesh_imports_pending() || self.topology_pending() {
339            return Err("wait for pending engine work before staging a feature".into());
340        }
341        if let Some(reason) = self.history.locked() {
342            return Err(format!("document is locked: {reason}"));
343        }
344        let before = self.history.clone();
345        let metadata = self.metadata.clone();
346        let library = brep_kernel::parts_library_map();
347        let mut staged = before.clone();
348        let mut aliases = BTreeMap::new();
349        let features = prepare(&self.feature_catalogue(), std::slice::from_ref(item), &mut staged, &mut aliases)?;
350        let feature = features.into_iter().next().ok_or("nothing to stage")?;
351        let id = feature["inputParams"]["id"].as_str().ok_or("the staged feature has no id")?.to_string();
352        let mut validation: Value = serde_json::from_str(&before.request_json()).map_err(|e| e.to_string())?;
353        validation["features"].as_array_mut().ok_or("document features missing")?.push(feature.clone());
354        serde_json::from_value::<HistoryRequest>(validation).map_err(|e| format!("stage validation: {e}"))?;
355        self.add_features(&[feature]);
356        // The user may keep editing while the run evaluates (the frame is
357        // not held): the serial after OUR write tells the finish whether
358        // anything else wrote the recipe meanwhile.
359        let edit_serial = self.history.edit_serial();
360        // Until it lands, the user's own edits to this document are refused
361        // (and said), not interleaved with the agent's.
362        self.history.set_busy(Some("an agent's change to this document is still evaluating".into()));
363        self.staged_feature = Some(StagedFeature { id: id.clone(), before, metadata, library, staged, edit_serial });
364        Ok(id)
365    }
366
367    /// Whether a feature is staged and its run has not been finished yet.
368    pub fn stage_feature_pending(&self) -> bool {
369        self.staged_feature.is_some()
370    }
371
372    /// Finish a staged feature once its run has landed: `None` while it is
373    /// still evaluating, else its row `{id, committed, status,
374    /// generatedSolids, error}`.
375    pub fn stage_feature_poll(&mut self) -> Option<Result<Value, String>> {
376        if self.staged_feature.is_none() || self.run_pending() {
377            return None;
378        }
379        let st = self.staged_feature.take()?;
380        self.history.set_busy(None);
381        // Say any refused user edit now: a restore below replaces the history
382        // that counted it.
383        if self.history.busy_refused() > self.busy_refused_seen {
384            self.push_notice("Not applied: an agent's change to this document was still evaluating. Try again.");
385        }
386        let report: Value = serde_json::from_str(&self.history_report_json()).unwrap_or(Value::Null);
387        let id = st.id.clone();
388        let names: Vec<String> = serde_json::from_value(report["featureOutputs"][&id].clone()).unwrap_or_default();
389        let errors: Vec<String> = report["featureErrors"]
390            .as_array()
391            .into_iter()
392            .flatten()
393            .filter_map(Value::as_str)
394            .filter(|e| e.starts_with(&format!("{id}:")))
395            .map(|e| e.chars().take(240).collect())
396            .collect();
397        let evaluated = report["featureTimings"].get(&id).is_some();
398        let failed = !errors.is_empty() || report["featureFulfilment"].get(&id).is_some() || report.get("error").is_some() || !evaluated;
399        // Did a user edit the recipe while it evaluated?
400        let interleaved = self.history.edit_serial() != st.edit_serial;
401        if failed && interleaved {
402            // Restoring the snapshot would throw the user's edit away: remove
403            // only the staged feature, and keep everything else as it is now.
404            if let Some(index) = self.history.index_of(&id) {
405                self.history.remove_feature(index);
406            }
407            self.rerun_history();
408            let why = if errors.is_empty() { "the feature did not evaluate".to_string() } else { errors.join("; ") };
409            self.busy_refused_seen = self.history.busy_refused();
410            return Some(Ok(json!({ "id": id, "committed": false, "status": "failed", "generatedSolids": [], "error": why, "rolledBack": true, "interleavedEdit": true })));
411        }
412        if failed {
413            // Restore the snapshot exactly; the display re-runs on its own.
414            self.history = st.before;
415            self.metadata = st.metadata;
416            brep_kernel::install_parts_library(&Default::default());
417            brep_kernel::install_parts_library(&st.library);
418            self.rerun_history();
419            let why = if errors.is_empty() { "the feature did not evaluate".to_string() } else { errors.join("; ") };
420            self.busy_refused_seen = self.history.busy_refused();
421            return Some(Ok(json!({ "id": id, "committed": false, "status": "failed", "generatedSolids": [], "error": why, "rolledBack": true })));
422        }
423        if interleaved {
424            // The user's own edits sit on the undo stack beside ours: leave the
425            // stack as it is rather than fold them into the agent's step.
426            self.history.retain_feature_allocations(&st.staged);
427            self.busy_refused_seen = self.history.busy_refused();
428            return Some(Ok(json!({ "id": id, "committed": true, "status": "evaluated", "generatedSolids": names, "rolledBack": false, "interleavedEdit": true })));
429        }
430        // One undo checkpoint for the staged write, as a batch commits.
431        let final_document = self.history.request_json();
432        self.history = st.before;
433        if let Err(e) = self.history.adopt_document_checkpointed(&final_document) {
434            return Some(Err(e));
435        }
436        self.history.retain_feature_allocations(&st.staged);
437        self.history.set_rollback(self.history.len().saturating_sub(1));
438        self.busy_refused_seen = self.history.busy_refused();
439        Some(Ok(json!({ "id": id, "committed": true, "status": "evaluated", "generatedSolids": names, "rolledBack": false })))
440    }
441
442    fn finish_batch_run(&mut self) {
443        while self.run_pending() {
444            self.pump();
445            #[cfg(not(target_arch = "wasm32"))]
446            if self.run_pending() {
447                std::thread::sleep(std::time::Duration::from_millis(1));
448            }
449        }
450    }
451
452    /// Full-document rollback includes recipe, library, metadata, counters and
453    /// undo/redo. Runtime caches and the generation counter are deliberately
454    /// invalidated, not rewound. No file, network or document-tab side effects.
455    pub fn author_batch(&mut self, args: &Value) -> Result<Value, String> {
456        if cfg!(target_arch = "wasm32") {
457            return Err("structured native authoring requires a native MCP host".into());
458        }
459        if self.run_pending()
460            || self.queries_pending()
461            || self.mesh_imports_pending()
462            || self.topology_pending()
463        {
464            return Err("wait for pending engine work before authoring a batch".into());
465        }
466        if let Some(reason) = self.history.locked() {
467            return Err(format!("document is locked: {reason}"));
468        }
469        let items = args["features"]
470            .as_array()
471            .ok_or("features must be an array")?;
472        let rollback = args["rollback_on_error"].as_bool().unwrap_or(false);
473        let before = self.history.clone();
474        let metadata = self.metadata.clone();
475        let library = brep_kernel::parts_library_map();
476        let mut staged = before.clone();
477        let mut document: Value =
478            serde_json::from_str(&staged.request_json()).map_err(|e| e.to_string())?;
479        let mut aliases = BTreeMap::new();
480        let mut part_aliases = BTreeMap::new();
481        let mut part_work = Vec::new();
482        let mut constraint_ids = Vec::new();
483        if let Some(parts) = args.get("parts") {
484            for (i, part) in parts
485                .as_array()
486                .ok_or("parts must be an array")?
487                .iter()
488                .enumerate()
489            {
490                let alias = part["alias"]
491                    .as_str()
492                    .filter(|s| !s.is_empty() && !s.contains(['@', '/', ':']))
493                    .ok_or_else(|| format!("parts[{i}].alias is required"))?;
494                if aliases.insert(alias.into(), alias.into()).is_some()
495                    || document["partsLibrary"].get(alias).is_some()
496                {
497                    return Err(format!("parts[{i}]: duplicate part {alias}"));
498                }
499                let mut doc = part["document"].clone();
500                let native = doc["features"]
501                    .as_array()
502                    .ok_or_else(|| format!("parts[{i}].document.features must be an array"))?
503                    .clone();
504                let mut allocation_base = doc.clone();
505                allocation_base["features"] = json!([]);
506                let mut part_history = History::from_request_json(&allocation_base.to_string())?;
507                let mut local_aliases = BTreeMap::new();
508                let mut scope = EngineState::new();
509                scope.inherit_plugins(self);
510                scope.history = part_history.clone();
511                let mut prepared = prepare(&scope.feature_catalogue(), &native, &mut part_history, &mut local_aliases)
512                    .map_err(|e| format!("parts[{i}].document.{e}"))?;
513                let _ = plan(&native, &prepared, &local_aliases)
514                    .map_err(|e| format!("parts[{i}].document.{e}"))?;
515                for (index, f) in prepared.iter_mut().enumerate() {
516                    for key in ["alias", "depends_on"] {
517                        if let Some(value) = native[index].get(key) {
518                            f[key] = value.clone();
519                        }
520                    }
521                }
522                part_aliases.insert(alias.to_owned(), local_aliases);
523                // Keep client order for result positions; the isolated batch
524                // below executes its own dependency plan.
525                doc["features"] = json!(prepared);
526                doc["featureCounter"] = serde_json::from_str::<Value>(&part_history.request_json())
527                    .unwrap_or_default()["featureCounter"]
528                    .clone();
529                part_work.push((alias.to_owned(), doc.clone()));
530                document["partsLibrary"][alias] = json!({"sourceKey":alias,"sourceSignature":"batch", "document":doc,"snapshot":""});
531            }
532        }
533        let mut features = prepare(&self.feature_catalogue(), items, &mut staged, &mut aliases)?;
534        let (order, deps) = plan(items, &features, &aliases)?;
535        document["featureCounter"] = serde_json::from_str::<Value>(&staged.request_json())
536            .unwrap_or_default()["featureCounter"]
537            .clone();
538        if let Some(expressions) = args.get("expressions") {
539            if !expressions.is_string() {
540                return Err("expressions must be a script string".into());
541            }
542            document["expressions"] = expressions.clone();
543        }
544        // Constraints use the native catalogue and descriptor shape.
545        if let Some(constraints) = args.get("constraints") {
546            let catalogue = brep_kernel::constraint_schema_catalogue();
547            let mut counter = document["assembly"]["idCounter"].as_u64().unwrap_or(0);
548            for (i, constraint) in constraints
549                .as_array()
550                .ok_or("constraints must be an array")?
551                .iter()
552                .enumerate()
553            {
554                let ty = constraint["type"]
555                    .as_str()
556                    .ok_or("constraint type is required")?;
557                let entry = catalogue
558                    .as_array()
559                    .and_then(|a| a.iter().find(|e| e["type"].as_str() == Some(ty)))
560                    .ok_or_else(|| format!("constraints[{i}].type: unknown constraint {ty}"))?;
561                counter += 1;
562                let id = format!("{}{}", entry["shortName"].as_str().unwrap_or("C"), counter);
563                let mut params = json!({});
564                if let Some(schema) = entry["inputParamsSchema"].as_object() {
565                    for (k, v) in schema {
566                        params[k] = v["default_value"].clone();
567                    }
568                }
569                merge(
570                    &mut params,
571                    constraint
572                        .get("params")
573                        .or_else(|| constraint.get("inputParams"))
574                        .unwrap_or(&json!({})),
575                );
576                for key in params
577                    .as_object()
578                    .ok_or_else(|| format!("constraints[{i}].params must be an object"))?
579                    .keys()
580                {
581                    if entry["inputParamsSchema"].get(key).is_none() {
582                        return Err(format!("constraints[{i}].params.{key}: unknown field"));
583                    }
584                }
585                constraint_ids.push(id.clone());
586                params["id"] = json!(id);
587                validate_references(&params, &aliases, &format!("constraints[{i}].params"))?;
588                if let Some(a) = constraint["alias"].as_str() {
589                    if aliases.insert(a.into(), id).is_some() {
590                        return Err(format!("constraints[{i}].alias is duplicate"));
591                    }
592                }
593                if !document["assembly"]["constraints"].is_array() {
594                    document["assembly"]["constraints"] = json!([]);
595                }
596                let mut persistent = constraint
597                    .get("persistent_data")
598                    .or_else(|| constraint.get("persistentData"))
599                    .cloned()
600                    .unwrap_or(json!({}));
601                validate_references(
602                    &persistent,
603                    &aliases,
604                    &format!("constraints[{i}].persistentData"),
605                )?;
606                let explicit = constraint
607                    .get("params")
608                    .or_else(|| constraint.get("inputParams"));
609                // Interactive creation adopts a measurement on its first solve.
610                // A batch's explicitly supplied target already expresses intent.
611                for (field, flag) in [
612                    ("distance", "initializedDistance"),
613                    ("angle", "initializedAngle"),
614                ] {
615                    if explicit.is_some_and(|p| p.get(field).is_some()) {
616                        persistent
617                            .as_object_mut()
618                            .ok_or_else(|| {
619                                format!("constraints[{i}].persistent_data must be an object")
620                            })?
621                            .entry(flag)
622                            .or_insert(json!(true));
623                    }
624                }
625                document["assembly"]["constraints"].as_array_mut().unwrap().push(json!({"type":ty,"inputParams":params,"persistentData":persistent,"enabled":constraint.get("enabled").cloned().unwrap_or(json!(true))}));
626            }
627            document["assembly"]["idCounter"] = json!(counter);
628        }
629        if let Some(patch) = args.get("metadata") {
630            let map = patch.as_object().ok_or("metadata must be an object")?;
631            for key in map.keys() {
632                if let Some((a, _)) = alias_ref(key) {
633                    if !aliases.contains_key(a) {
634                        return Err(format!("metadata.{key}: missing alias @{a}"));
635                    }
636                }
637            }
638        }
639        // Parse the entire proposed request before touching any live state.
640        let mut validation = document.clone();
641        validation["features"]
642            .as_array_mut()
643            .ok_or("document features missing")?
644            .extend(features.clone());
645        serde_json::from_value::<HistoryRequest>(validation)
646            .map_err(|e| format!("batch validation: {e}"))?;
647        self.geometry_diagnostics.clear();
648        let run = (|| -> Result<Value, String> {
649            // Compile each native definition in isolation first. This resolves
650            // generated-output aliases inside part histories too, without
651            // turning the part into an imported/baked solid.
652            let mut part_results = Vec::new();
653            for (position, (alias, source)) in part_work.iter().enumerate() {
654                let mut base = source.clone();
655                let part_features = base["features"].take();
656                base["features"] = json!([]);
657                base.as_object_mut().unwrap().remove("metadata");
658                let mut part = EngineState::new();
659                part.inherit_plugins(self);
660                part.set_history_json(&base.to_string())?;
661                let mut part_args = json!({"features":part_features,"rollback_on_error":true});
662                if let Some(metadata) = source.get("metadata") {
663                    part_args["metadata"] = metadata.clone();
664                }
665                let mut evaluated = part.author_batch(&part_args)?;
666                for (id, details) in &part.geometry_diagnostics {
667                    self.geometry_diagnostics
668                        .insert(format!("part:{alias}:{id}"), details.clone());
669                }
670                for item in evaluated["items"].as_array_mut().into_iter().flatten() {
671                    if let Some(id) = item["diagnostic"]["detailId"].as_str().map(str::to_owned) {
672                        item["diagnostic"]["detailId"] = json!(format!("part:{alias}:{id}"));
673                    }
674                }
675                part_results.push(json!({"position":position,"alias":alias,"id":alias,"status":if evaluated["success"] == true {"evaluated"} else {"failed"},"committed":false,"items":evaluated["items"],"outputs":evaluated["outputs"]}));
676                if evaluated["success"] != true {
677                    for (i, (remaining, _)) in part_work.iter().enumerate().skip(position + 1) {
678                        part_results.push(json!({"position":i,"alias":remaining,"id":remaining,"status":"not_evaluated","committed":false}));
679                    }
680                    let pending: Vec<Value> = items.iter().enumerate().map(|(i,item)| json!({"position":i,"alias":item["alias"],"id":features[i]["inputParams"]["id"],"status":"not_evaluated","committed":false,"dependencyFailure":{"part":alias}})).collect();
681                    return Ok(
682                        json!({"success":false,"requiresRestore":true,"items":pending,"partResults":part_results,"constraintResults":[],"aliases":aliases,"partAliases":part_aliases,"diagnosticsTool":"geometry_diagnostics"}),
683                    );
684                }
685                document["partsLibrary"][alias]["document"] =
686                    serde_json::from_str::<Value>(&part.history_request_json())
687                        .map_err(|e| e.to_string())?;
688            }
689            // Delay constraints until every instance exists.
690            let constraints = document.get("assembly").cloned();
691            document.as_object_mut().unwrap().remove("assembly");
692            self.edit_document_json(&document.to_string())?;
693            self.finish_batch_run();
694            let prepared_library =
695                serde_json::from_value(document.get("partsLibrary").cloned().unwrap_or(json!({})))
696                    .map_err(|e| format!("partsLibrary: {e}"))?;
697            let mut outputs: BTreeMap<String, Vec<String>> = BTreeMap::new();
698            let mut results = vec![Value::Null; items.len()];
699            let mut failed_items = BTreeSet::new();
700            for i in order {
701                let id = features[i]["inputParams"]["id"]
702                    .as_str()
703                    .unwrap()
704                    .to_string();
705                let blocked: Vec<usize> = deps[i]
706                    .iter()
707                    .filter(|d| failed_items.contains(*d))
708                    .copied()
709                    .collect();
710                let mut result = json!({"position":i,"alias":items[i]["alias"],"id":id,"committed":false,"dependencies":deps[i]});
711                if !blocked.is_empty() {
712                    failed_items.insert(i);
713                    result["status"] = json!("not_evaluated");
714                    result["dependencyFailures"] = json!(blocked);
715                    results[i] = result;
716                    continue;
717                }
718                if let Err(error) = resolve(&mut features[i], &aliases, &outputs) {
719                    failed_items.insert(i);
720                    result["status"] = json!("failed");
721                    result["error"] = json!({"category":"reference_resolution","message":error,"path":format!("features[{i}]")});
722                    results[i] = result;
723                    continue;
724                }
725                brep_kernel::install_parts_library(&prepared_library);
726                self.history.set_parts_library(
727                    serde_json::to_value(brep_kernel::parts_library_map())
728                        .map_err(|e| e.to_string())?,
729                );
730                self.add_features(&[features[i].clone()]);
731                self.finish_batch_run();
732                let report: Value =
733                    serde_json::from_str(&self.history_report_json()).map_err(|e| e.to_string())?;
734                let names: Vec<String> =
735                    serde_json::from_value(report["featureOutputs"][&id].clone())
736                        .unwrap_or_default();
737                outputs.insert(id.clone(), names.clone());
738                let errors: Vec<Value> = report["featureErrors"]
739                    .as_array()
740                    .into_iter()
741                    .flatten()
742                    .filter(|e| e.as_str().is_some_and(|e| e.starts_with(&format!("{id}:"))))
743                    .cloned()
744                    .collect();
745                let has_error = !errors.is_empty()
746                    || report["featureFulfilment"].get(&id).is_some()
747                    || report.get("error").is_some();
748                if has_error {
749                    failed_items.insert(i);
750                }
751                result["status"] = json!(if has_error {
752                    "failed"
753                } else if report["featureTimings"].get(&id).is_some() {
754                    "evaluated"
755                } else {
756                    "not_evaluated"
757                });
758                if result["status"] == "not_evaluated" {
759                    failed_items.insert(i);
760                }
761                result["generatedSolids"] = json!(names);
762                self.geometry_diagnostics.insert(id.clone(), json!({"errors":errors,"refusal":report["featureRefusals"][&id],"unresolved":report["unresolved"],"fulfilment":report["featureFulfilment"][&id],"approximations":report["featureApproximations"][&id],"operation":features[i]["type"],"operands":features[i]["inputParams"],"dependencies":deps[i]}));
763                result["error"] = json!(errors
764                    .iter()
765                    .filter_map(Value::as_str)
766                    .map(|s| s.chars().take(240).collect::<String>())
767                    .collect::<Vec<_>>());
768                let mut references = Vec::new();
769                for name in &names {
770                    if let Some(solid) = self.scene.solid(name) {
771                        references.push(json!({"solid":name,"faces":solid.faces.iter().map(|f| &f.name).collect::<Vec<_>>(),"edges":solid.edges.iter().map(|e| &e.name).collect::<Vec<_>>()}));
772                    }
773                }
774                outputs.insert(
775                    format!("{id}/face"),
776                    references
777                        .iter()
778                        .flat_map(|r| r["faces"].as_array().into_iter().flatten())
779                        .filter_map(Value::as_str)
780                        .map(str::to_owned)
781                        .collect(),
782                );
783                outputs.insert(
784                    format!("{id}/edge"),
785                    references
786                        .iter()
787                        .flat_map(|r| r["edges"].as_array().into_iter().flatten())
788                        .filter_map(Value::as_str)
789                        .map(str::to_owned)
790                        .collect(),
791                );
792                result["generatedReferences"] = json!(references);
793                let schema =
794                    self.feature_schema(features[i]["type"].as_str().unwrap_or(""))
795                        .unwrap_or_default();
796                let operands: serde_json::Map<String, Value> = features[i]["inputParams"]
797                    .as_object()
798                    .into_iter()
799                    .flat_map(|o| o.iter())
800                    .filter(|(k, _)| {
801                        matches!(
802                            schema["inputParamsSchema"][*k]["type"].as_str(),
803                            Some("reference_selection" | "boolean_operation")
804                        ) || k.as_str() == "partName"
805                    })
806                    .map(|(k, v)| (k.clone(), v.clone()))
807                    .collect();
808                result["diagnostic"] = json!({"operation":features[i]["type"],"owningComponent": if super::components::is_acomp_feature_type(features[i]["type"].as_str().unwrap_or("")) { Some(&id) } else { None }, "operands":operands,"affectedTopology":report["featureRefusals"][&id]["faces"],"category":if has_error { Some(refusal_category(&report["featureRefusals"][&id])) } else { None },"kernelClass":report["featureRefusals"][&id]["class"],"detailId":id});
809                result["committed"] = json!(true);
810                results[i] = result;
811            }
812            let mut constraint_errors = BTreeMap::new();
813            if let Some(mut constraints) = constraints {
814                if let Some(entries) = constraints["constraints"].as_array_mut() {
815                    entries.retain_mut(|entry| {
816                        let id = entry["inputParams"]["id"].as_str().unwrap_or("").to_owned();
817                        if let Err(error) = resolve(entry, &aliases, &outputs) {
818                            constraint_errors.insert(id, error);
819                            false
820                        } else {
821                            true
822                        }
823                    });
824                }
825                let mut final_doc: Value = serde_json::from_str(&self.history.request_json())
826                    .map_err(|e| e.to_string())?;
827                final_doc["assembly"] = constraints;
828                self.edit_document_json(&final_doc.to_string())?;
829                self.finish_batch_run();
830            }
831            if let Some(patch) = args.get("metadata").and_then(Value::as_object) {
832                let mut merged = self.metadata.to_json();
833                for (key, record) in patch {
834                    let mut name = json!(key);
835                    resolve(&mut name, &aliases, &outputs)?;
836                    merge(&mut merged[name.as_str().unwrap()], record);
837                }
838                self.metadata.load_json(Some(&merged));
839                self.sync_colors_from_metadata();
840            }
841            let final_report: Value =
842                serde_json::from_str(&self.history_report_json()).map_err(|e| e.to_string())?;
843            let statuses = self.assembly_statuses_value();
844            let constraint_failure = statuses.as_array().is_some_and(|a| {
845                a.iter()
846                    .any(|s| s["enabled"] != false && s["satisfied"] == false)
847            });
848            let success = failed_items.is_empty()
849                && !failed(&final_report)
850                && !constraint_failure
851                && constraint_errors.is_empty();
852            let constraint_results: Vec<Value> = constraint_ids.iter().enumerate().map(|(i,id)| {
853                let row = statuses.as_array().and_then(|a| a.iter().find(|r| r["id"].as_str() == Some(id)));
854                let state = if constraint_errors.contains_key(id) || row.is_none() || row.is_some_and(|r| r["enabled"] == false) { "not_evaluated" } else if row.is_some_and(|r| r["satisfied"] == false) { "failed" } else { "evaluated" };
855                json!({"position":i,"alias":args["constraints"][i]["alias"],"id":id,"status":state,"committed":!constraint_errors.contains_key(id),"error":constraint_errors.get(id),"diagnostics":row,"dependencyFailures":if constraint_errors.contains_key(id) { failed_items.iter().copied().collect::<Vec<_>>() } else { vec![] }})
856            }).collect();
857            // Keep explicitly supplied definitions, including ones not yet
858            // instantiated. Normal library GC still applies on later edits.
859            let mut retained_library = brep_kernel::parts_library_map();
860            for (alias, _) in &part_work {
861                if let Some(entry) = prepared_library.get(alias) {
862                    retained_library
863                        .entry(alias.clone())
864                        .or_insert_with(|| entry.clone());
865                }
866            }
867            brep_kernel::install_parts_library(&retained_library);
868            self.history.set_parts_library(
869                serde_json::to_value(&retained_library).map_err(|e| e.to_string())?,
870            );
871            for result in &mut part_results {
872                result["committed"] = json!(true);
873            }
874            self.geometry_diagnostics
875                .insert("__report__".into(), final_report);
876            Ok(
877                json!({"success":success,"items":results,"partResults":part_results,"constraintResults":constraint_results,"aliases":aliases,"partAliases":part_aliases,"outputs":outputs,"diagnosticsTool":"geometry_diagnostics","constraintStatuses":statuses,"dof":self.assembly_dof_value()}),
878            )
879        })();
880        let restore = run
881            .as_ref()
882            .map(|r| r["requiresRestore"] == true || (rollback && r["success"] != true))
883            .unwrap_or(true);
884        if restore {
885            self.history = before.clone();
886            self.metadata = metadata.clone();
887            brep_kernel::install_parts_library(&Default::default());
888            brep_kernel::install_parts_library(&library);
889            self.rerun_history();
890            self.finish_batch_run();
891            // The restoration rebuild may heal/GC library entries or fold a
892            // solver pose. Preserve the exact pre-transaction authored state.
893            self.history = before;
894            self.metadata = metadata;
895            brep_kernel::install_parts_library(&Default::default());
896            brep_kernel::install_parts_library(&library);
897        } else {
898            // Collapse the staged rebuilds into a single user undo checkpoint.
899            let final_document = self.history.request_json();
900            self.history = before;
901            self.history.adopt_document_checkpointed(&final_document)?;
902            self.history.retain_feature_allocations(&staged);
903            self.history
904                .set_rollback(self.history.len().saturating_sub(1));
905        }
906        let mut result = run?;
907        result.as_object_mut().unwrap().remove("requiresRestore");
908        result["rolledBack"] = json!(restore);
909        result["transaction"] = json!({"validationAtomic":true,"geometryAtomic":rollback,"idCountersRolledBack":restore,"runtimeGenerationRolledBack":false});
910        if restore {
911            fn uncommit(value: &mut Value) {
912                match value {
913                    Value::Object(object) => {
914                        if object.contains_key("committed") {
915                            object.insert("committed".into(), json!(false));
916                        }
917                        for value in object.values_mut() {
918                            uncommit(value);
919                        }
920                    }
921                    Value::Array(array) => {
922                        for value in array {
923                            uncommit(value);
924                        }
925                    }
926                    _ => (),
927                }
928            }
929            uncommit(&mut result);
930        }
931        Ok(result)
932    }
933}
934
935/// Transform strings are expressions, including strings nested in vec3s.
936pub(super) fn contains_expression(value: &Value) -> bool {
937    match value {
938        Value::String(_) => true,
939        Value::Array(a) => a.iter().any(contains_expression),
940        Value::Object(o) => o.values().any(contains_expression),
941        _ => false,
942    }
943}
944
945
946
947
948