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")
182            && !brep_kernel::is_component_reference(&id)
183            && brep_kernel::validate_feature_name(&id).is_err()
184        {
185            return Err(format!(
186                "features[{i}].id: a component id is ACOMP<digits> or a name of letters, digits and `-` starting with a letter"
187            ));
188        }
189        params["id"] = json!(id);
190        if super::components::is_acomp_feature_type(ty) {
191            if !object.contains_key("isFixed") {
192                params.as_object_mut().unwrap().remove("isFixed");
193            }
194            // Occurrence attributes live in the ACOMP's `bom` record — the
195            // one the BOM reads. A params-level `occurrenceAttributes` (the
196            // key this path once wrote) is folded into it.
197            let record = super::bom::OCCURRENCE_ATTRIBUTES;
198            if let Some(legacy) = params.as_object_mut().and_then(|p| p.remove("occurrenceAttributes")) {
199                merge(&mut params[record], &legacy);
200            }
201            if let Some(attributes) = item.get("attributes") {
202                if !attributes.is_object() {
203                    return Err(format!("features[{i}].attributes must be an object"));
204                }
205                merge(&mut params[record], attributes);
206            }
207            if let Some(key) = params[record].as_object().and_then(|object| {
208                object.keys().find(|key| super::part_mass::PART_ONLY_KEYS.contains(&key.as_str())).cloned()
209            }) {
210                return Err(format!(
211                    "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`)"
212                ));
213            }
214            if let Some(name) = item.get("display_name") {
215                params[record]["Name"] = name.clone();
216            }
217            // `material` is a PART attribute: `author_batch` writes it onto
218            // the placed part's own document, never onto this occurrence.
219        }
220        if let Some(alias) = item.get("alias") {
221            let alias = alias
222                .as_str()
223                .filter(|s| !s.is_empty() && !s.contains(['@', '/', ':']))
224                .ok_or_else(|| format!("features[{i}].alias: invalid alias"))?;
225            if aliases.insert(alias.into(), id.clone()).is_some() {
226                return Err(format!("features[{i}].alias: duplicate alias {alias}"));
227            }
228        }
229        brep_kernel::feature_pipeline::validate_literal_feature_params(schema["type"].as_str().unwrap_or_default(), &params)?;
230        features.push(json!({"type":schema["type"], "inputParams":params, "persistentData":item.get("persistent_data").or_else(|| item.get("persistentData")).cloned().unwrap_or(json!({}))}));
231    }
232    Ok(features)
233}
234
235/// Stable topological order; dependencies include explicit `depends_on` aliases
236/// and alias references anywhere in parameters or persistent data.
237fn plan(
238    items: &[Value],
239    features: &[Value],
240    aliases: &BTreeMap<String, String>,
241) -> Result<(Vec<usize>, Vec<Vec<usize>>), String> {
242    let positions: BTreeMap<&str, usize> = features
243        .iter()
244        .enumerate()
245        .map(|(i, f)| (f["inputParams"]["id"].as_str().unwrap(), i))
246        .collect();
247    let mut deps = vec![Vec::new(); features.len()];
248    for (i, feature) in features.iter().enumerate() {
249        let mut refs = Vec::new();
250        strings(&feature["inputParams"], &mut refs);
251        strings(&feature["persistentData"], &mut refs);
252        if let Some(explicit) = items[i].get("depends_on") {
253            let a = explicit
254                .as_array()
255                .ok_or_else(|| format!("features[{i}].depends_on must be an array"))?;
256            for r in a {
257                refs.push(format!(
258                    "@{}",
259                    r.as_str().ok_or("depends_on entries must be aliases")?
260                ));
261            }
262        }
263        for r in refs {
264            validate_reference(&r, aliases).map_err(|error| format!("features[{i}]: {error}"))?;
265            if let Some((a, _)) = alias_ref(&r) {
266                let id = &aliases[a];
267                if let Some(&p) = positions.get(id.as_str()) {
268                    deps[i].push(p);
269                }
270            }
271        }
272        deps[i].sort_unstable();
273        deps[i].dedup();
274    }
275    let mut order = Vec::new();
276    while order.len() < features.len() {
277        let Some(i) = (0..features.len())
278            .find(|i| !order.contains(i) && deps[*i].iter().all(|d| order.contains(d)))
279        else {
280            return Err(format!(
281                "dependency cycle among feature positions {:?}",
282                (0..features.len())
283                    .filter(|i| !order.contains(i))
284                    .collect::<Vec<_>>()
285            ));
286        };
287        order.push(i);
288    }
289    Ok((order, deps))
290}
291
292/// What [`EngineState::stage_feature_begin`] keeps until the run lands.
293#[derive(Debug, Clone)]
294pub(crate) struct StagedFeature {
295    id: String,
296    before: History,
297    metadata: crate::metadata::MetadataStore,
298    library: brep_kernel::PartsLibraryMap,
299    staged: History,
300    /// `History::edit_serial` right after the staged feature was appended.
301    edit_serial: u64,
302}
303
304/// Why the user's edits are refused while a structured batch evaluates.
305const BATCH_BUSY: &str = "an agent's change to this document is still evaluating";
306
307/// Where a structured batch is ([`EngineState::author_batch_begin`]).
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309enum BatchStep {
310    Parts,
311    Document,
312    Items,
313    Constraints,
314    Finish,
315    Restoring,
316    Done,
317}
318
319/// What one step of a batch asks of [`EngineState::author_batch_advance`].
320enum Flow {
321    /// Go on: the engine's own run (if one was started) is checked first.
322    Go,
323    /// A part engine's run is still in flight: answer "not yet".
324    Wait,
325    /// The batch's evaluation ended with this result body.
326    Ran(Value),
327}
328
329/// A part engine's batch: waiting to start, or started.
330enum PartWork {
331    Args(Value),
332    Job(Box<BatchJob>),
333}
334
335/// A structured batch in flight: everything `author_batch` used to keep on
336/// its stack across its (blocking) waits, so the waits can be frames.
337pub(crate) struct BatchJob {
338    args: Value,
339    items: Vec<Value>,
340    rollback: bool,
341    before: History,
342    metadata: crate::metadata::MetadataStore,
343    library: brep_kernel::PartsLibraryMap,
344    staged: History,
345    document: Value,
346    aliases: BTreeMap<String, String>,
347    part_aliases: BTreeMap<String, BTreeMap<String, String>>,
348    part_work: Vec<(String, Value)>,
349    constraint_ids: Vec<String>,
350    features: Vec<Value>,
351    order: Vec<usize>,
352    deps: Vec<Vec<usize>>,
353    step: BatchStep,
354    part_results: Vec<Value>,
355    /// The part definition being compiled, on an engine of its own: its
356    /// batch arguments until the engine's first (empty-recipe) run lands,
357    /// then its batch.
358    part: Option<(Box<EngineState>, PartWork)>,
359    next_part: usize,
360    prepared_library: brep_kernel::PartsLibraryMap,
361    outputs: BTreeMap<String, Vec<String>>,
362    results: Vec<Value>,
363    failed_items: BTreeSet<usize>,
364    next_order: usize,
365    /// The item whose run is in flight, with its partial result row.
366    running: Option<(usize, Value)>,
367    constraints: Option<Value>,
368    constraint_errors: BTreeMap<String, String>,
369    run: Option<Result<Value, String>>,
370    restore: bool,
371}
372
373fn failed(report: &Value) -> bool {
374    report.get("error").is_some()
375        || [
376            "featureErrors",
377            "displayErrors",
378            "unresolved",
379            "featureFulfilment",
380        ]
381        .iter()
382        .any(|key| match &report[*key] {
383            Value::Object(o) => !o.is_empty(),
384            Value::Array(a) => !a.is_empty(),
385            _ => false,
386        })
387}
388
389fn refusal_category(refusal: &Value) -> &'static str {
390    match refusal["class"].as_str() {
391        Some("degenerate_arrangement" | "non_integral_genus" | "invalid_result_topology") => {
392            "invalid_topology"
393        }
394        Some("tangent_node_singularity" | "conservative_empty_overlap") => "contact_related",
395        Some("non_convergence") => "numerical_nonconvergence",
396        Some("invalid_input") => "invalid_input",
397        Some("unsupported_geometry") => "unsupported_geometry",
398        _ => "geometry_execution_failure",
399    }
400}
401
402impl EngineState {
403    /// Full diagnostics from the last batch, including a rolled-back attempt.
404    pub fn geometry_diagnostics(&self, id: &str) -> Option<Value> {
405        self.geometry_diagnostics.get(id).cloned()
406    }
407
408    /// Wait on the installed native runner, preserving its resident geometry
409    /// and delta baseline. A transaction is one app command, so other commands
410    /// cannot observe its intermediate recipes. Kernel operations are not
411    /// preemptible inside a feature.
412    /// Stage ONE feature without waiting for it (an agent's `cad.*` write,
413    /// contract §5.1/§6): snapshot the recipe, metadata and parts library,
414    /// append the seeded, validated feature and hand its run to the runner,
415    /// then return. [`Self::stage_feature_poll`] finishes it on the frame the
416    /// run lands — committing it as one undo checkpoint, or restoring the
417    /// snapshot if it failed — so no frame waits for geometry. One stage at a
418    /// time per document; `item` is a batch item (`{type, params, …}`).
419    pub fn stage_feature_begin(&mut self, item: &Value) -> Result<String, String> {
420        if self.staged_feature.is_some() {
421            return Err("document_busy: a staged feature is still evaluating".into());
422        }
423        if self.batch_job.is_some() {
424            return Err("document_busy: an agent's batch is still evaluating".into());
425        }
426        if self.run_pending() || self.queries_pending() || self.mesh_imports_pending() || self.topology_pending() {
427            return Err("wait for pending engine work before staging a feature".into());
428        }
429        if let Some(reason) = self.history.locked() {
430            return Err(format!("document is locked: {reason}"));
431        }
432        let before = self.history.clone();
433        let metadata = self.metadata.clone();
434        let library = brep_kernel::parts_library_map();
435        let mut staged = before.clone();
436        let mut aliases = BTreeMap::new();
437        if item.get("material").is_some() {
438            return Err("material is a PART attribute: set it with bom_set_part_attribute, or in a feature_add_many part's document".into());
439        }
440        let features = prepare(&self.feature_catalogue(), std::slice::from_ref(item), &mut staged, &mut aliases)?;
441        let feature = features.into_iter().next().ok_or("nothing to stage")?;
442        let id = feature["inputParams"]["id"].as_str().ok_or("the staged feature has no id")?.to_string();
443        let mut validation: Value = serde_json::from_str(&before.request_json()).map_err(|e| e.to_string())?;
444        validation["features"].as_array_mut().ok_or("document features missing")?.push(feature.clone());
445        serde_json::from_value::<HistoryRequest>(validation).map_err(|e| format!("stage validation: {e}"))?;
446        self.add_features(&[feature]);
447        // The user may keep editing while the run evaluates (the frame is
448        // not held): the serial after OUR write tells the finish whether
449        // anything else wrote the recipe meanwhile.
450        let edit_serial = self.history.edit_serial();
451        // Until it lands, the user's own edits to this document are refused
452        // (and said), not interleaved with the agent's.
453        self.history.set_busy(Some("an agent's change to this document is still evaluating".into()));
454        self.staged_feature = Some(StagedFeature { id: id.clone(), before, metadata, library, staged, edit_serial });
455        Ok(id)
456    }
457
458    /// Whether a feature is staged and its run has not been finished yet.
459    pub fn stage_feature_pending(&self) -> bool {
460        self.staged_feature.is_some()
461    }
462
463    /// Finish a staged feature once its run has landed: `None` while it is
464    /// still evaluating, else its row `{id, committed, status,
465    /// generatedSolids, error}`.
466    pub fn stage_feature_poll(&mut self) -> Option<Result<Value, String>> {
467        if self.staged_feature.is_none() || self.run_pending() {
468            return None;
469        }
470        let st = self.staged_feature.take()?;
471        self.history.set_busy(None);
472        // Say any refused user edit now: a restore below replaces the history
473        // that counted it.
474        if self.history.busy_refused() > self.busy_refused_seen {
475            self.push_notice("Not applied: an agent's change to this document was still evaluating. Try again.");
476        }
477        let report: Value = serde_json::from_str(&self.history_report_json()).unwrap_or(Value::Null);
478        let id = st.id.clone();
479        let names: Vec<String> = serde_json::from_value(report["featureOutputs"][&id].clone()).unwrap_or_default();
480        let errors: Vec<String> = report["featureErrors"]
481            .as_array()
482            .into_iter()
483            .flatten()
484            .filter_map(Value::as_str)
485            .filter(|e| e.starts_with(&format!("{id}:")))
486            .map(|e| e.chars().take(240).collect())
487            .collect();
488        let evaluated = report["featureTimings"].get(&id).is_some();
489        let failed = !errors.is_empty() || report["featureFulfilment"].get(&id).is_some() || report.get("error").is_some() || !evaluated;
490        // Did a user edit the recipe while it evaluated?
491        let interleaved = self.history.edit_serial() != st.edit_serial;
492        if failed && interleaved {
493            // Restoring the snapshot would throw the user's edit away: remove
494            // only the staged feature, and keep everything else as it is now.
495            if let Some(index) = self.history.index_of(&id) {
496                self.history.remove_feature(index);
497            }
498            self.rerun_history();
499            let why = if errors.is_empty() { "the feature did not evaluate".to_string() } else { errors.join("; ") };
500            self.busy_refused_seen = self.history.busy_refused();
501            return Some(Ok(json!({ "id": id, "committed": false, "status": "failed", "generatedSolids": [], "error": why, "rolledBack": true, "interleavedEdit": true })));
502        }
503        if failed {
504            // Restore the snapshot exactly; the display re-runs on its own.
505            self.history = st.before;
506            self.metadata = st.metadata;
507            brep_kernel::install_parts_library(&Default::default());
508            brep_kernel::install_parts_library(&st.library);
509            self.rerun_history();
510            let why = if errors.is_empty() { "the feature did not evaluate".to_string() } else { errors.join("; ") };
511            self.busy_refused_seen = self.history.busy_refused();
512            return Some(Ok(json!({ "id": id, "committed": false, "status": "failed", "generatedSolids": [], "error": why, "rolledBack": true })));
513        }
514        if interleaved {
515            // The user's own edits sit on the undo stack beside ours: leave the
516            // stack as it is rather than fold them into the agent's step.
517            self.history.retain_feature_allocations(&st.staged);
518            self.busy_refused_seen = self.history.busy_refused();
519            return Some(Ok(json!({ "id": id, "committed": true, "status": "evaluated", "generatedSolids": names, "rolledBack": false, "interleavedEdit": true })));
520        }
521        // One undo checkpoint for the staged write, as a batch commits.
522        let final_document = self.history.request_json();
523        self.history = st.before;
524        if let Err(e) = self.history.adopt_document_checkpointed(&final_document) {
525            return Some(Err(e));
526        }
527        self.history.retain_feature_allocations(&st.staged);
528        self.history.set_rollback(self.history.len().saturating_sub(1));
529        self.busy_refused_seen = self.history.busy_refused();
530        Some(Ok(json!({ "id": id, "committed": true, "status": "evaluated", "generatedSolids": names, "rolledBack": false })))
531    }
532
533    /// Wait for the run in flight (tests drive a threaded engine with it).
534    #[cfg_attr(not(test), allow(dead_code))]
535    fn finish_batch_run(&mut self) {
536        while self.run_pending() {
537            self.pump();
538            #[cfg(not(target_arch = "wasm32"))]
539            if self.run_pending() {
540                std::thread::sleep(std::time::Duration::from_millis(1));
541            }
542        }
543    }
544
545    /// Full-document rollback includes recipe, library, metadata, counters and
546    /// undo/redo. Runtime caches and the generation counter are deliberately
547    /// invalidated, not rewound. No file, network or document-tab side effects.
548    ///
549    /// This form WAITS for every run of the batch: for a nested part engine,
550    /// a test, or a host with no frame to keep. The app's command never calls
551    /// it — it steps [`Self::author_batch_begin`] / [`Self::author_batch_poll`]
552    /// once per frame, so a long batch (a 9 s extrude of a traced logo) never
553    /// holds the window's frame thread.
554    pub fn author_batch(&mut self, args: &Value) -> Result<Value, String> {
555        let mut job = self.author_batch_prepare(args)?;
556        loop {
557            if let Some(result) = self.author_batch_advance(&mut job) {
558                return result;
559            }
560            #[cfg(not(target_arch = "wasm32"))]
561            std::thread::sleep(std::time::Duration::from_millis(1));
562        }
563    }
564
565    /// Start a structured batch without waiting for its geometry: validation
566    /// and every write happen here or in later [`Self::author_batch_poll`]s,
567    /// each of which only hands runs to the runner and reads what landed.
568    /// `Ok(Some(result))` when it finished at once (an inline runner, or a
569    /// refusal), `Ok(None)` while it evaluates. User edits to the document
570    /// are refused (and said) until it ends, as for a staged feature.
571    pub fn author_batch_begin(&mut self, args: &Value) -> Result<Option<Value>, String> {
572        let mut job = self.author_batch_prepare(args)?;
573        match self.author_batch_advance(&mut job) {
574            Some(result) => result.map(Some),
575            None => {
576                self.batch_job = Some(Box::new(job));
577                Ok(None)
578            }
579        }
580    }
581
582    /// Step the batch [`Self::author_batch_begin`] left running: `None` while
583    /// it still evaluates (or none is running), else its result (once).
584    pub fn author_batch_poll(&mut self) -> Option<Result<Value, String>> {
585        let mut job = self.batch_job.take()?;
586        let result = self.author_batch_advance(&mut job);
587        if result.is_none() {
588            self.batch_job = Some(job);
589        }
590        result
591    }
592
593    /// Whether a batch started by [`Self::author_batch_begin`] is still running.
594    pub fn author_batch_pending(&self) -> bool {
595        self.batch_job.is_some()
596    }
597
598    /// A write the batch itself makes: let it past the busy flag that
599    /// refuses the user's edits while the batch runs.
600    fn batch_write<R>(&mut self, write: impl FnOnce(&mut Self) -> R) -> R {
601        let reason = self.history.busy().map(str::to_owned);
602        self.history.set_busy(None);
603        let result = write(self);
604        self.history.set_busy(reason);
605        result
606    }
607
608    /// Validate a batch and plan it, touching no live state.
609    fn author_batch_prepare(&mut self, args: &Value) -> Result<BatchJob, String> {
610        if cfg!(target_arch = "wasm32") {
611            return Err("structured native authoring requires a native MCP host".into());
612        }
613        if self.batch_job.is_some() || self.staged_feature.is_some() {
614            return Err("document_busy: an agent's change to this document is still evaluating".into());
615        }
616        if self.run_pending()
617            || self.queries_pending()
618            || self.mesh_imports_pending()
619            || self.topology_pending()
620        {
621            return Err("wait for pending engine work before authoring a batch".into());
622        }
623        if let Some(reason) = self.history.locked() {
624            return Err(format!("document is locked: {reason}"));
625        }
626        let items = args["features"]
627            .as_array()
628            .ok_or("features must be an array")?;
629        let rollback = args["rollback_on_error"].as_bool().unwrap_or(false);
630        let before = self.history.clone();
631        let metadata = self.metadata.clone();
632        let library = brep_kernel::parts_library_map();
633        let mut staged = before.clone();
634        let mut document: Value =
635            serde_json::from_str(&staged.request_json()).map_err(|e| e.to_string())?;
636        let mut aliases = BTreeMap::new();
637        let mut part_aliases = BTreeMap::new();
638        let mut part_work = Vec::new();
639        let mut constraint_ids = Vec::new();
640        if let Some(parts) = args.get("parts") {
641            for (i, part) in parts
642                .as_array()
643                .ok_or("parts must be an array")?
644                .iter()
645                .enumerate()
646            {
647                let alias = part["alias"]
648                    .as_str()
649                    .filter(|s| !s.is_empty() && !s.contains(['@', '/', ':']))
650                    .ok_or_else(|| format!("parts[{i}].alias is required"))?;
651                if aliases.insert(alias.into(), alias.into()).is_some()
652                    || document["partsLibrary"].get(alias).is_some()
653                {
654                    return Err(format!("parts[{i}]: duplicate part {alias}"));
655                }
656                let mut doc = part["document"].clone();
657                let native = doc["features"]
658                    .as_array()
659                    .ok_or_else(|| format!("parts[{i}].document.features must be an array"))?
660                    .clone();
661                let mut allocation_base = doc.clone();
662                allocation_base["features"] = json!([]);
663                let mut part_history = History::from_request_json(&allocation_base.to_string())?;
664                let mut local_aliases = BTreeMap::new();
665                let mut scope = EngineState::new();
666                scope.inherit_plugins(self);
667                scope.history = part_history.clone();
668                let mut prepared = prepare(&scope.feature_catalogue(), &native, &mut part_history, &mut local_aliases)
669                    .map_err(|e| format!("parts[{i}].document.{e}"))?;
670                let _ = plan(&native, &prepared, &local_aliases)
671                    .map_err(|e| format!("parts[{i}].document.{e}"))?;
672                for (index, f) in prepared.iter_mut().enumerate() {
673                    for key in ["alias", "depends_on"] {
674                        if let Some(value) = native[index].get(key) {
675                            f[key] = value.clone();
676                        }
677                    }
678                }
679                part_aliases.insert(alias.to_owned(), local_aliases);
680                // Keep client order for result positions; the isolated batch
681                // below executes its own dependency plan.
682                doc["features"] = json!(prepared);
683                doc["featureCounter"] = serde_json::from_str::<Value>(&part_history.request_json())
684                    .unwrap_or_default()["featureCounter"]
685                    .clone();
686                part_work.push((alias.to_owned(), doc.clone()));
687                document["partsLibrary"][alias] = json!({"sourceKey":alias,"sourceSignature":"batch", "document":doc,"snapshot":""});
688            }
689        }
690        let features = prepare(&self.feature_catalogue(), items, &mut staged, &mut aliases)?;
691        // `material` on a component names the PART's material: it goes onto
692        // the part's own `partAttributes`. Only a part this batch defines can
693        // take it here (an existing library part is edited through
694        // `bom_set_part_attribute`, which also writes the kernel store), and
695        // two components of one part must agree.
696        let mut materials: BTreeMap<String, Value> = BTreeMap::new();
697        for (i, item) in items.iter().enumerate() {
698            let Some(material) = item.get("material") else { continue };
699            let part = features[i]["inputParams"]["partName"].as_str().unwrap_or_default();
700            let part = part.strip_prefix('@').unwrap_or(part).to_string();
701            if !part_work.iter().any(|(alias, _)| *alias == part) {
702                return Err(format!(
703                    "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)"
704                ));
705            }
706            if let Some(previous) = materials.insert(part.clone(), material.clone()) {
707                if previous != *material {
708                    return Err(format!(
709                        "features[{i}].material: part '{part}' is given two materials ({previous} and {material}); a material belongs to the part, so its components must agree"
710                    ));
711                }
712            }
713        }
714        for (part, material) in materials {
715            for (alias, doc) in part_work.iter_mut() {
716                if *alias == part {
717                    doc[super::bom::PART_ATTRIBUTES]["Material"] = material.clone();
718                    document["partsLibrary"][alias.as_str()]["document"] = doc.clone();
719                }
720            }
721        }
722        let (order, deps) = plan(items, &features, &aliases)?;
723        document["featureCounter"] = serde_json::from_str::<Value>(&staged.request_json())
724            .unwrap_or_default()["featureCounter"]
725            .clone();
726        if let Some(expressions) = args.get("expressions") {
727            let Some(script) = expressions.as_str() else {
728                return Err("expressions must be a script string".into());
729            };
730            // Stored one statement per line, like every expressions write.
731            document["expressions"] = Value::String(brep_kernel::format_expressions(script));
732        }
733        // Constraints use the native catalogue and descriptor shape.
734        if let Some(constraints) = args.get("constraints") {
735            let catalogue = brep_kernel::constraint_schema_catalogue();
736            let mut counter = document["assembly"]["idCounter"].as_u64().unwrap_or(0);
737            for (i, constraint) in constraints
738                .as_array()
739                .ok_or("constraints must be an array")?
740                .iter()
741                .enumerate()
742            {
743                let ty = constraint["type"]
744                    .as_str()
745                    .ok_or("constraint type is required")?;
746                if ty == "fixed" {
747                    return Err(format!("constraints[{i}].type: {}", brep_kernel::FIXED_IS_NOT_A_CONSTRAINT));
748                }
749                let entry = catalogue
750                    .as_array()
751                    .and_then(|a| a.iter().find(|e| e["type"].as_str() == Some(ty)))
752                    .ok_or_else(|| format!("constraints[{i}].type: unknown constraint {ty}"))?;
753                counter += 1;
754                let id = format!("{}{}", entry["shortName"].as_str().unwrap_or("C"), counter);
755                let mut params = json!({});
756                if let Some(schema) = entry["inputParamsSchema"].as_object() {
757                    for (k, v) in schema {
758                        params[k] = v["default_value"].clone();
759                    }
760                }
761                merge(
762                    &mut params,
763                    constraint
764                        .get("params")
765                        .or_else(|| constraint.get("inputParams"))
766                        .unwrap_or(&json!({})),
767                );
768                for key in params
769                    .as_object()
770                    .ok_or_else(|| format!("constraints[{i}].params must be an object"))?
771                    .keys()
772                {
773                    if entry["inputParamsSchema"].get(key).is_none() {
774                        return Err(format!("constraints[{i}].params.{key}: unknown field"));
775                    }
776                }
777                constraint_ids.push(id.clone());
778                params["id"] = json!(id);
779                validate_references(&params, &aliases, &format!("constraints[{i}].params"))?;
780                if let Some(a) = constraint["alias"].as_str() {
781                    if aliases.insert(a.into(), id).is_some() {
782                        return Err(format!("constraints[{i}].alias is duplicate"));
783                    }
784                }
785                if !document["assembly"]["constraints"].is_array() {
786                    document["assembly"]["constraints"] = json!([]);
787                }
788                let mut persistent = constraint
789                    .get("persistent_data")
790                    .or_else(|| constraint.get("persistentData"))
791                    .cloned()
792                    .unwrap_or(json!({}));
793                validate_references(
794                    &persistent,
795                    &aliases,
796                    &format!("constraints[{i}].persistentData"),
797                )?;
798                let explicit = constraint
799                    .get("params")
800                    .or_else(|| constraint.get("inputParams"));
801                // Interactive creation adopts a measurement on its first solve.
802                // A batch's explicitly supplied target already expresses intent.
803                for (field, flag) in [
804                    ("distance", "initializedDistance"),
805                    ("angle", "initializedAngle"),
806                ] {
807                    if explicit.is_some_and(|p| p.get(field).is_some()) {
808                        persistent
809                            .as_object_mut()
810                            .ok_or_else(|| {
811                                format!("constraints[{i}].persistent_data must be an object")
812                            })?
813                            .entry(flag)
814                            .or_insert(json!(true));
815                    }
816                }
817                document["assembly"]["constraints"].as_array_mut().unwrap().push(json!({"type":ty,"inputParams":params,"persistentData":persistent,"enabled":constraint.get("enabled").cloned().unwrap_or(json!(true))}));
818            }
819            document["assembly"]["idCounter"] = json!(counter);
820        }
821        if let Some(patch) = args.get("metadata") {
822            let map = patch.as_object().ok_or("metadata must be an object")?;
823            for key in map.keys() {
824                if let Some((a, _)) = alias_ref(key) {
825                    if !aliases.contains_key(a) {
826                        return Err(format!("metadata.{key}: missing alias @{a}"));
827                    }
828                }
829            }
830        }
831        // Parse the entire proposed request before touching any live state.
832        let mut validation = document.clone();
833        validation["features"]
834            .as_array_mut()
835            .ok_or("document features missing")?
836            .extend(features.clone());
837        serde_json::from_value::<HistoryRequest>(validation)
838            .map_err(|e| format!("batch validation: {e}"))?;
839        self.geometry_diagnostics.clear();
840        self.history.set_busy(Some(BATCH_BUSY.into()));
841        Ok(BatchJob {
842            args: args.clone(),
843            items: items.clone(),
844            rollback,
845            before,
846            metadata,
847            library,
848            staged,
849            document,
850            aliases,
851            part_aliases,
852            part_work,
853            constraint_ids,
854            features,
855            order,
856            deps,
857            step: BatchStep::Parts,
858            part_results: Vec::new(),
859            part: None,
860            next_part: 0,
861            prepared_library: Default::default(),
862            outputs: BTreeMap::new(),
863            results: vec![Value::Null; items.len()],
864            failed_items: BTreeSet::new(),
865            next_order: 0,
866            running: None,
867            constraints: None,
868            constraint_errors: BTreeMap::new(),
869            run: None,
870            restore: false,
871        })
872    }
873
874    /// Advance the batch as far as it goes without waiting for a run: `None`
875    /// while one is in flight (the caller steps it again later), else its
876    /// result. Never sleeps and never blocks on the runner.
877    fn author_batch_advance(&mut self, job: &mut BatchJob) -> Option<Result<Value, String>> {
878        loop {
879            if self.run_pending() {
880                self.pump();
881                if self.run_pending() {
882                    return None;
883                }
884            }
885            let flow = match job.step {
886                BatchStep::Parts => self.batch_parts(job),
887                BatchStep::Document => self.batch_document(job),
888                BatchStep::Items => self.batch_items(job),
889                BatchStep::Constraints => self.batch_constraints(job),
890                BatchStep::Finish => self.batch_finish(job).map(Flow::Ran),
891                BatchStep::Restoring => {
892                    self.batch_restored(job);
893                    continue;
894                }
895                BatchStep::Done => return Some(self.batch_conclude(job)),
896            };
897            match flow {
898                Ok(Flow::Go) => {}
899                Ok(Flow::Wait) => return None,
900                Ok(Flow::Ran(value)) => self.batch_settle(job, Ok(value)),
901                Err(error) => self.batch_settle(job, Err(error)),
902            }
903        }
904    }
905
906    /// Compile each native part definition in isolation first, one engine
907    /// per part. This resolves generated-output aliases inside part histories
908    /// too, without turning the part into an imported/baked solid. The part
909    /// engine has a runner thread of its own, so its compile is stepped like
910    /// the document's runs, never run on the caller's thread.
911    fn batch_parts(&mut self, job: &mut BatchJob) -> Result<Flow, String> {
912        if let Some((part, work)) = job.part.as_mut() {
913            let part_job = match work {
914                PartWork::Job(part_job) => part_job,
915                PartWork::Args(part_args) => {
916                    // The engine's first run (its empty recipe) must land
917                    // before its batch may start.
918                    if part.run_pending() {
919                        part.pump();
920                        if part.run_pending() {
921                            return Ok(Flow::Wait);
922                        }
923                    }
924                    let part_job = part.author_batch_prepare(part_args)?;
925                    *work = PartWork::Job(Box::new(part_job));
926                    let PartWork::Job(part_job) = work else { unreachable!() };
927                    part_job
928                }
929            };
930            let Some(result) = part.author_batch_advance(part_job) else {
931                return Ok(Flow::Wait);
932            };
933            let (part, _) = job.part.take().expect("the part engine being stepped");
934            let mut evaluated = result?;
935            let position = job.next_part;
936            let alias = job.part_work[position].0.clone();
937            for (id, details) in &part.geometry_diagnostics {
938                self.geometry_diagnostics
939                    .insert(format!("part:{alias}:{id}"), details.clone());
940            }
941            for item in evaluated["items"].as_array_mut().into_iter().flatten() {
942                if let Some(id) = item["diagnostic"]["detailId"].as_str().map(str::to_owned) {
943                    item["diagnostic"]["detailId"] = json!(format!("part:{alias}:{id}"));
944                }
945            }
946            job.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"]}));
947            if evaluated["success"] != true {
948                for (i, (remaining, _)) in job.part_work.iter().enumerate().skip(position + 1) {
949                    job.part_results.push(json!({"position":i,"alias":remaining,"id":remaining,"status":"not_evaluated","committed":false}));
950                }
951                let pending: Vec<Value> = job.items.iter().enumerate().map(|(i,item)| json!({"position":i,"alias":item["alias"],"id":job.features[i]["inputParams"]["id"],"status":"not_evaluated","committed":false,"dependencyFailure":{"part":alias}})).collect();
952                return Ok(Flow::Ran(
953                    json!({"success":false,"requiresRestore":true,"items":pending,"partResults":job.part_results,"constraintResults":[],"aliases":job.aliases,"partAliases":job.part_aliases,"diagnosticsTool":"geometry_diagnostics"}),
954                ));
955            }
956            job.document["partsLibrary"][alias.as_str()]["document"] =
957                serde_json::from_str::<Value>(&part.history_request_json())
958                    .map_err(|e| e.to_string())?;
959            job.next_part += 1;
960            return Ok(Flow::Go);
961        }
962        let Some((_, source)) = job.part_work.get(job.next_part).cloned() else {
963            job.step = BatchStep::Document;
964            return Ok(Flow::Go);
965        };
966        let mut base = source.clone();
967        let part_features = base["features"].take();
968        base["features"] = json!([]);
969        base.as_object_mut().unwrap().remove("metadata");
970        let mut part = EngineState::new();
971        #[cfg(not(target_arch = "wasm32"))]
972        part.set_runner(Box::new(crate::runner::ThreadRunner::new()));
973        part.inherit_plugins(self);
974        part.set_history_json(&base.to_string())?;
975        let mut part_args = json!({"features":part_features,"rollback_on_error":true});
976        if let Some(metadata) = source.get("metadata") {
977            part_args["metadata"] = metadata.clone();
978        }
979        job.part = Some((Box::new(part), PartWork::Args(part_args)));
980        Ok(Flow::Go)
981    }
982
983    /// Install the batch's parts library and recipe (constraints wait until
984    /// every instance exists).
985    fn batch_document(&mut self, job: &mut BatchJob) -> Result<Flow, String> {
986        job.constraints = job.document.get("assembly").cloned();
987        job.document.as_object_mut().unwrap().remove("assembly");
988        let document = job.document.to_string();
989        self.batch_write(|engine| engine.edit_document_json(&document))?;
990        job.prepared_library =
991            serde_json::from_value(job.document.get("partsLibrary").cloned().unwrap_or(json!({})))
992                .map_err(|e| format!("partsLibrary: {e}"))?;
993        job.step = BatchStep::Items;
994        Ok(Flow::Go)
995    }
996
997    /// One item per call: read what the last item's run produced, then hand
998    /// the next item's run to the runner.
999    fn batch_items(&mut self, job: &mut BatchJob) -> Result<Flow, String> {
1000        if let Some((i, mut result)) = job.running.take() {
1001            let id = job.features[i]["inputParams"]["id"].as_str().unwrap().to_string();
1002            let report: Value =
1003                serde_json::from_str(&self.history_report_json()).map_err(|e| e.to_string())?;
1004            let names: Vec<String> =
1005                serde_json::from_value(report["featureOutputs"][&id].clone())
1006                    .unwrap_or_default();
1007            job.outputs.insert(id.clone(), names.clone());
1008            let errors: Vec<Value> = report["featureErrors"]
1009                .as_array()
1010                .into_iter()
1011                .flatten()
1012                .filter(|e| e.as_str().is_some_and(|e| e.starts_with(&format!("{id}:"))))
1013                .cloned()
1014                .collect();
1015            let has_error = !errors.is_empty()
1016                || report["featureFulfilment"].get(&id).is_some()
1017                || report.get("error").is_some();
1018            if has_error {
1019                job.failed_items.insert(i);
1020            }
1021            result["status"] = json!(if has_error {
1022                "failed"
1023            } else if report["featureTimings"].get(&id).is_some() {
1024                "evaluated"
1025            } else {
1026                "not_evaluated"
1027            });
1028            if result["status"] == "not_evaluated" {
1029                job.failed_items.insert(i);
1030            }
1031            result["generatedSolids"] = json!(names);
1032            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":job.features[i]["type"],"operands":job.features[i]["inputParams"],"dependencies":job.deps[i]}));
1033            result["error"] = json!(errors
1034                .iter()
1035                .filter_map(Value::as_str)
1036                .map(|s| s.chars().take(240).collect::<String>())
1037                .collect::<Vec<_>>());
1038            let mut references = Vec::new();
1039            for name in &names {
1040                if let Some(solid) = self.scene.solid(name) {
1041                    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<_>>()}));
1042                }
1043            }
1044            job.outputs.insert(
1045                format!("{id}/face"),
1046                references
1047                    .iter()
1048                    .flat_map(|r| r["faces"].as_array().into_iter().flatten())
1049                    .filter_map(Value::as_str)
1050                    .map(str::to_owned)
1051                    .collect(),
1052            );
1053            job.outputs.insert(
1054                format!("{id}/edge"),
1055                references
1056                    .iter()
1057                    .flat_map(|r| r["edges"].as_array().into_iter().flatten())
1058                    .filter_map(Value::as_str)
1059                    .map(str::to_owned)
1060                    .collect(),
1061            );
1062            result["generatedReferences"] = json!(references);
1063            let schema = self
1064                .feature_schema(job.features[i]["type"].as_str().unwrap_or(""))
1065                .unwrap_or_default();
1066            let operands: serde_json::Map<String, Value> = job.features[i]["inputParams"]
1067                .as_object()
1068                .into_iter()
1069                .flat_map(|o| o.iter())
1070                .filter(|(k, _)| {
1071                    matches!(
1072                        schema["inputParamsSchema"][*k]["type"].as_str(),
1073                        Some("reference_selection" | "boolean_operation")
1074                    ) || k.as_str() == "partName"
1075                })
1076                .map(|(k, v)| (k.clone(), v.clone()))
1077                .collect();
1078            result["diagnostic"] = json!({"operation":job.features[i]["type"],"owningComponent": if super::components::is_acomp_feature_type(job.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});
1079            result["committed"] = json!(true);
1080            job.results[i] = result;
1081            return Ok(Flow::Go);
1082        }
1083        while let Some(&i) = job.order.get(job.next_order) {
1084            job.next_order += 1;
1085            let id = job.features[i]["inputParams"]["id"].as_str().unwrap().to_string();
1086            let blocked: Vec<usize> = job.deps[i]
1087                .iter()
1088                .filter(|d| job.failed_items.contains(*d))
1089                .copied()
1090                .collect();
1091            let mut result = json!({"position":i,"alias":job.items[i]["alias"],"id":id,"committed":false,"dependencies":job.deps[i]});
1092            if !blocked.is_empty() {
1093                job.failed_items.insert(i);
1094                result["status"] = json!("not_evaluated");
1095                result["dependencyFailures"] = json!(blocked);
1096                job.results[i] = result;
1097                continue;
1098            }
1099            if let Err(error) = resolve(&mut job.features[i], &job.aliases, &job.outputs) {
1100                job.failed_items.insert(i);
1101                result["status"] = json!("failed");
1102                result["error"] = json!({"category":"reference_resolution","message":error,"path":format!("features[{i}]")});
1103                job.results[i] = result;
1104                continue;
1105            }
1106            brep_kernel::install_parts_library(&job.prepared_library);
1107            self.history.set_parts_library(
1108                serde_json::to_value(brep_kernel::parts_library_map())
1109                    .map_err(|e| e.to_string())?,
1110            );
1111            let feature = job.features[i].clone();
1112            self.batch_write(|engine| engine.add_features(&[feature]));
1113            job.running = Some((i, result));
1114            return Ok(Flow::Go);
1115        }
1116        job.step = BatchStep::Constraints;
1117        Ok(Flow::Go)
1118    }
1119
1120    /// Resolve and install the constraints once every instance exists.
1121    fn batch_constraints(&mut self, job: &mut BatchJob) -> Result<Flow, String> {
1122        job.step = BatchStep::Finish;
1123        let Some(mut constraints) = job.constraints.take() else {
1124            return Ok(Flow::Go);
1125        };
1126        if let Some(entries) = constraints["constraints"].as_array_mut() {
1127            let (aliases, outputs, errors) = (&job.aliases, &job.outputs, &mut job.constraint_errors);
1128            entries.retain_mut(|entry| {
1129                let id = entry["inputParams"]["id"].as_str().unwrap_or("").to_owned();
1130                if let Err(error) = resolve(entry, aliases, outputs) {
1131                    errors.insert(id, error);
1132                    false
1133                } else {
1134                    true
1135                }
1136            });
1137        }
1138        let mut final_doc: Value =
1139            serde_json::from_str(&self.history.request_json()).map_err(|e| e.to_string())?;
1140        final_doc["assembly"] = constraints;
1141        let document = final_doc.to_string();
1142        self.batch_write(|engine| engine.edit_document_json(&document))?;
1143        Ok(Flow::Go)
1144    }
1145
1146    /// Metadata, then the batch's result rows.
1147    fn batch_finish(&mut self, job: &mut BatchJob) -> Result<Value, String> {
1148        if let Some(patch) = job.args.get("metadata").and_then(Value::as_object) {
1149            let mut merged = self.metadata.to_json();
1150            for (key, record) in patch {
1151                let mut name = json!(key);
1152                resolve(&mut name, &job.aliases, &job.outputs)?;
1153                merge(&mut merged[name.as_str().unwrap()], record);
1154            }
1155            self.metadata.load_json(Some(&merged));
1156            self.sync_colors_from_metadata();
1157        }
1158        let final_report: Value =
1159            serde_json::from_str(&self.history_report_json()).map_err(|e| e.to_string())?;
1160        let statuses = self.assembly_statuses_value();
1161        let constraint_failure = statuses.as_array().is_some_and(|a| {
1162            a.iter()
1163                .any(|s| s["enabled"] != false && s["satisfied"] == false)
1164        });
1165        let success = job.failed_items.is_empty()
1166            && !failed(&final_report)
1167            && !constraint_failure
1168            && job.constraint_errors.is_empty();
1169        let constraint_results: Vec<Value> = job.constraint_ids.iter().enumerate().map(|(i,id)| {
1170            let row = statuses.as_array().and_then(|a| a.iter().find(|r| r["id"].as_str() == Some(id)));
1171            let state = if job.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" };
1172            json!({"position":i,"alias":job.args["constraints"][i]["alias"],"id":id,"status":state,"committed":!job.constraint_errors.contains_key(id),"error":job.constraint_errors.get(id),"diagnostics":row,"dependencyFailures":if job.constraint_errors.contains_key(id) { job.failed_items.iter().copied().collect::<Vec<_>>() } else { vec![] }})
1173        }).collect();
1174        // Keep explicitly supplied definitions, including ones not yet
1175        // instantiated. Normal library GC still applies on later edits.
1176        let mut retained_library = brep_kernel::parts_library_map();
1177        for (alias, _) in &job.part_work {
1178            if let Some(entry) = job.prepared_library.get(alias) {
1179                retained_library
1180                    .entry(alias.clone())
1181                    .or_insert_with(|| entry.clone());
1182            }
1183        }
1184        brep_kernel::install_parts_library(&retained_library);
1185        self.history.set_parts_library(
1186            serde_json::to_value(&retained_library).map_err(|e| e.to_string())?,
1187        );
1188        for result in &mut job.part_results {
1189            result["committed"] = json!(true);
1190        }
1191        self.geometry_diagnostics
1192            .insert("__report__".into(), final_report);
1193        Ok(json!({"success":success,"items":job.results,"partResults":job.part_results,"constraintResults":constraint_results,"aliases":job.aliases,"partAliases":job.part_aliases,"outputs":job.outputs,"diagnosticsTool":"geometry_diagnostics","constraintStatuses":statuses,"dof":self.assembly_dof_value()}))
1194    }
1195
1196    /// The run is over: restore the snapshot (and re-run it) when it failed
1197    /// or rolls back, else collapse its rebuilds into one undo checkpoint.
1198    fn batch_settle(&mut self, job: &mut BatchJob, run: Result<Value, String>) {
1199        if self.history.busy_refused() > self.busy_refused_seen {
1200            self.push_notice("Not applied: an agent's change to this document was still evaluating. Try again.");
1201        }
1202        let restore = run
1203            .as_ref()
1204            .map(|r| r["requiresRestore"] == true || (job.rollback && r["success"] != true))
1205            .unwrap_or(true);
1206        job.run = Some(run);
1207        job.restore = restore;
1208        if restore {
1209            self.history = job.before.clone();
1210            self.metadata = job.metadata.clone();
1211            brep_kernel::install_parts_library(&Default::default());
1212            brep_kernel::install_parts_library(&job.library);
1213            self.rerun_history();
1214            // Still refuse the user's edits while the restoring run evaluates.
1215            self.history.set_busy(Some(BATCH_BUSY.into()));
1216            job.step = BatchStep::Restoring;
1217        } else {
1218            // Collapse the staged rebuilds into a single user undo checkpoint.
1219            let final_document = self.history.request_json();
1220            self.history = job.before.clone();
1221            match self.history.adopt_document_checkpointed(&final_document) {
1222                Ok(_) => {
1223                    self.history.retain_feature_allocations(&job.staged);
1224                    self.history
1225                        .set_rollback(self.history.len().saturating_sub(1));
1226                }
1227                Err(error) => job.run = Some(Err(error)),
1228            }
1229            job.step = BatchStep::Done;
1230        }
1231    }
1232
1233    /// The restoration rebuild has landed. It may heal/GC library entries or
1234    /// fold a solver pose: preserve the exact pre-transaction authored state.
1235    fn batch_restored(&mut self, job: &mut BatchJob) {
1236        self.history = job.before.clone();
1237        self.metadata = job.metadata.clone();
1238        brep_kernel::install_parts_library(&Default::default());
1239        brep_kernel::install_parts_library(&job.library);
1240        job.step = BatchStep::Done;
1241    }
1242
1243    fn batch_conclude(&mut self, job: &mut BatchJob) -> Result<Value, String> {
1244        self.busy_refused_seen = self.history.busy_refused();
1245        let restore = job.restore;
1246        let mut result = job.run.take().unwrap_or_else(|| Err("batch did not run".into()))?;
1247        result.as_object_mut().unwrap().remove("requiresRestore");
1248        result["rolledBack"] = json!(restore);
1249        result["transaction"] = json!({"validationAtomic":true,"geometryAtomic":job.rollback,"idCountersRolledBack":restore,"runtimeGenerationRolledBack":false});
1250        if restore {
1251            fn uncommit(value: &mut Value) {
1252                match value {
1253                    Value::Object(object) => {
1254                        if object.contains_key("committed") {
1255                            object.insert("committed".into(), json!(false));
1256                        }
1257                        for value in object.values_mut() {
1258                            uncommit(value);
1259                        }
1260                    }
1261                    Value::Array(array) => {
1262                        for value in array {
1263                            uncommit(value);
1264                        }
1265                    }
1266                    _ => (),
1267                }
1268            }
1269            uncommit(&mut result);
1270        }
1271        Ok(result)
1272    }
1273}
1274
1275/// Transform strings are expressions, including strings nested in vec3s.
1276pub(super) fn contains_expression(value: &Value) -> bool {
1277    match value {
1278        Value::String(_) => true,
1279        Value::Array(a) => a.iter().any(contains_expression),
1280        Value::Object(o) => o.values().any(contains_expression),
1281        _ => false,
1282    }
1283}
1284
1285
1286
1287
1288
1289