mdvault-core 0.7.2

Core library for mdvault - markdown vault management
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Hook execution for lifecycle events.
//!
//! This module provides functions to run lifecycle hooks defined in type definitions.

use super::engine::LuaEngine;
use super::hooks::{HookError, NoteContext};
use super::types::SandboxConfig;
use super::vault_context::VaultContext;
use crate::types::definition::TypeDefinition;
use crate::types::validation::yaml_to_lua_table;
use tracing::debug;

/// Result of running a hook that may modify the note.
#[derive(Debug)]
pub struct HookResult {
    /// Whether the hook made changes to the note.
    pub modified: bool,
    /// The updated frontmatter (if modified).
    pub frontmatter: Option<serde_yaml::Value>,
    /// The updated content (if modified).
    pub content: Option<String>,
    /// The updated template variables (if modified).
    pub variables: Option<serde_yaml::Value>,
}

/// Alias for backwards compatibility.
pub type UpdateHookResult = HookResult;

/// Run the `on_create` hook for a type definition.
///
/// This function is called after a note is created to allow the type definition
/// to perform additional operations like logging to daily notes, updating indexes,
/// or modifying the note's frontmatter.
///
/// # Arguments
///
/// * `typedef` - The type definition containing the hook
/// * `note_ctx` - Context about the created note
/// * `vault_ctx` - Vault context with access to repositories
///
/// # Returns
///
/// * `Ok(HookResult)` with any modifications from the hook
/// * `Err(HookError)` on failure
///
/// # Example
///
/// ```ignore
/// use mdvault_core::scripting::{run_on_create_hook, NoteContext, VaultContext};
///
/// let note_ctx = NoteContext::new(path, "task".into(), frontmatter, content, variables);
/// let result = run_on_create_hook(&typedef, &note_ctx, vault_ctx)?;
/// if result.modified {
///     // Write back the updated content
/// }
/// ```
pub fn run_on_create_hook(
    typedef: &TypeDefinition,
    note_ctx: &NoteContext,
    vault_ctx: VaultContext,
) -> Result<HookResult, HookError> {
    // Skip if no hook defined
    if !typedef.has_on_create_hook {
        return Ok(HookResult {
            modified: false,
            frontmatter: None,
            content: None,
            variables: None,
        });
    }

    // Create engine with vault context
    let engine = LuaEngine::with_vault_context(SandboxConfig::restricted(), vault_ctx)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    let lua = engine.lua();

    // Load and evaluate the type definition to get the table
    let typedef_table: mlua::Table =
        lua.load(&typedef.lua_source).eval().map_err(|e| {
            HookError::LuaError(format!("failed to load type definition: {}", e))
        })?;

    // Build note table for the hook
    let note_table =
        lua.create_table().map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("path", note_ctx.path.to_string_lossy().to_string())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("type", note_ctx.note_type.clone())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("content", note_ctx.content.clone())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    // Convert frontmatter to Lua table
    let fm_table = yaml_to_lua_table(lua, &note_ctx.frontmatter)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("frontmatter", fm_table)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    // Convert variables to Lua table
    debug!("Hook input variables: {:?}", note_ctx.variables);
    let vars_table = yaml_to_lua_table(lua, &note_ctx.variables)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("variables", vars_table)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    // Get on_create function
    let on_create_fn: mlua::Function = typedef_table.get("on_create").map_err(|e| {
        HookError::LuaError(format!("on_create function not found: {}", e))
    })?;

    // Call the hook - it may return a modified note table
    let result: mlua::Value = on_create_fn
        .call(note_table)
        .map_err(|e| HookError::Execution(format!("on_create hook failed: {}", e)))?;

    // Check if hook returned a modified note
    match result {
        mlua::Value::Table(returned_note) => {
            // Extract frontmatter, content, and variables if present
            let frontmatter: Option<serde_yaml::Value> =
                if let Ok(fm_table) = returned_note.get::<mlua::Table>("frontmatter") {
                    Some(lua_table_to_yaml(&fm_table)?)
                } else {
                    None
                };

            let content: Option<String> = returned_note.get("content").ok();
            let content = match content {
                Some(ref c) if c != &note_ctx.content => content,
                _ => None,
            };

            let variables: Option<serde_yaml::Value> =
                if let Ok(vars_table) = returned_note.get::<mlua::Table>("variables") {
                    let v = Some(lua_table_to_yaml(&vars_table)?);
                    debug!("Hook output variables: {:?}", v);
                    v
                } else {
                    None
                };

            let modified =
                frontmatter.is_some() || content.is_some() || variables.is_some();
            Ok(HookResult { modified, frontmatter, content, variables })
        }
        mlua::Value::Nil => {
            // Hook returned nil, no modifications
            Ok(HookResult {
                modified: false,
                frontmatter: None,
                content: None,
                variables: None,
            })
        }
        _ => {
            // Unexpected return type
            Ok(HookResult {
                modified: false,
                frontmatter: None,
                content: None,
                variables: None,
            })
        }
    }
}

