progit-plugin-sdk 0.2.1

Plugin SDK for ProGit — sandboxed LuaJIT runtime with capability-based security. LSL-1.0 (file-level copyleft, proprietary plugins allowed via the commercial bridge).
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
# Plugin Development Guide

## Overview

This guide covers best practices for developing ProGit plugins using the Apache 2.0 licensed SDK.

## Plugin Types

### Lua Plugins

**Best for:**
- Simple integrations (Slack notifications, webhooks)
- Rapid prototyping
- Non-performance-critical tasks
- Scripts that need frequent updates

**Pros:**
- No compilation required
- Easy to distribute and update
- Sandboxed execution
- Familiar scripting language

**Cons:**
- Slower than WASM
- Limited access to system resources
- No static typing

### WASM Plugins

**Best for:**
- Performance-critical operations
- Complex business logic
- Integration with existing Rust/C/C++ code
- Plugins requiring strong typing

**Pros:**
- Near-native performance
- Strongly typed (if written in Rust)
- Sandboxed execution
- Access to rich Rust ecosystem

**Cons:**
- Requires compilation step
- Larger binary size
- More complex development workflow

---

## Plugin Lifecycle

1. **Load**: Plugin file is loaded and parsed
2. **Validate**: Metadata is extracted and validated
3. **Initialize**: `init()` function is called with context
4. **Execute**: Hooks are called as events occur
5. **Unload**: Plugin is cleaned up (automatic)

---

## Hook Patterns

### Issue Lifecycle Hooks

```lua
function on_issue_created(issue)
    -- Validate issue data
    if not issue.title or issue.title == "" then
        return { success = false, error = "Title required" }
    end
    
    -- Perform action (e.g., notify team)
    notify_slack("New issue: " .. issue.title)
    
    -- Return success with optional metadata
    return {
        success = true,
        notified = true,
        timestamp = os.time()
    }
end
```

### Sync Hooks

```lua
function on_sync_push(issues)
    local synced = 0
    local failed = 0
    
    for i, issue in ipairs(issues) do
        local result = sync_to_external_system(issue)
        if result.success then
            synced = synced + 1
        else
            failed = failed + 1
            log_error("Failed to sync issue " .. issue.id .. ": " .. result.error)
        end
    end
    
    return {
        success = failed == 0,
        synced = synced,
        failed = failed
    }
end
```

---

## Configuration

Plugins receive configuration via `context.config`:

```lua
function init()
    -- Load from context.config
    local api_key = context.config.api_key
    
    -- Fallback to environment variables
    if not api_key then
        api_key = os.getenv("MY_PLUGIN_API_KEY")
    end
    
    -- Validate configuration
    if not api_key then
        error("API key not configured. Set MY_PLUGIN_API_KEY or add to config")
    end
    
    -- Store for later use
    _G.api_key = api_key
end
```

User configuration in `.project/config.kdl`:

```kdl
plugins {
    my-plugin {
        api_key "secret-key-here"
        endpoint "https://api.example.com"
        enabled true
    }
}
```

---

## Error Handling

### Lua

```lua
function on_issue_created(issue)
    -- Validate inputs
    if not issue or not issue.id then
        return { success = false, error = "Invalid issue data" }
    end
    
    -- Try operation with error handling
    local success, result = pcall(function()
        return call_external_api(issue)
    end)
    
    if not success then
        log_error("API call failed: " .. tostring(result))
        return { success = false, error = "External API error" }
    end
    
    return { success = true, result = result }
end
```

### WASM (Rust)

```rust
#[no_mangle]
pub extern "C" fn on_issue_created(data_ptr: i32, data_len: i32) -> i32 {
    match process_issue(data_ptr, data_len) {
        Ok(result) => serialize_result(&result),
        Err(e) => {
            log_error(&format!("Error: {}", e));
            serialize_error(&e)
        }
    }
}
```

---

## Testing Plugins

### Lua Testing

Create a test harness:

```lua
-- test_my_plugin.lua
local plugin = require("my_plugin")

local test_issue = {
    id = "test-123",
    title = "Test Issue",
    status = "backlog",
    tags = {},
    created = "2025-12-11T00:00:00Z",
    updated = "2025-12-11T00:00:00Z",
    metadata = {}
}

local result = plugin.on_issue_created(test_issue)
assert(result.success, "Plugin should succeed")
print("✅ Test passed")
```

### WASM Testing

