logicpearl-engine 0.1.4

Library-level execution facade for LogicPearl artifacts and pipelines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use logicpearl_core::{LogicPearlError, Result, RuleMask};
use logicpearl_ir::LogicPearlGateIr;
use logicpearl_pipeline::{PipelineDefinition, PipelineExecution, PreparedPipeline};
use logicpearl_plugin::PluginExecutionPolicy;
use logicpearl_runtime::{evaluate_gate, parse_input_payload};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EngineKind {
    Artifact,
    Pipeline,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArtifactEvaluation {
    pub bitmask: RuleMask,
    pub allow: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArtifactExecution {
    pub gate_id: String,
    pub evaluation: ArtifactEvaluation,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArtifactBatchExecution {
    pub gate_id: String,
    pub evaluations: Vec<ArtifactEvaluation>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EngineSingleExecution {
    Artifact(ArtifactExecution),
    Pipeline(PipelineExecution),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EngineBatchExecution {
    Artifact(ArtifactBatchExecution),
    Pipeline(Vec<PipelineExecution>),
}

#[derive(Debug, Clone)]
pub struct LogicPearlEngine {
    kind: EngineKind,
    source_path: PathBuf,
    prepared: PreparedExecution,
}

#[derive(Debug, Clone)]
enum PreparedExecution {
    Artifact(PreparedArtifact),
    Pipeline(PreparedPipeline),
}

#[derive(Debug, Clone)]
struct PreparedArtifact {
    gate: LogicPearlGateIr,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct NamedArtifactManifest {
    files: NamedArtifactFiles,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct NamedArtifactFiles {
    pearl_ir: String,
}

impl LogicPearlEngine {
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        if looks_like_pipeline_path(path) {
            return Self::from_pipeline_path(path);
        }
        if looks_like_artifact_path(path) {
            return Self::from_artifact_path(path);
        }

        if path.is_file() {
            let content = fs::read_to_string(path)?;
            let value: Value = serde_json::from_str(&content)?;
            if value.get("pipeline_version").is_some() {
                return Self::from_pipeline_path(path);
            }
            if value.get("ir_version").is_some() || value.get("files").is_some() {
                return Self::from_artifact_path(path);
            }
        }

        if path.is_dir() {
            if path.join("pipeline.json").exists() {
                return Self::from_pipeline_path(path.join("pipeline.json"));
            }
            if path.join("artifact.json").exists() || path.join("pearl.ir.json").exists() {
                return Self::from_artifact_path(path);
            }
        }

        Err(LogicPearlError::message(format!(
            "could not determine whether {} is a LogicPearl artifact or pipeline",
            path.display()
        )))
    }

    pub fn from_artifact_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let resolved = resolve_artifact_input(path)?;
        let gate = LogicPearlGateIr::from_path(&resolved.pearl_ir)?;
        Ok(Self {
            kind: EngineKind::Artifact,
            source_path: path.to_path_buf(),
            prepared: PreparedExecution::Artifact(PreparedArtifact { gate }),
        })
    }

    pub fn from_pipeline_path(path: impl AsRef<Path>) -> Result<Self> {
        Self::from_pipeline_path_with_plugin_policy(path, PluginExecutionPolicy::default())
    }

    pub fn from_path_with_plugin_policy(
        path: impl AsRef<Path>,
        plugin_policy: PluginExecutionPolicy,
    ) -> Result<Self> {
        let path = path.as_ref();
        if looks_like_pipeline_path(path) {
            return Self::from_pipeline_path_with_plugin_policy(path, plugin_policy);
        }
        if looks_like_artifact_path(path) {
            return Self::from_artifact_path(path);
        }

        if path.is_file() {
            let content = fs::read_to_string(path)?;
            let value: Value = serde_json::from_str(&content)?;
            if value.get("pipeline_version").is_some() {
                return Self::from_pipeline_path_with_plugin_policy(path, plugin_policy);
            }
            if value.get("ir_version").is_some() || value.get("files").is_some() {
                return Self::from_artifact_path(path);
            }
        }

        if path.is_dir() {
            if path.join("pipeline.json").exists() {
                return Self::from_pipeline_path_with_plugin_policy(
                    path.join("pipeline.json"),
                    plugin_policy,
                );
            }
            if path.join("artifact.json").exists() || path.join("pearl.ir.json").exists() {
                return Self::from_artifact_path(path);
            }
        }

        Err(LogicPearlError::message(format!(
            "could not determine whether {} is a LogicPearl artifact or pipeline",
            path.display()
        )))
    }

    pub fn from_pipeline_path_with_plugin_policy(
        path: impl AsRef<Path>,
        plugin_policy: PluginExecutionPolicy,
    ) -> Result<Self> {
        let path = path.as_ref();
        let resolved_path = if path.is_dir() {
            path.join("pipeline.json")
        } else {
            path.to_path_buf()
        };
        let pipeline = PipelineDefinition::from_path(&resolved_path)?;
        let base_dir = resolved_path.parent().unwrap_or_else(|| Path::new("."));
        let prepared = pipeline.prepare_with_plugin_policy(base_dir, plugin_policy)?;
        Ok(Self {
            kind: EngineKind::Pipeline,
            source_path: resolved_path,
            prepared: PreparedExecution::Pipeline(prepared),
        })
    }

    pub fn kind(&self) -> EngineKind {
        self.kind
    }

    pub fn source_path(&self) -> &Path {
        &self.source_path
    }

    pub fn run_single_json(&self, input: &Value) -> Result<EngineSingleExecution> {
        match &self.prepared {
            PreparedExecution::Artifact(artifact) => {
                Ok(EngineSingleExecution::Artifact(ArtifactExecution {
                    gate_id: artifact.gate.gate_id.clone(),
                    evaluation: evaluate_artifact_single(&artifact.gate, input)?,
                }))
            }
            PreparedExecution::Pipeline(pipeline) => {
                Ok(EngineSingleExecution::Pipeline(pipeline.run(input)?))
            }
        }
    }

    pub fn run_batch_json(&self, inputs: &[Value]) -> Result<EngineBatchExecution> {
        match &self.prepared {
            PreparedExecution::Artifact(artifact) => {
                Ok(EngineBatchExecution::Artifact(ArtifactBatchExecution {
                    gate_id: artifact.gate.gate_id.clone(),
                    evaluations: inputs
                        .iter()
                        .map(|input| evaluate_artifact_single(&artifact.gate, input))
                        .collect::<Result<Vec<_>>>()?,
                }))
            }
            PreparedExecution::Pipeline(pipeline) => {
                Ok(EngineBatchExecution::Pipeline(pipeline.run_batch(inputs)?))
            }
        }
    }

    pub fn run_json_value(&self, input: &Value) -> Result<EngineExecutionEnvelope> {
        match input {
            Value::Array(items) => self
                .run_batch_json(items)
                .map(EngineExecutionEnvelope::Batch),
            _ => self
                .run_single_json(input)
                .map(EngineExecutionEnvelope::Single),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum EngineExecutionEnvelope {
    Single(EngineSingleExecution),
    Batch(EngineBatchExecution),
}

fn evaluate_artifact_single(gate: &LogicPearlGateIr, input: &Value) -> Result<ArtifactEvaluation> {
    let parsed = parse_input_payload(input.clone())?;
    if parsed.len() != 1 {
        return Err(LogicPearlError::message(
            "artifact single execution expects one feature object",
        ));
    }
    let bitmask = evaluate_gate(gate, &parsed[0])?;
    Ok(ArtifactEvaluation {
        allow: bitmask.is_zero(),
        bitmask,
    })
}

#[derive(Debug, Clone)]
struct ResolvedArtifactInput {
    pearl_ir: PathBuf,
}

fn resolve_artifact_input(path: &Path) -> Result<ResolvedArtifactInput> {
    if path.is_dir() {
        let manifest_path = path.join("artifact.json");
        if manifest_path.exists() {
            let manifest = load_named_artifact_manifest(&manifest_path)?;
            return Ok(ResolvedArtifactInput {
                pearl_ir: resolve_manifest_path(&manifest_path, &manifest.files.pearl_ir),
            });
        }
        let pearl_ir = path.join("pearl.ir.json");
        if pearl_ir.exists() {
            return Ok(ResolvedArtifactInput { pearl_ir });
        }
        return Err(LogicPearlError::message(format!(
            "artifact directory {} is missing artifact.json and pearl.ir.json",
            path.display()
        )));
    }

    if path
        .file_name()
        .is_some_and(|name| name == std::ffi::OsStr::new("artifact.json"))
    {
        let manifest = load_named_artifact_manifest(path)?;
        return Ok(ResolvedArtifactInput {
            pearl_ir: resolve_manifest_path(path, &manifest.files.pearl_ir),
        });
    }

    Ok(ResolvedArtifactInput {
        pearl_ir: path.to_path_buf(),
    })
}

fn load_named_artifact_manifest(path: &Path) -> Result<NamedArtifactManifest> {
    let content = fs::read_to_string(path)?;
    let manifest = serde_json::from_str(&content)?;
    Ok(manifest)
}

fn resolve_manifest_path(manifest_path: &Path, value: &str) -> PathBuf {
    let candidate = Path::new(value);
    if candidate.is_absolute() {
        candidate.to_path_buf()
    } else {
        manifest_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(candidate)
    }
}

fn looks_like_pipeline_path(path: &Path) -> bool {
    path.file_name()
        .and_then(|value| value.to_str())
        .is_some_and(|name| name.ends_with(".pipeline.json") || name == "pipeline.json")
}

fn looks_like_artifact_path(path: &Path) -> bool {
    if path.is_dir() {
        return path.join("artifact.json").exists() || path.join("pearl.ir.json").exists();
    }
    path.file_name()
        .and_then(|value| value.to_str())
        .is_some_and(|name| {
            name == "artifact.json" || name == "pearl.ir.json" || name.ends_with(".ir.json")
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::tempdir;

    fn repo_root() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .and_then(|path| path.parent())
            .expect("crate should live under workspace/crates/logicpearl-engine")
            .to_path_buf()
    }

    #[test]
    fn loads_and_runs_artifact_from_direct_ir_path() {
        let repo_root = repo_root();
        let artifact = repo_root.join("fixtures/ir/valid/auth-demo-v1.json");
        let engine = LogicPearlEngine::from_artifact_path(&artifact).expect("artifact loads");
        let result = engine
            .run_single_json(&json!({
                "action": "delete",
                "resource_archived": true,
                "user_role": "viewer",
                "failed_attempts": 99
            }))
            .expect("artifact runs");
        match result {
            EngineSingleExecution::Artifact(output) => {
                assert_eq!(output.gate_id, "auth_demo_v1");
                assert!(!output.evaluation.allow);
                assert_eq!(output.evaluation.bitmask.as_u64(), Some(7));
            }
            _ => panic!("expected artifact result"),
        }
    }

    #[test]
    fn loads_artifact_from_manifest() {
        let repo_root = repo_root();
        let dir = tempdir().expect("tempdir should exist");
        let ir_path = repo_root.join("fixtures/ir/valid/auth-demo-v1.json");
        fs::copy(&ir_path, dir.path().join("pearl.ir.json")).expect("fixture should copy");
        fs::write(
            dir.path().join("artifact.json"),
            serde_json::to_string_pretty(&json!({
                "artifact_version": "1.0",
                "artifact_name": "auth-demo",
                "gate_id": "auth_demo_v1",
                "files": {
                    "pearl_ir": "pearl.ir.json"
                }
            }))
            .expect("manifest encodes"),
        )
        .expect("manifest writes");

        let engine =
            LogicPearlEngine::from_path(dir.path()).expect("manifest-backed artifact loads");
        assert_eq!(engine.kind(), EngineKind::Artifact);
    }

    #[test]
    fn loads_and_runs_pipeline() {
        let repo_root = repo_root();
        let pipeline =
            repo_root.join("examples/pipelines/observer_membership_verify/pipeline.json");
        let input = json!({
            "age": 34,
            "member": true,
            "country": "US"
        });
        let engine = LogicPearlEngine::from_path(&pipeline).expect("pipeline loads");
        let result = engine.run_single_json(&input).expect("pipeline runs");
        match result {
            EngineSingleExecution::Pipeline(output) => {
                assert_eq!(output.output.get("allow"), Some(&json!(true)));
                assert_eq!(
                    output.output.get("audit_status"),
                    Some(&json!("clean_pass"))
                );
            }
            _ => panic!("expected pipeline result"),
        }
    }
}