gollum-ir 0.4.0

Intermediate Representation for the Gollum language
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
//! IR representation of planning actions.
//!
//! [`IrAction`] captures the STRIPS-style structure of a planning action:
//! a name, typed parameters, preconditions that gate applicability, and
//! effects that describe world changes after execution.  Optional
//! [`IrMetadata`] allows attaching probabilistic weights or costs for
//! probabilistic and neurosymbolic planning.
//!
//! Call [`IrAction::validate`] after construction to check structural
//! consistency before the action enters the planning pipeline.

use std::collections::HashSet;

use serde::{Deserialize, Serialize};

use crate::metadata::IrMetadata;
use crate::term::IrTerm;

// ── Validation error ──────────────────────────────────────────────────────────

/// Errors produced by [`IrAction::validate`].
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ActionValidationError {
    /// The action name is empty.
    #[error("action name must not be empty")]
    EmptyName,

    /// A parameter name is used more than once.
    #[error("duplicate parameter name: {0:?}")]
    DuplicateParameter(String),

    /// A variable appearing in the preconditions or effects is not declared as
    /// a parameter.  The contained string is the variable name, and the second
    /// field indicates where it was found.
    #[error("undeclared variable {0:?} in {1}")]
    UndeclaredVariable(String, &'static str),
}

/// IR-level representation of a planning action.
///
/// Follows the classical STRIPS action schema (Fikes & Nilsson, 1971):
/// an action is applicable in a state when all its `preconditions` hold,
/// and executing it produces the `effects`.
///
/// # Example
///
/// ```rust
/// use gollum_ir::{IrAction, IrTerm};
///
/// let move_action = IrAction {
///     name: "move".into(),
///     parameters: vec!["X".into(), "Y".into()],
///     preconditions: vec![
///         IrTerm::Structure {
///             name: "at".into(),
///             args: vec![IrTerm::Var("X".into())],
///         },
///         IrTerm::Structure {
///             name: "connected".into(),
///             args: vec![IrTerm::Var("X".into()), IrTerm::Var("Y".into())],
///         },
///     ],
///     effects: vec![
///         IrTerm::Structure {
///             name: "at".into(),
///             args: vec![IrTerm::Var("Y".into())],
///         },
///         IrTerm::Structure {
///             name: "not".into(),
///             args: vec![IrTerm::Structure {
///                 name: "at".into(),
///                 args: vec![IrTerm::Var("X".into())],
///             }],
///         },
///     ],
///     metadata: None,
/// };
/// assert_eq!(move_action.name, "move");
/// assert_eq!(move_action.parameters.len(), 2);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IrAction {
    /// Name of the action, e.g. `"move"` or `"pickup"`.
    pub name: String,
    /// Parameter names (variables) shared across preconditions and effects.
    pub parameters: Vec<String>,
    /// Conditions that must hold in the current state for this action to be
    /// applicable.
    pub preconditions: Vec<IrTerm>,
    /// Terms describing world changes after the action executes.  Positive
    /// terms are added; terms wrapped in `not(…)` represent deletions.
    pub effects: Vec<IrTerm>,
    /// Optional reasoning metadata (probability, cost, temporal bounds, …).
    pub metadata: Option<IrMetadata>,
}

// ── impl IrAction ─────────────────────────────────────────────────────────────

impl IrAction {
    /// Validate the structural consistency of this action.
    ///
    /// Checks performed:
    ///
    /// 1. `name` is non-empty.
    /// 2. `parameters` contains no duplicates.
    /// 3. Every `Var` node inside `preconditions` names a declared parameter.
    /// 4. Every `Var` node inside `effects` names a declared parameter.
    ///
    /// Anonymous variables (names starting with `_`) are allowed anywhere
    /// without being declared as parameters.
    ///
    /// Returns `Ok(())` on success or the first [`ActionValidationError`]
    /// encountered.
    pub fn validate(&self) -> Result<(), ActionValidationError> {
        // 1. Non-empty name.
        if self.name.is_empty() {
            return Err(ActionValidationError::EmptyName);
        }

        // 2. No duplicate parameter names.
        let mut seen: HashSet<&str> = HashSet::new();
        for p in &self.parameters {
            if !seen.insert(p.as_str()) {
                return Err(ActionValidationError::DuplicateParameter(p.clone()));
            }
        }
        let declared: HashSet<&str> = self.parameters.iter().map(String::as_str).collect();

        // 3. Variables in preconditions must be declared.
        for term in &self.preconditions {
            if let Some(v) = find_undeclared_var(term, &declared) {
                return Err(ActionValidationError::UndeclaredVariable(v, "preconditions"));
            }
        }

        // 4. Variables in effects must be declared.
        for term in &self.effects {
            if let Some(v) = find_undeclared_var(term, &declared) {
                return Err(ActionValidationError::UndeclaredVariable(v, "effects"));
            }
        }

        Ok(())
    }
}