Use Rust's built-in test framework:

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

    #[test]
    fn test_issue_processing() {
        let issue = Issue {
            id: "test-123".to_string(),
            title: "Test".to_string(),
            // ...
        };
        
        let result = process_issue(&issue).unwrap();
        assert!(result.success);
    }
}
```

---

## Performance Tips

### Lua

1. **Cache expensive operations**:
   ```lua
   local cached_data = nil
   
   function get_data()
       if not cached_data then
           cached_data = expensive_operation()
       end
       return cached_data
   end
   ```

2. **Avoid table creation in loops**:
   ```lua
   -- Bad
   for i, issue in ipairs(issues) do
       local result = { success = true, id = issue.id }
   end
   
   -- Good
   local result = { success = true }
   for i, issue in ipairs(issues) do
       result.id = issue.id
       process(result)
   end
   ```

3. **Use local variables**:
   ```lua
   -- Bad
   function process()
       global_var = expensive_calc()
   end
   
   -- Good
   function process()
       local result = expensive_calc()
       return result
   end
   ```

### WASM

1. **Minimize allocations**: Reuse buffers where possible
2. **Use `&str` instead of `String`** when you don't need ownership
3. **Batch operations**: Process multiple issues in one call
4. **Profile**: Use `cargo flamegraph` to find bottlenecks

---

## Security Considerations

### Sandboxing

Both Lua and WASM plugins run in sandboxed environments:

- **No direct file system access** (except via SDK APIs)
- **No network access** (except via SDK APIs)
- **No arbitrary code execution**
- **Limited memory**

### Input Validation

Always validate inputs from ProGit:

```lua
function on_issue_created(issue)
    -- Validate required fields
    assert(type(issue) == "table", "Issue must be a table")
    assert(type(issue.id) == "string", "Issue ID must be a string")
    assert(#issue.id > 0, "Issue ID cannot be empty")
    
    -- Sanitize user input before external API calls
    local safe_title = sanitize(issue.title)
    
    -- Proceed with validated data
    return call_api(safe_title)
end
```

### Secrets Management

**Never hardcode secrets**:

```lua
-- ❌ BAD
local api_key = "sk-1234567890abcdef"

-- ✅ GOOD
local api_key = os.getenv("API_KEY") or context.config.api_key
if not api_key then
    error("API key not configured")
end
```

---

## Distribution

### Lua Plugins

Distribute as single `.lua` files:

```bash
# Install
cp my_plugin.lua ~/.progit/plugins/

# Or via git
git clone https://github.com/user/progit-plugin-xyz ~/.progit/plugins/xyz
```

### WASM Plugins

Distribute as `.wasm` binaries:

```bash
# Build
cargo build --target wasm32-wasi --release

# Package
tar czf my-plugin-v1.0.0.tar.gz \
    target/wasm32-wasi/release/my_plugin.wasm \
    README.md \
    LICENSE

# Install
tar xzf my-plugin-v1.0.0.tar.gz -C ~/.progit/plugins/
```

---

## Example: Complete Slack Notification Plugin

```lua
-- SPDX-License-Identifier: Apache-2.0
-- slack_notify.lua

plugin = {
    name = "slack-notify",
    version = "1.0.0",
    author = "Your Name",
    description = "Send Slack notifications for issue events",
    hooks = {
        on_issue_created = true,
        on_status_changed = true,
    }
}

local webhook_url = nil

function init()
    webhook_url = context.config.webhook_url or os.getenv("SLACK_WEBHOOK_URL")
    if not webhook_url then
        error("Slack webhook URL not configured")
    end
    print("Slack notifications enabled")
end

function on_issue_created(issue)
    local message = string.format(
        "🎉 New issue created: *%s*\nStatus: %s\nAssignee: %s",
        issue.title,
        issue.status,
        issue.assignee or "Unassigned"
    )
    
    return send_slack_message(message)
end

function on_status_changed(issue)
    local emoji = issue.status == "done" and "✅" or "🔄"
    local message = string.format(
        "%s Issue status changed: *%s*\nNew status: %s",
        emoji,
        issue.title,
        issue.status
    )
    
    return send_slack_message(message)
end

function send_slack_message(text)
    -- In real implementation, use HTTP library
    -- For demo, just log
    print("Would send to Slack: " .. text)
    return { success = true }
end
```

---

## Next Steps

- See [examples/]../examples/ for more plugin examples
- Read [API Reference]api_reference.md for complete SDK documentation
- Join the community to share your plugins!