Skip to main content

sim_lib_auto_order/
conformance.rs

1//! Modeled work-order conformance runner.
2
3use std::{collections::BTreeSet, sync::Arc};
4
5use sim_kernel::{
6    CapabilityName, Consistency, Cx, Error, EvalFabric, EvalMode, EvalRequest, Expr, Result, Symbol,
7};
8use sim_lib_auto_core::{
9    AUTO_DIAGNOSTICS_READ, AUTO_FLASH, AUTO_ORDER, AUTO_SERVICE_WRITE, SiteManifest, VehicleId,
10};
11use sim_lib_auto_parts::{OrderStatus, Supplier};
12use sim_lib_auto_vendor::{
13    AutomotiveGateRecords, ModeledVendorBridge, VendorSiteFabric, autotuner_manifest,
14    biluppgifter_se_manifest, esitronic_manifest, flash_site_cassettes, haynespro_manifest,
15    ista_manifest, manifest_operation, mekonomen_pro_manifest, odis_manifest, oem_site_cassettes,
16    supplier_site_cassettes, vendor_irreversible_request_expr, vendor_request_expr, vida_manifest,
17    xentry_manifest,
18};
19use sim_lib_operation_gate::ExecutionMode;
20
21use crate::{
22    ConformanceReport, LedgerInvoiceExport, WorkOrder, WorkOrderEvent, model::WorkOrderEventInput,
23};
24
25/// Runs the public modeled automotive work-order conformance story.
26pub fn run_modeled_conformance(cx: &mut Cx) -> Result<ConformanceReport> {
27    run_modeled_conformance_with_parent_grants(cx, default_parent_grants())
28}
29
30/// Runs conformance with an explicit parent grant set.
31pub fn run_modeled_conformance_with_parent_grants(
32    cx: &mut Cx,
33    parent_grants: Vec<CapabilityName>,
34) -> Result<ConformanceReport> {
35    ModeledWorkOrderEngine::new(parent_grants).run(cx)
36}
37
38/// Returns the site labels covered by the modeled conformance story.
39pub fn expected_modeled_sites() -> Vec<&'static str> {
40    vec![
41        "xentry",
42        "ista",
43        "vida",
44        "odis",
45        "esitronic",
46        "haynespro",
47        "biluppgifter-se",
48        "mekonomen-pro",
49        "autotuner",
50    ]
51}
52
53/// Manifest-driven engine for a modeled work-order conformance story.
54#[derive(Clone, Debug)]
55pub struct ModeledWorkOrderEngine {
56    parent_grants: Vec<CapabilityName>,
57}
58
59impl ModeledWorkOrderEngine {
60    /// Builds an engine with the parent session grants.
61    pub fn new(parent_grants: Vec<CapabilityName>) -> Self {
62        Self { parent_grants }
63    }
64
65    /// Runs the conformance story.
66    pub fn run(&self, cx: &mut Cx) -> Result<ConformanceReport> {
67        cx.require_all(&self.parent_grants)?;
68        let mut work_order = WorkOrder::new(
69            "SIM-WO-MBTECH-1",
70            VehicleId::new("modeled-se", "vehicle-alpha"),
71            self.parent_grants.clone(),
72        );
73        let mut issues = Vec::new();
74        let mut delegation_violations = Vec::new();
75        let expected_sites = expected_modeled_sites();
76
77        for story in site_stories() {
78            self.run_story(
79                cx,
80                story,
81                &mut work_order,
82                &mut issues,
83                &mut delegation_violations,
84            )?;
85        }
86
87        if let Some(order) = &work_order.order_status {
88            work_order.invoice = Some(LedgerInvoiceExport::for_work_order(
89                &work_order.id,
90                order,
91                &work_order.parts,
92                90,
93            ));
94        } else {
95            issues.push("mekonomen-pro order/place did not produce an order status".to_owned());
96        }
97
98        let seen_sites = work_order.ledger.sites();
99        for expected in &expected_sites {
100            if !seen_sites.contains(*expected) {
101                issues.push(format!("missing modeled site {expected}"));
102            }
103        }
104        if !has_denial(&work_order, "xentry", "code/sca", AUTO_SERVICE_WRITE) {
105            issues.push("missing denied xentry code/sca event".to_owned());
106        }
107        if !has_denial(&work_order, "autotuner", "flash/write", AUTO_FLASH) {
108            issues.push("missing denied autotuner flash/write event".to_owned());
109        }
110
111        Ok(ConformanceReport::new(
112            work_order,
113            expected_sites.len(),
114            delegation_violations,
115            issues,
116        ))
117    }
118
119    fn run_story(
120        &self,
121        cx: &mut Cx,
122        story: SiteStory,
123        work_order: &mut WorkOrder,
124        issues: &mut Vec<String>,
125        delegation_violations: &mut Vec<String>,
126    ) -> Result<()> {
127        let bridge = Arc::new(ModeledVendorBridge::with_cassettes(all_cassettes()));
128        let gate_records = Arc::new(AutomotiveGateRecords::new());
129        let fabric = VendorSiteFabric::with_gate_records(
130            story.manifest.clone(),
131            bridge,
132            Arc::clone(&gate_records),
133        );
134        for operation in story.operations {
135            let operation_policy = manifest_operation(&story.manifest, operation)?;
136            let delegated = self.delegated_grants(&operation_policy.declaration.capability);
137            let before = gate_records.records()?.len();
138            let outcome = fabric.realize(
139                cx,
140                request(
141                    operation,
142                    operation_policy.declaration.mode,
143                    delegated.clone(),
144                ),
145            );
146            let event = match outcome {
147                Ok(_) => {
148                    if let Some(violation) =
149                        delegated_violation(&delegated, &self.parent_grants, operation)
150                    {
151                        delegation_violations.push(violation);
152                    }
153                    if operation == "order/place" {
154                        work_order.order_status = Some(OrderStatus::accepted(
155                            "SIM-ORDER-MBTECH-1",
156                            Supplier::MekonomenProModeled,
157                            work_order.parts.len() as u32,
158                        ));
159                    }
160                    WorkOrderEvent::from_input(WorkOrderEventInput {
161                        site: story.manifest.site.clone(),
162                        operation: operation.to_owned(),
163                        lane: operation_policy.lane.name,
164                        capability: operation_policy.declaration.capability.clone(),
165                        effect: mode_name(operation_policy.declaration.mode).to_owned(),
166                        outcome: "accepted".to_owned(),
167                        note: gate_note(&gate_records, before)?,
168                        delegated_capabilities: delegated,
169                    })
170                }
171                Err(Error::CapabilityDenied { capability }) => {
172                    WorkOrderEvent::from_input(WorkOrderEventInput {
173                        site: story.manifest.site.clone(),
174                        operation: operation.to_owned(),
175                        lane: operation_policy.lane.name,
176                        capability: operation_policy.declaration.capability.clone(),
177                        effect: mode_name(operation_policy.declaration.mode).to_owned(),
178                        outcome: "denied".to_owned(),
179                        note: format!("denied missing {}", capability.as_str()),
180                        delegated_capabilities: delegated,
181                    })
182                }
183                Err(err) => {
184                    issues.push(format!(
185                        "{} {} failed: {err}",
186                        story.manifest.site, operation
187                    ));
188                    WorkOrderEvent::from_input(WorkOrderEventInput {
189                        site: story.manifest.site.clone(),
190                        operation: operation.to_owned(),
191                        lane: operation_policy.lane.name,
192                        capability: operation_policy.declaration.capability.clone(),
193                        effect: mode_name(operation_policy.declaration.mode).to_owned(),
194                        outcome: "failed".to_owned(),
195                        note: err.to_string(),
196                        delegated_capabilities: delegated,
197                    })
198                }
199            };
200            work_order.ledger.push(event);
201        }
202        Ok(())
203    }
204
205    fn delegated_grants(&self, required: &CapabilityName) -> Vec<CapabilityName> {
206        if self.parent_grants.iter().any(|grant| grant == required) {
207            vec![required.clone()]
208        } else {
209            Vec::new()
210        }
211    }
212}
213
214fn default_parent_grants() -> Vec<CapabilityName> {
215    vec![
216        CapabilityName::new(AUTO_DIAGNOSTICS_READ),
217        CapabilityName::new(AUTO_ORDER),
218    ]
219}
220
221#[derive(Clone, Debug)]
222struct SiteStory {
223    manifest: SiteManifest,
224    operations: Vec<&'static str>,
225}
226
227impl SiteStory {
228    fn new(manifest: SiteManifest, operations: Vec<&'static str>) -> Self {
229        Self {
230            manifest,
231            operations,
232        }
233    }
234}
235
236fn site_stories() -> Vec<SiteStory> {
237    vec![
238        SiteStory::new(
239            xentry_manifest(),
240            vec![
241                "read/dtc",
242                "info/wis-procedure",
243                "parts/epc-lookup",
244                "code/sca",
245            ],
246        ),
247        SiteStory::new(
248            ista_manifest(),
249            vec!["read/dtc", "info/test-plan", "code/coding"],
250        ),
251        SiteStory::new(vida_manifest(), vec!["read/dtc", "info/procedure"]),
252        SiteStory::new(odis_manifest(), vec!["service/guided-function"]),
253        SiteStory::new(esitronic_manifest(), vec!["read/dtc", "info/procedure"]),
254        SiteStory::new(
255            haynespro_manifest(),
256            vec!["read/identity", "info/procedure"],
257        ),
258        SiteStory::new(biluppgifter_se_manifest(), vec!["read/plate-lookup"]),
259        SiteStory::new(
260            mekonomen_pro_manifest(),
261            vec!["parts/catalog-lookup", "order/status", "order/place"],
262        ),
263        SiteStory::new(autotuner_manifest(), vec!["flash/write"]),
264    ]
265}
266
267fn all_cassettes() -> Vec<sim_lib_auto_vendor::ModeledVendorCassette> {
268    oem_site_cassettes()
269        .into_iter()
270        .chain(supplier_site_cassettes())
271        .chain(flash_site_cassettes())
272        .collect()
273}
274
275fn request(
276    operation: &str,
277    mode: ExecutionMode,
278    required_capabilities: Vec<CapabilityName>,
279) -> EvalRequest {
280    let expr = if mode == ExecutionMode::Reviewed {
281        vendor_irreversible_request_expr(
282            operation,
283            story_args(),
284            reversal_artifact(operation),
285            "modeled-work-order-warrant",
286        )
287    } else {
288        vendor_request_expr(operation, story_args())
289    };
290    EvalRequest {
291        expr,
292        result_shape: None,
293        required_capabilities,
294        deadline: None,
295        consistency: Consistency::LocalFirst,
296        mode: EvalMode::Eval,
297        answer_limit: None,
298        stream_buffer: None,
299        stream: false,
300        trace: false,
301    }
302}
303
304fn story_args() -> Expr {
305    Expr::Map(vec![
306        string_field("work-order", "SIM-WO-MBTECH-1"),
307        string_field("vehicle", "modeled-se/vehicle-alpha"),
308    ])
309}
310
311fn reversal_artifact(operation: &str) -> Expr {
312    Expr::Map(vec![
313        (
314            Expr::Symbol(Symbol::new("content-key")),
315            Expr::String(format!("stock-map-before-{operation}")),
316        ),
317        (
318            Expr::Symbol(Symbol::new("bytes")),
319            Expr::Bytes(operation.as_bytes().to_vec()),
320        ),
321    ])
322}
323
324fn string_field(name: &str, value: &str) -> (Expr, Expr) {
325    (
326        Expr::Symbol(Symbol::new(name.to_owned())),
327        Expr::String(value.to_owned()),
328    )
329}
330
331fn gate_note(ledger: &AutomotiveGateRecords, before: usize) -> Result<String> {
332    let records = ledger.records()?;
333    if records.len() > before {
334        Ok(format!("vendor gate recorded {}", records.len() - before))
335    } else {
336        Ok("pure manifest reply".to_owned())
337    }
338}
339
340fn mode_name(mode: ExecutionMode) -> &'static str {
341    match mode {
342        ExecutionMode::Observation => "observation",
343        ExecutionMode::Recorded => "recorded",
344        ExecutionMode::Reviewed => "reviewed",
345    }
346}
347
348fn delegated_violation(
349    delegated: &[CapabilityName],
350    parent_grants: &[CapabilityName],
351    operation: &str,
352) -> Option<String> {
353    let parent = parent_grants.iter().collect::<BTreeSet<_>>();
354    delegated
355        .iter()
356        .find(|capability| !parent.contains(*capability))
357        .map(|capability| {
358            format!(
359                "{operation} delegated {} outside parent grant set",
360                capability.as_str()
361            )
362        })
363}
364
365fn has_denial(work_order: &WorkOrder, site: &str, operation: &str, capability: &str) -> bool {
366    work_order.ledger.events.iter().any(|event| {
367        event.site == site
368            && event.operation == operation
369            && event.capability == capability
370            && event.denied()
371    })
372}