/// Run the `on_update` hook for a type definition.
///
/// This function is called after a note is modified (via capture operations) to allow
/// the type definition to perform additional operations like updating timestamps.
///
/// Unlike `on_create`, this hook can return a modified note which will be written back.
///
/// # Arguments
///
/// * `typedef` - The type definition containing the hook
/// * `note_ctx` - Context about the updated note
/// * `vault_ctx` - Vault context with access to repositories
///
/// # Returns
///
/// * `Ok(UpdateHookResult)` with any modifications from the hook
/// * `Err(HookError)` on failure
///
/// # Example
///
/// ```ignore
/// use mdvault_core::scripting::{run_on_update_hook, NoteContext, VaultContext};
///
/// let note_ctx = NoteContext::new(path, "task".into(), frontmatter, content);
/// let result = run_on_update_hook(&typedef, &note_ctx, vault_ctx)?;
/// if result.modified {
///     // Write back the updated content
/// }
/// ```
pub fn run_on_update_hook(
    typedef: &TypeDefinition,
    note_ctx: &NoteContext,
    vault_ctx: VaultContext,
) -> Result<UpdateHookResult, HookError> {
    // Skip if no hook defined
    if !typedef.has_on_update_hook {
        return Ok(UpdateHookResult {
            modified: false,
            frontmatter: None,
            content: None,
            variables: None,
        });
    }

    // Create engine with vault context
    let engine = LuaEngine::with_vault_context(SandboxConfig::restricted(), vault_ctx)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    let lua = engine.lua();

    // Load and evaluate the type definition to get the table
    let typedef_table: mlua::Table =
        lua.load(&typedef.lua_source).eval().map_err(|e| {
            HookError::LuaError(format!("failed to load type definition: {}", e))
        })?;

    // Build note table for the hook
    let note_table =
        lua.create_table().map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("path", note_ctx.path.to_string_lossy().to_string())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("type", note_ctx.note_type.clone())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("content", note_ctx.content.clone())
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    // Convert frontmatter to Lua table
    let fm_table = yaml_to_lua_table(lua, &note_ctx.frontmatter)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    note_table
        .set("frontmatter", fm_table)
        .map_err(|e| HookError::LuaError(e.to_string()))?;

    // Get on_update function
    let on_update_fn: mlua::Function = typedef_table.get("on_update").map_err(|e| {
        HookError::LuaError(format!("on_update function not found: {}", e))
    })?;

    // Call the hook - it may return a modified note table
    let result: mlua::Value = on_update_fn
        .call(note_table)
        .map_err(|e| HookError::Execution(format!("on_update hook failed: {}", e)))?;

    // Check if hook returned a modified note
    match result {
        mlua::Value::Table(returned_note) => {
            // Extract frontmatter and content if present
            let frontmatter: Option<serde_yaml::Value> =
                if let Ok(fm_table) = returned_note.get::<mlua::Table>("frontmatter") {
                    Some(lua_table_to_yaml(&fm_table)?)
                } else {
                    None
                };

            let content: Option<String> = returned_note.get("content").ok();

            let modified = frontmatter.is_some() || content.is_some();
            Ok(UpdateHookResult { modified, frontmatter, content, variables: None })
        }
        mlua::Value::Nil => {
            // Hook returned nil, no modifications
            Ok(UpdateHookResult {
                modified: false,
                frontmatter: None,
                content: None,
                variables: None,
            })
        }
        _ => {
            // Unexpected return type
            Ok(UpdateHookResult {
                modified: false,
                frontmatter: None,
                content: None,
                variables: None,
            })
        }
    }
}

/// Convert a Lua table to serde_yaml::Value.
fn lua_table_to_yaml(table: &mlua::Table) -> Result<serde_yaml::Value, HookError> {
    let mut map = serde_yaml::Mapping::new();

    for pair in table.pairs::<mlua::Value, mlua::Value>() {
        let (key, value) = pair.map_err(|e| HookError::LuaError(e.to_string()))?;

        let yaml_key = match key {
            mlua::Value::String(s) => {
                let str_val =
                    s.to_str().map_err(|e| HookError::LuaError(e.to_string()))?;
                serde_yaml::Value::String(str_val.to_string())
            }
            mlua::Value::Integer(i) => serde_yaml::Value::Number(i.into()),
            _ => continue, // Skip non-string/integer keys
        };

        let yaml_value = lua_value_to_yaml(value)?;
        map.insert(yaml_key, yaml_value);
    }

    Ok(serde_yaml::Value::Mapping(map))
}