/// Walk `term` recursively and return the first `Var` whose name is not in
/// `declared` and does not start with `_` (anonymous variables are exempt).
fn find_undeclared_var(term: &IrTerm, declared: &HashSet<&str>) -> Option<String> {
    match term {
        IrTerm::Var(name) => {
            if !name.starts_with('_') && !declared.contains(name.as_str()) {
                Some(name.clone())
            } else {
                None
            }
        }
        IrTerm::Structure { args, .. } => {
            args.iter().find_map(|a| find_undeclared_var(a, declared))
        }
        IrTerm::Typed { term: inner, .. }
        | IrTerm::Neural { term: inner, .. }
        | IrTerm::Differentiable { term: inner, .. } => find_undeclared_var(inner, declared),
        IrTerm::DiffNeural { term: inner, .. } => find_undeclared_var(inner, declared),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(loc: &str) -> IrTerm {
        IrTerm::Structure { name: "at".into(), args: vec![IrTerm::Atom(loc.into())] }
    }

    fn at_var(v: &str) -> IrTerm {
        IrTerm::Structure { name: "at".into(), args: vec![IrTerm::Var(v.into())] }
    }

    fn connected(x: &str, y: &str) -> IrTerm {
        IrTerm::Structure {
            name: "connected".into(),
            args: vec![IrTerm::Var(x.into()), IrTerm::Var(y.into())],
        }
    }

    fn not_term(inner: IrTerm) -> IrTerm {
        IrTerm::Structure { name: "not".into(), args: vec![inner] }
    }

    #[test]
    fn test_move_action_fields() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into(), "Y".into()],
            preconditions: vec![at_var("X"), connected("X", "Y")],
            effects: vec![at_var("Y"), not_term(at_var("X"))],
            metadata: None,
        };
        assert_eq!(action.name, "move");
        assert_eq!(action.parameters, vec!["X", "Y"]);
        assert_eq!(action.preconditions.len(), 2);
        assert_eq!(action.effects.len(), 2);
        assert!(action.metadata.is_none());
    }

    #[test]
    fn test_ground_action_no_parameters() {
        let action = IrAction {
            name: "open_door".into(),
            parameters: vec![],
            preconditions: vec![at("locked")],
            effects: vec![at("unlocked"), not_term(at("locked"))],
            metadata: None,
        };
        assert!(action.parameters.is_empty());
        assert_eq!(action.preconditions.len(), 1);
        assert_eq!(action.effects.len(), 2);
    }

    #[test]
    fn test_action_with_metadata() {
        let action = IrAction {
            name: "risky_move".into(),
            parameters: vec!["X".into()],
            preconditions: vec![at_var("X")],
            effects: vec![],
            metadata: Some(IrMetadata { probability: Some(0.8), ..IrMetadata::default() }),
        };
        assert_eq!(
            action.metadata.as_ref().and_then(|m| m.probability),
            Some(0.8)
        );
    }

    #[test]
    fn test_serde_roundtrip() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into(), "Y".into()],
            preconditions: vec![at_var("X"), connected("X", "Y")],
            effects: vec![at_var("Y"), not_term(at_var("X"))],
            metadata: None,
        };
        let s = ron::to_string(&action).expect("serialize failed");
        let back: IrAction = ron::from_str(&s).expect("deserialize failed");
        assert_eq!(action, back);
    }

    #[test]
    fn test_serde_roundtrip_with_metadata() {
        let action = IrAction {
            name: "probabilistic_move".into(),
            parameters: vec!["X".into()],
            preconditions: vec![],
            effects: vec![at_var("X")],
            metadata: Some(IrMetadata { probability: Some(0.5), ..IrMetadata::default() }),
        };
        let s = ron::to_string(&action).expect("serialize failed");
        let back: IrAction = ron::from_str(&s).expect("deserialize failed");
        assert_eq!(action, back);
    }

    #[test]
    fn test_clone_and_eq() {
        let a = IrAction {
            name: "jump".into(),
            parameters: vec!["X".into()],
            preconditions: vec![at_var("X")],
            effects: vec![],
            metadata: None,
        };
        let b = a.clone();
        assert_eq!(a, b);
    }

    // ── validate() tests ──────────────────────────────────────────────────────

    #[test]
    fn test_validate_well_formed_parametric_action() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into(), "Y".into()],
            preconditions: vec![at_var("X"), connected("X", "Y")],
            effects: vec![at_var("Y"), not_term(at_var("X"))],
            metadata: None,
        };
        assert!(action.validate().is_ok());
    }

    #[test]
    fn test_validate_well_formed_ground_action() {
        let action = IrAction {
            name: "open_door".into(),
            parameters: vec![],
            preconditions: vec![at("locked")],
            effects: vec![at("unlocked"), not_term(at("locked"))],
            metadata: None,
        };
        assert!(action.validate().is_ok());
    }

    #[test]
    fn test_validate_empty_name_is_error() {
        let action = IrAction {
            name: "".into(),
            parameters: vec![],
            preconditions: vec![],
            effects: vec![],
            metadata: None,
        };
        assert_eq!(action.validate(), Err(ActionValidationError::EmptyName));
    }

    #[test]
    fn test_validate_duplicate_parameter_is_error() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into(), "X".into()],
            preconditions: vec![at_var("X")],
            effects: vec![],
            metadata: None,
        };
        assert_eq!(
            action.validate(),
            Err(ActionValidationError::DuplicateParameter("X".into()))
        );
    }

    #[test]
    fn test_validate_undeclared_variable_in_preconditions() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into()],
            // Y is not declared as a parameter
            preconditions: vec![connected("X", "Y")],
            effects: vec![],
            metadata: None,
        };
        assert_eq!(
            action.validate(),
            Err(ActionValidationError::UndeclaredVariable("Y".into(), "preconditions"))
        );
    }

    #[test]
    fn test_validate_undeclared_variable_in_effects() {
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into()],
            preconditions: vec![at_var("X")],
            // Z is not declared as a parameter
            effects: vec![IrTerm::Structure {
                name: "at".into(),
                args: vec![IrTerm::Var("Z".into())],
            }],
            metadata: None,
        };
        assert_eq!(
            action.validate(),
            Err(ActionValidationError::UndeclaredVariable("Z".into(), "effects"))
        );
    }

    #[test]
    fn test_validate_anonymous_variable_is_allowed() {
        // Anonymous variables (starting with _) need not be declared.
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into()],
            preconditions: vec![IrTerm::Structure {
                name: "edge".into(),
                args: vec![IrTerm::Var("X".into()), IrTerm::Var("_".into())],
            }],
            effects: vec![],
            metadata: None,
        };
        assert!(action.validate().is_ok());
    }

    #[test]
    fn test_validate_nested_undeclared_variable_is_detected() {
        // Z is nested inside not(at(Z)) in effects.
        let action = IrAction {
            name: "move".into(),
            parameters: vec!["X".into()],
            preconditions: vec![],
            effects: vec![not_term(IrTerm::Structure {
                name: "at".into(),
                args: vec![IrTerm::Var("Z".into())],
            })],
            metadata: None,
        };
        assert_eq!(
            action.validate(),
            Err(ActionValidationError::UndeclaredVariable("Z".into(), "effects"))
        );
    }

    #[test]
    fn test_validate_empty_preconditions_and_effects_is_ok() {
        let action = IrAction {
            name: "noop".into(),
            parameters: vec![],
            preconditions: vec![],
            effects: vec![],
            metadata: None,
        };
        assert!(action.validate().is_ok());
    }
}