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