/// Convert a single Lua value to serde_yaml::Value.
fn lua_value_to_yaml(value: mlua::Value) -> Result<serde_yaml::Value, HookError> {
    match value {
        mlua::Value::Nil => Ok(serde_yaml::Value::Null),
        mlua::Value::Boolean(b) => Ok(serde_yaml::Value::Bool(b)),
        mlua::Value::Integer(i) => Ok(serde_yaml::Value::Number(i.into())),
        mlua::Value::Number(n) => {
            Ok(serde_yaml::Value::Number(serde_yaml::Number::from(n)))
        }
        mlua::Value::String(s) => {
            let str_val = s.to_str().map_err(|e| HookError::LuaError(e.to_string()))?;
            Ok(serde_yaml::Value::String(str_val.to_string()))
        }
        mlua::Value::Table(t) => {
            // Check if it's an array or a map
            if is_lua_array(&t) {
                let mut seq = Vec::new();
                for pair in t.pairs::<i64, mlua::Value>() {
                    let (_, v) = pair.map_err(|e| HookError::LuaError(e.to_string()))?;
                    seq.push(lua_value_to_yaml(v)?);
                }
                Ok(serde_yaml::Value::Sequence(seq))
            } else {
                lua_table_to_yaml(&t)
            }
        }
        _ => Ok(serde_yaml::Value::Null),
    }
}

/// Check if a Lua table is an array (sequential integer keys starting from 1).
fn is_lua_array(table: &mlua::Table) -> bool {
    let len = table.raw_len();
    if len == 0 {
        // Could be empty table, check for any keys
        table.pairs::<mlua::Value, mlua::Value>().next().is_none()
    } else {
        // Check if keys are 1..=len
        for i in 1..=len {
            if table.raw_get::<mlua::Value>(i).is_err() {
                return false;
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;

    fn make_typedef_with_hook(lua_source: &str) -> TypeDefinition {
        TypeDefinition {
            name: "test".to_string(),
            description: None,
            source_path: PathBuf::new(),
            schema: HashMap::new(),
            output: None,
            frontmatter_order: None,
            variables: crate::vars::VarsMap::new(),
            has_validate_fn: false,
            has_on_create_hook: true,
            has_on_update_hook: false,
            is_builtin_override: false,
            lua_source: lua_source.to_string(),
        }
    }

    fn make_note_ctx() -> NoteContext {
        NoteContext {
            path: PathBuf::from("test.md"),
            note_type: "test".to_string(),
            frontmatter: serde_yaml::Value::Mapping(serde_yaml::Mapping::new()),
            content: "# Test".to_string(),
            variables: serde_yaml::Value::Null,
        }
    }

    #[test]
    fn test_skip_if_no_hook() {
        let typedef = TypeDefinition {
            name: "test".to_string(),
            description: None,
            source_path: PathBuf::new(),
            schema: HashMap::new(),
            output: None,
            frontmatter_order: None,
            variables: crate::vars::VarsMap::new(),
            has_validate_fn: false,
            has_on_create_hook: false, // No hook
            has_on_update_hook: false,
            is_builtin_override: false,
            lua_source: String::new(),
        };

        // Create a minimal vault context - this won't be used since there's no hook
        // We can't easily create a VaultContext in tests without real repositories,
        // but since has_on_create_hook is false, it will return early
        let _note_ctx = make_note_ctx();

        // This test verifies that when has_on_create_hook is false,
        // the function returns Ok(()) without trying to access vault_ctx
        // However, we need a VaultContext to call the function...
        // For now, just test the hook detection logic works.
        assert!(!typedef.has_on_create_hook);
    }

    #[test]
    fn test_hook_receives_note_context() {
        // This test verifies the Lua hook structure works
        // We create a hook that just returns true without vault operations
        let lua_source = r#"
            return {
                on_create = function(note)
                    -- Just verify we can access note fields
                    local _ = note.path
                    local _ = note.type
                    local _ = note.content
                    local _ = note.frontmatter
                    return note
                end
            }
        "#;

        let _typedef = make_typedef_with_hook(lua_source);
        let _note_ctx = make_note_ctx();

        // Create a sandboxed engine to test the Lua code directly
        let engine = LuaEngine::sandboxed().unwrap();
        let lua = engine.lua();

        // Load the typedef
        let typedef_table: mlua::Table = lua.load(lua_source).eval().unwrap();

        // Build note table
        let note_table = lua.create_table().unwrap();
        note_table.set("path", "test.md").unwrap();
        note_table.set("type", "test").unwrap();
        note_table.set("content", "# Test").unwrap();
        let fm = lua.create_table().unwrap();
        note_table.set("frontmatter", fm).unwrap();

        // Call on_create
        let on_create: mlua::Function = typedef_table.get("on_create").unwrap();
        let result = on_create.call::<mlua::Value>(note_table);

        assert!(result.is_ok());
    }
}