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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
// SPDX-License-Identifier: LSL-1.0
// Copyright (c) 2025 Markus Maiwald

//! Sandboxed LuaJIT plugin runtime.
//!
//! [SEC] Doctrine 4 ("Plugins are sandboxed") is enforced here, not just
//! aspirationally. The VM is constructed with a filtered stdlib, dangerous
//! `os`/`package` entries are neutralised, memory and instruction caps
//! are wired in. Plugins that try `os.execute`, `io.popen`, `package.loadlib`
//! or `debug.*` get a hard error rather than a foothold to read your SSH keys.
//!
//! [HAZMAT] If you change `setup_safe_stdlib`, audit every callable returned
//! to Lua. A single dangling `os.exit` or `io.open` defeats the sandbox for
//! the entire VM.

use crate::event::PluginEvent;
use crate::manifest::Capabilities;
use crate::render::{HighlightRequest, HighlightResponse};
use crate::storage::{JsonFileStorage, PluginStorage};
use crate::traits::*;
use anyhow::Result;
use mlua::{HookTriggers, Lua, LuaOptions, LuaSerdeExt, StdLib, Table, Value};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Request passed from Lua `sober.run(action, opts)` to the host.
#[derive(Debug, Clone)]
pub struct SoberInvocation {
    /// Allowlisted Sober action, e.g. `doctor` or `review-preview`.
    pub action: String,
    /// Free-form JSON options interpreted by the host.
    pub options: serde_json::Value,
}

/// Result returned by the host-backed Sober capability.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SoberInvocationResult {
    pub ok: bool,
    #[serde(default)]
    pub data: serde_json::Value,
    #[serde(default)]
    pub error: Option<String>,
}

/// Host-provided Sober capability handle.
#[derive(Clone)]
pub struct SoberHost {
    runner: Arc<dyn Fn(SoberInvocation) -> SoberInvocationResult + Send + Sync>,
}

impl std::fmt::Debug for SoberHost {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SoberHost").finish_non_exhaustive()
    }
}

impl SoberHost {
    /// Create a Sober capability from a host callback.
    pub fn new<F>(runner: F) -> Self
    where
        F: Fn(SoberInvocation) -> SoberInvocationResult + Send + Sync + 'static,
    {
        Self {
            runner: Arc::new(runner),
        }
    }

    /// Run a Sober invocation through the host callback.
    pub fn run(&self, invocation: SoberInvocation) -> SoberInvocationResult {
        (self.runner)(invocation)
    }
}

/// Tunable knobs for a `LuaPlugin` VM.
///
/// Defaults are conservative and align with `Capabilities::legacy_default()`:
/// 64 MB memory, 10 M instructions per hook call, 5 s HTTP timeout.
///
/// [HAZMAT] The instruction cap is *best-effort under LuaJIT*. LuaJIT's
/// tracing JIT can compile a tight integer loop into native code that
/// bypasses debug hooks; the cap will not trip on that specific
/// pathology until the loop calls a function or touches a table /
/// string. In practice every real plugin does. The memory cap and HTTP
/// timeout are not affected by JIT and remain hard limits.
#[derive(Debug, Clone)]
pub struct LuaPluginOptions {
    /// Heap memory ceiling in megabytes. Counted by the Lua GC.
    pub memory_mb: u32,
    /// Hard cap on Lua instructions per single hook call.
    /// Set to `0` to disable (not recommended).
    pub max_instructions: u64,
    /// Per-request HTTP timeout.
    pub http_timeout: Duration,
    /// If set, restrict outbound HTTP to these hosts (suffix match).
    pub network_allow: Vec<String>,
    /// Master switch for outbound HTTP.
    pub network: bool,
    /// Allow `os.getenv`. Disable in hardened deployments.
    pub env_access: bool,
    /// Host-provided Sober bridge. Only set when the manifest grants it.
    pub sober: Option<SoberHost>,
    /// Repository root; used to scope the plugin's `storage` table.
    pub repo_root: Option<PathBuf>,
}

impl Default for LuaPluginOptions {
    fn default() -> Self {
        Self::from_capabilities(&Capabilities::legacy_default())
    }
}

impl LuaPluginOptions {
    /// Derive runtime options from a manifest capability block.
    pub fn from_capabilities(caps: &Capabilities) -> Self {
        Self {
            memory_mb: caps.memory_mb,
            max_instructions: caps.max_instructions,
            http_timeout: Duration::from_secs(caps.http_timeout_secs),
            network_allow: caps.network_allow.clone(),
            network: caps.network,
            env_access: caps.env,
            sober: None,
            repo_root: None,
        }
    }
}

/// Shared HTTP capability handle — single client + allowlist.
struct HttpCap {
    client: reqwest::blocking::Client,
    network: bool,
    allow: Vec<String>,
}

impl HttpCap {
    fn new(opts: &LuaPluginOptions) -> mlua::Result<Self> {
        let client = reqwest::blocking::Client::builder()
            .timeout(opts.http_timeout)
            .user_agent(concat!("progit-plugin-sdk/", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(|e| mlua::Error::RuntimeError(format!("http client init: {e}")))?;
        Ok(Self {
            client,
            network: opts.network,
            allow: opts.network_allow.clone(),
        })
    }

    fn check(&self, url: &str) -> mlua::Result<()> {
        if !self.network {
            return Err(mlua::Error::RuntimeError(
                "http: capability 'network' not granted in plugin manifest".into(),
            ));
        }
        if self.allow.is_empty() {
            return Ok(());
        }
        let host = match reqwest::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string)) {
            Some(h) => h.to_lowercase(),
            None => {
                return Err(mlua::Error::RuntimeError(format!("http: invalid URL '{url}'")));
            }
        };
        let ok = self.allow.iter().any(|a| {
            let al = a.to_lowercase();
            host == al || host.ends_with(&format!(".{al}"))
        });
        if ok {
            Ok(())
        } else {
            Err(mlua::Error::RuntimeError(format!(
                "http: host '{host}' not in network_allow list"
            )))
        }
    }
}

/// A sandboxed LuaJIT plugin instance.
pub struct LuaPlugin {
    lua: Lua,
    metadata: PluginMetadata,
    context: Option<PluginContext>,
    options: LuaPluginOptions,
    /// Wired up at `init()` once we know the repo root + plugin name.
    storage: Arc<Mutex<Option<JsonFileStorage>>>,
}

impl LuaPlugin {
    /// Load with default options (legacy-permissive caps, network OFF).
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::load_with_options(path, LuaPluginOptions::default())
    }

    /// Load from a script string with default options.
    pub fn from_string(script: &str, name: &str) -> Result<Self> {
        Self::from_string_with_options(script, name, LuaPluginOptions::default())
    }

    /// Load with explicit options. Use when constructing from a manifest's
    /// declared capabilities (the recommended path for production hosts).
    pub fn load_with_options<P: AsRef<Path>>(path: P, options: LuaPluginOptions) -> Result<Self> {
        let script = std::fs::read_to_string(path.as_ref())?;
        Self::from_string_with_options(&script, "<file>", options)
    }

    /// Load from a script string with explicit options.
    pub fn from_string_with_options(
        script: &str,
        _name: &str,
        options: LuaPluginOptions,
    ) -> Result<Self> {
        // === Build a sandboxed VM ============================================
        // Skip IO (file open, popen), DEBUG (introspection), and FFI (raw C
        // memory access — defeats the entire sandbox in one line). Keep
        // TABLE/STRING/MATH for ergonomics; OS for time/date (dangerous bits
        // get neutralised below); PACKAGE for require of injected modules
        // (loadlib neutralised); BIT and JIT because they are LuaJIT-essential
        // and benign. Coroutines come with the base library on Lua 5.1/LuaJIT
        // — there is no separate `StdLib::COROUTINE` flag.
        let libs = StdLib::TABLE
            | StdLib::STRING
            | StdLib::MATH
            | StdLib::OS
            | StdLib::PACKAGE
            | StdLib::BIT
            | StdLib::JIT;
        
        // Create Lua VM with panic isolation (mlua can panic on some errors)
        let lua_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            Lua::new_with(libs, LuaOptions::default())
        }));
        
        let lua = match lua_result {
            Ok(Ok(lua)) => lua,
            Ok(Err(e)) => return Err(anyhow::anyhow!("Failed to construct sandboxed Lua VM: {}", e)),
            Err(panic_info) => {
                let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
                    s.to_string()
                } else if let Some(s) = panic_info.downcast_ref::<String>() {
                    s.clone()
                } else {
                    "Unknown panic".to_string()
                };
                return Err(anyhow::anyhow!("Lua VM construction panicked: {}", msg));
            }
        };

        // Memory cap. Note: `set_memory_limit` is best-effort — large native
        // userdata can still allocate outside this budget.
        if options.memory_mb > 0 {
            let bytes = (options.memory_mb as usize).saturating_mul(1024 * 1024);
            let _ = lua.set_memory_limit(bytes);
        }

        let storage = Arc::new(Mutex::new(None));

        // Set up stdlib with panic isolation
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            setup_safe_stdlib(&lua, &options, storage.clone())
        })).map_err(|e| {
            let msg = if let Some(s) = e.downcast_ref::<&str>() {
                s.to_string()
            } else if let Some(s) = e.downcast_ref::<String>() {
                s.clone()
            } else {
                "Unknown panic".to_string()
            };
            anyhow::anyhow!("Failed to set up sandboxed stdlib (panicked): {}", msg)
        })?.map_err(|e| anyhow::anyhow!("Failed to set up sandboxed stdlib: {}", e))?;

        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            neutralise_dangerous(&lua, &options)
        })).map_err(|e| {
            let msg = if let Some(s) = e.downcast_ref::<&str>() {
                s.to_string()
            } else if let Some(s) = e.downcast_ref::<String>() {
                s.clone()
            } else {
                "Unknown panic".to_string()
            };
            anyhow::anyhow!("Failed to neutralise dangerous globals (panicked): {}", msg)
        })?.map_err(|e| anyhow::anyhow!("Failed to neutralise dangerous globals: {}", e))?;

        lua.load(script)
            .exec()
            .map_err(|e| anyhow::anyhow!("Plugin script error: {e}"))?;

        let metadata = Self::extract_metadata(&lua)?;

        if options.max_instructions > 0 {
            install_instruction_hook(&lua, options.max_instructions)?;
        }

        Ok(Self {
            lua,
            metadata,
            context: None,
            options,
            storage,
        })
    }

    fn extract_metadata(lua: &Lua) -> Result<PluginMetadata> {
        let globals = lua.globals();
        let plugin_table: Table = globals
            .get("plugin")
            .map_err(|e| anyhow::anyhow!("Plugin must define a 'plugin' table: {e}"))?;

        let name: String = plugin_table
            .get("name")
            .map_err(|e| anyhow::anyhow!("Plugin metadata missing 'name': {e}"))?;
        let version: String = plugin_table
            .get("version")
            .map_err(|e| anyhow::anyhow!("Plugin metadata missing 'version': {e}"))?;
        let author: String = plugin_table
            .get("author")
            .map_err(|e| anyhow::anyhow!("Plugin metadata missing 'author': {e}"))?;
        let description: String = plugin_table.get("description").unwrap_or_default();

        let hooks_table: Table = plugin_table
            .get("hooks")
            .map_err(|e| anyhow::anyhow!("Plugin metadata missing 'hooks' table: {e}"))?;
        let mut hooks = Vec::new();
        for pair in hooks_table.pairs::<String, bool>() {
            let (hook_name, enabled) = pair
                .map_err(|e| anyhow::anyhow!("Failed to iterate hooks: {e}"))?;
            if !enabled {
                continue;
            }
            if let Some(h) = hook_name_to_enum(&hook_name) {
                hooks.push(h);
            }
        }

        Ok(PluginMetadata {
            name,
            version,
            author,
            description,
            hooks,
        })
    }

    fn call_lua_hook(
        &self,
        hook_name: &str,
        data: &serde_json::Value,
    ) -> Result<serde_json::Value> {
        let globals = self.lua.globals();
        let lua_data = self.json_to_lua(data)?;
        let hook_fn: mlua::Function = globals
            .get(hook_name)
            .map_err(|e| anyhow::anyhow!("Hook function '{hook_name}' not found: {e}"))?;
        let result: Value = hook_fn
            .call(lua_data)
            .map_err(|e| anyhow::anyhow!("Lua hook '{hook_name}' raised: {e}"))?;
        self.lua_to_json(&result)
    }

    fn json_to_lua(&self, value: &serde_json::Value) -> Result<Value> {
        Ok(self
            .lua
            .to_value(value)
            .map_err(|e| anyhow::anyhow!("Failed to convert JSON to Lua: {e}"))?)
    }

    fn lua_to_json(&self, value: &Value) -> Result<serde_json::Value> {
        Ok(self
            .lua
            .from_value(value.clone())
            .map_err(|e| anyhow::anyhow!("Failed to convert Lua to JSON: {e}"))?)
    }

    /// Call `plugin.on_event(event)` if the plugin defines it.
    pub fn call_event(&self, event: &serde_json::Value) -> Result<Option<serde_json::Value>> {
        let globals = self.lua.globals();
        let plugin_table: Table = match globals.get("plugin") {
            Ok(t) => t,
            Err(_) => return Ok(None),
        };
        let on_event_fn: mlua::Function = match plugin_table.get("on_event") {
            Ok(f) => f,
            Err(_) => return Ok(None),
        };
        let lua_event = self.json_to_lua(event)?;
        let result: Value = on_event_fn
            .call(lua_event)
            .map_err(|e| anyhow::anyhow!("plugin.on_event failed: {e}"))?;
        match result {
            Value::Nil => Ok(None),
            _ => Ok(Some(self.lua_to_json(&result)?)),
        }
    }

    /// Strongly-typed convenience for the `Custom` event variant.
    pub fn call_typed_event(&self, event: &PluginEvent) -> Result<Option<serde_json::Value>> {
        let v = serde_json::to_value(event)?;
        self.call_event(&v)
    }

    /// Call `plugin.highlight(req)` if defined. Returns `Ok(None)` when
    /// the plugin is not a highlight provider, when it explicitly
    /// returned `nil`, or when its decoded response was empty.
    fn call_highlight(
        &self,
        request: &HighlightRequest,
    ) -> Result<Option<HighlightResponse>> {
        let globals = self.lua.globals();
        let plugin_table: Table = match globals.get("plugin") {
            Ok(t) => t,
            Err(_) => return Ok(None),
        };
        let highlight_fn: mlua::Function = match plugin_table.get("highlight") {
            Ok(f) => f,
            Err(_) => return Ok(None),
        };
        let req_json = serde_json::to_value(request)?;
        let req_lua = self.json_to_lua(&req_json)?;
        let result: Value = highlight_fn
            .call(req_lua)
            .map_err(|e| anyhow::anyhow!("plugin.highlight failed: {e}"))?;
        if let Value::Nil = result {
            return Ok(None);
        }
        let resp_json = self.lua_to_json(&result)?;
        let resp: HighlightResponse = serde_json::from_value(resp_json)
            .map_err(|e| anyhow::anyhow!("highlight response decode: {e}"))?;
        if resp.spans.is_empty() {
            Ok(None)
        } else {
            Ok(Some(resp))
        }
    }
}

impl Plugin for LuaPlugin {
    fn metadata(&self) -> &PluginMetadata {
        &self.metadata
    }

    fn init(&mut self, context: &PluginContext) -> PluginResult<()> {
        let globals = self.lua.globals();

        let repo_root = self
            .options
            .repo_root
            .clone()
            .unwrap_or_else(|| PathBuf::from(&context.repo_path));
        let scoped = JsonFileStorage::new(&repo_root, &self.metadata.name);
        if let Ok(mut slot) = self.storage.lock() {
            *slot = Some(scoped);
        }

        // Set context with panic isolation
        let context_clone = context.clone();
        // Run init in panic-safe wrapper
        let init_result: Result<Result<(), PluginError>, String> = 
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let context_json = serde_json::to_value(&context_clone)
                    .map_err(|e| PluginError::InitError(e.to_string()))?;
                let context_lua = self
                    .json_to_lua(&context_json)
                    .map_err(|e| PluginError::InitError(e.to_string()))?;
                globals
                    .set("context", context_lua)
                    .map_err(|e| PluginError::InitError(e.to_string()))?;

                self.context = Some(context_clone.clone());

                if let Ok(init_fn) = globals.get::<mlua::Function>("init") {
                    init_fn
                        .call::<()>(())
                        .map_err(|e| PluginError::InitError(e.to_string()))?;
                }
                Ok(())
            })).map_err(|panic_payload| {
                if let Some(s) = panic_payload.downcast_ref::<&str>() {
                    s.to_string()
                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                    s.clone()
                } else {
                    "Unknown panic in init".to_string()
                }
            });

        match init_result {
            Ok(Ok(())) => Ok(()),
            Ok(Err(e)) => Err(e),
            Err(msg) => Err(PluginError::InitError(format!("Plugin init panicked: {}", msg))),
        }
    }

    fn execute_hook(
        &mut self,
        hook: &PluginHook,
        data: &serde_json::Value,
    ) -> PluginResult<serde_json::Value> {
        if !self.supports_hook(hook) {
            return Err(PluginError::UnsupportedHook(hook.clone()));
        }
        let result = match hook {
            PluginHook::OnSchedule(name) => {
                self.call_lua_hook(&format!("on_schedule_{name}"), data)
            }
            PluginHook::OnSprintStart(n) => self.call_lua_hook(
                "on_sprint_start",
                &serde_json::json!({ "sprint": n, "data": data }),
            ),
            PluginHook::OnSprintEnd(n) => self.call_lua_hook(
                "on_sprint_end",
                &serde_json::json!({ "sprint": n, "data": data }),
            ),
            PluginHook::OnCommand(_cmd) => self.call_lua_hook("on_command", data),
            PluginHook::OnBulkOperation(op) => {
                let name = match op {
                    BulkOp::Import => "on_bulk_import",
                    BulkOp::Export => "on_bulk_export",
                    BulkOp::Archive => "on_bulk_archive",
                    BulkOp::Delete => "on_bulk_delete",
                };
                self.call_lua_hook(name, data)
            }
            other => {
                let name = hook_enum_to_name(other).ok_or_else(|| {
                    PluginError::ExecutionError(format!("no Lua name for hook {other:?}"))
                })?;
                self.call_lua_hook(name, data)
            }
        };
        result.map_err(|e| PluginError::ExecutionError(e.to_string()))
    }

    fn on_event(&mut self, event: &serde_json::Value) -> PluginResult<Option<serde_json::Value>> {
        self.call_event(event)
            .map_err(|e| PluginError::ExecutionError(e.to_string()))
    }

    fn highlight(
        &mut self,
        request: &HighlightRequest,
    ) -> PluginResult<Option<HighlightResponse>> {
        self.call_highlight(request)
            .map_err(|e| PluginError::ExecutionError(e.to_string()))
    }
}

impl IssuePlugin for LuaPlugin {}
impl SyncPlugin for LuaPlugin {}

// ─── Hook name <-> enum bridge ────────────────────────────────────────────

fn hook_name_to_enum(name: &str) -> Option<PluginHook> {
    Some(match name {
        "on_issue_created" => PluginHook::OnIssueCreated,
        "on_issue_updated" => PluginHook::OnIssueUpdated,
        "on_issue_deleted" => PluginHook::OnIssueDeleted,
        "on_status_changed" => PluginHook::OnStatusChanged,
        "on_sync_push" => PluginHook::OnSyncPush,
        "on_sync_pull" => PluginHook::OnSyncPull,
        "on_merge_request_created" => PluginHook::OnMergeRequestCreated,
        "on_external_sync" => PluginHook::OnExternalSync,
        "on_webhook_received" => PluginHook::OnWebhookReceived,
        "on_due_date_approaching" => PluginHook::OnDueDateApproaching,
        "on_due_date_passed" => PluginHook::OnDueDatePassed,
        "on_report_requested" => PluginHook::OnReportRequested,
        "on_metric_query" => PluginHook::OnMetricQuery,
        "on_command" => PluginHook::OnCommand(String::new()), // Command name set at runtime
        _ => return None,
    })
}

fn hook_enum_to_name(hook: &PluginHook) -> Option<&'static str> {
    Some(match hook {
        PluginHook::OnIssueCreated => "on_issue_created",
        PluginHook::OnIssueUpdated => "on_issue_updated",
        PluginHook::OnIssueDeleted => "on_issue_deleted",
        PluginHook::OnStatusChanged => "on_status_changed",
        PluginHook::OnSyncPush => "on_sync_push",
        PluginHook::OnSyncPull => "on_sync_pull",
        PluginHook::OnMergeRequestCreated => "on_merge_request_created",
        PluginHook::OnExternalSync => "on_external_sync",
        PluginHook::OnWebhookReceived => "on_webhook_received",
        PluginHook::OnDueDateApproaching => "on_due_date_approaching",
        PluginHook::OnDueDatePassed => "on_due_date_passed",
        PluginHook::OnReportRequested => "on_report_requested",
        PluginHook::OnMetricQuery => "on_metric_query",
        PluginHook::OnCommand(_) => "on_command", // Commands use dynamic names
        _ => return None,
    })
}

// ─── Sandbox plumbing ─────────────────────────────────────────────────────

/// Install an instruction-count hook that aborts a hook call once the
/// budget is exceeded. Triggers fire every 4 K instructions so the
/// per-instruction overhead stays negligible.
fn install_instruction_hook(lua: &Lua, max: u64) -> Result<()> {
    use std::sync::atomic::{AtomicU64, Ordering};
    let counter = Arc::new(AtomicU64::new(0));
    let triggers = HookTriggers::new().every_nth_instruction(4096);
    let counter_cl = counter.clone();
    lua.set_hook(triggers, move |_, _debug| {
        let n = counter_cl.fetch_add(4096, Ordering::Relaxed);
        if n >= max {
            return Err(mlua::Error::RuntimeError(format!(
                "plugin exceeded instruction budget ({max})"
            )));
        }
        Ok(mlua::VmState::Continue)
    })
    .map_err(|e| anyhow::anyhow!("Failed to install Lua instruction hook: {e}"))?;
    Ok(())
}

/// Build the safe stdlib: `http`, `json`, `log`, `storage`.
fn setup_safe_stdlib(
    lua: &Lua,
    opts: &LuaPluginOptions,
    storage: Arc<Mutex<Option<JsonFileStorage>>>,
) -> mlua::Result<()> {
    let globals = lua.globals();

    // ── http ─────────────────────────────────────────────────────────────
    let http_cap = Arc::new(HttpCap::new(opts)?);
    let http = lua.create_table()?;

    let cap = http_cap.clone();
    let http_get = lua.create_function(move |lua, (url, headers): (String, Option<Table>)| {
        cap.check(&url)?;
        let mut req = cap.client.get(&url);
        if let Some(h) = headers {
            for pair in h.pairs::<String, String>() {
                let (k, v) = pair?;
                req = req.header(k, v);
            }
        }
        send_and_wrap(lua, req)
    })?;

    let cap = http_cap.clone();
    let http_post = lua.create_function(
        move |lua, (url, body, headers): (String, String, Option<Table>)| {
            cap.check(&url)?;
            let mut req = cap.client.post(&url).body(body);
            if let Some(h) = headers {
                for pair in h.pairs::<String, String>() {
                    let (k, v) = pair?;
                    req = req.header(k, v);
                }
            }
            send_and_wrap(lua, req)
        },
    )?;

    let cap = http_cap.clone();
    let http_put = lua.create_function(
        move |lua, (url, body, headers): (String, String, Option<Table>)| {
            cap.check(&url)?;
            let mut req = cap.client.put(&url).body(body);
            if let Some(h) = headers {
                for pair in h.pairs::<String, String>() {
                    let (k, v) = pair?;
                    req = req.header(k, v);
                }
            }
            send_and_wrap(lua, req)
        },
    )?;

    let cap = http_cap.clone();
    let http_delete =
        lua.create_function(move |lua, (url, headers): (String, Option<Table>)| {
            cap.check(&url)?;
            let mut req = cap.client.delete(&url);
            if let Some(h) = headers {
                for pair in h.pairs::<String, String>() {
                    let (k, v) = pair?;
                    req = req.header(k, v);
                }
            }
            send_and_wrap(lua, req)
        })?;

    http.set("get", http_get)?;
    http.set("post", http_post)?;
    http.set("put", http_put)?;
    http.set("delete", http_delete)?;
    globals.set("http", http)?;

    // ── json ─────────────────────────────────────────────────────────────
    let json = lua.create_table()?;
    let json_encode = lua.create_function(|lua, value: Value| {
        let json_val: serde_json::Value = lua
            .from_value(value)
            .map_err(|e| mlua::Error::RuntimeError(format!("json.encode: {e}")))?;
        serde_json::to_string(&json_val)
            .map_err(|e| mlua::Error::RuntimeError(format!("json.encode: {e}")))
    })?;
    let json_decode = lua.create_function(|lua, s: String| {
        let json_val: serde_json::Value = serde_json::from_str(&s)
            .map_err(|e| mlua::Error::RuntimeError(format!("json.decode: {e}")))?;
        lua.to_value(&json_val)
            .map_err(|e| mlua::Error::RuntimeError(format!("json.decode: {e}")))
    })?;
    json.set("encode", json_encode)?;
    json.set("decode", json_decode)?;
    globals.set("json", json)?;

    // ── log ──────────────────────────────────────────────────────────────
    let log = lua.create_table()?;
    let log_debug = lua.create_function(|_, msg: String| {
        log::debug!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    let log_info = lua.create_function(|_, msg: String| {
        log::info!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    let log_warn = lua.create_function(|_, msg: String| {
        log::warn!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    let log_error = lua.create_function(|_, msg: String| {
        log::error!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    log.set("debug", log_debug)?;
    log.set("info", log_info)?;
    log.set("warn", log_warn)?;
    log.set("error", log_error)?;
    globals.set("log", log)?;

    // Back-compat shims: v0.1 plugins called `log_info("...")` etc. as globals.
    let log_info_global = lua.create_function(|_, msg: String| {
        log::info!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    let log_warn_global = lua.create_function(|_, msg: String| {
        log::warn!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    let log_error_global = lua.create_function(|_, msg: String| {
        log::error!(target: "progit_plugin", "{msg}");
        Ok(())
    })?;
    globals.set("log_info", log_info_global)?;
    globals.set("log_warn", log_warn_global)?;
    globals.set("log_error", log_error_global)?;

    // ── sober (host capability) ─────────────────────────────────────────
    let sober_tbl = lua.create_table()?;
    if let Some(host) = opts.sober.clone() {
        let sober_run = lua.create_function(
            move |lua, (action, options): (String, Option<Value>)| {
                let options_json = match options {
                    Some(value) => lua.from_value(value).map_err(|e| {
                        mlua::Error::RuntimeError(format!("sober.run: options: {e}"))
                    })?,
                    None => serde_json::Value::Object(Default::default()),
                };
                let result = host.run(SoberInvocation {
                    action,
                    options: options_json,
                });
                lua.to_value(&result)
                    .map_err(|e| mlua::Error::RuntimeError(format!("sober.run: result: {e}")))
            },
        )?;
        sober_tbl.set("run", sober_run)?;
    } else {
        let sober_run = lua.create_function(|_, (_action, _options): (String, Option<Value>)| {
            Err::<Value, _>(mlua::Error::RuntimeError(
                "sober.run requires the manifest capability `sober = true` and a host bridge"
                    .into(),
            ))
        })?;
        sober_tbl.set("run", sober_run)?;
    }
    globals.set("sober", sober_tbl)?;

    // ── storage ──────────────────────────────────────────────────────────
    let storage_tbl = lua.create_table()?;

    let s = storage.clone();
    let storage_get = lua.create_function(move |lua, key: String| {
        let guard = s
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("storage poisoned".into()))?;
        let val = match guard.as_ref() {
            Some(st) => st
                .get(&key)
                .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?,
            None => return Ok(Value::Nil),
        };
        match val {
            Some(v) => lua
                .to_value(&v)
                .map_err(|e| mlua::Error::RuntimeError(e.to_string())),
            None => Ok(Value::Nil),
        }
    })?;

    let s = storage.clone();
    let storage_set = lua.create_function(move |lua, (key, value): (String, Value)| {
        let json_val: serde_json::Value = lua
            .from_value(value)
            .map_err(|e| mlua::Error::RuntimeError(format!("storage.set: {e}")))?;
        let mut guard = s
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("storage poisoned".into()))?;
        match guard.as_mut() {
            Some(st) => st
                .set(&key, &json_val)
                .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?,
            None => return Err(mlua::Error::RuntimeError("storage not initialised".into())),
        }
        Ok(())
    })?;

    let s = storage.clone();
    let storage_delete = lua.create_function(move |_, key: String| {
        let mut guard = s
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("storage poisoned".into()))?;
        let removed = match guard.as_mut() {
            Some(st) => st
                .delete(&key)
                .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?,
            None => false,
        };
        Ok(removed)
    })?;

    let s = storage.clone();
    let storage_keys = lua.create_function(move |lua, ()| {
        let guard = s
            .lock()
            .map_err(|_| mlua::Error::RuntimeError("storage poisoned".into()))?;
        let keys: Vec<String> = match guard.as_ref() {
            Some(st) => st
                .keys()
                .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?,
            None => Vec::new(),
        };
        let t = lua.create_table()?;
        for (i, k) in keys.into_iter().enumerate() {
            t.set(i + 1, k)?;
        }
        Ok(t)
    })?;

    let storage_clear = {
        let s = storage.clone();
        lua.create_function(move |_, ()| {
            let mut guard = s
                .lock()
                .map_err(|_| mlua::Error::RuntimeError("storage poisoned".into()))?;
            if let Some(st) = guard.as_mut() {
                st.clear()
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
            }
            Ok(())
        })?
    };

    storage_tbl.set("get", storage_get)?;
    storage_tbl.set("set", storage_set)?;
    storage_tbl.set("delete", storage_delete)?;
    storage_tbl.set("keys", storage_keys)?;
    storage_tbl.set("clear", storage_clear)?;
    globals.set("storage", storage_tbl)?;

    // Mount under package.loaded so `require()` resolves.
    let package: Table = globals.get("package")?;
    let loaded: Table = package.get("loaded")?;
    for name in ["http", "json", "log", "sober", "storage"] {
        let v: Value = globals.get(name)?;
        loaded.set(name, v)?;
    }

    // ── io (safe shim) ──────────────────────────────────────────────────
    let repo_root = opts.repo_root.clone();
    let io = lua.create_table()?;
    
    let repo_for_open = repo_root.clone();
    let io_open = lua.create_function(move |lua, (path, mode): (String, Option<String>)| {
        let repo_str = repo_for_open.as_ref()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| ".".to_string());
        
        let m = mode.unwrap_or_else(|| "r".to_string());
        // Allow read ('r') and append ('a') modes only
        // Write mode ('w') is not allowed to prevent accidental overwrites
        if !m.starts_with('r') && !m.starts_with('a') {
            return Err(mlua::Error::RuntimeError(
                "io: only read ('r') and append ('a') modes are allowed".into()
            ));
        }
        
        let abs = if path.starts_with('/') { path.clone() }
                  else { format!("{}/{}", repo_str, path) };
        
        // Read file
        let content = match std::fs::read_to_string(&abs) {
            Ok(c) => c,
            Err(e) => return Err(mlua::Error::RuntimeError(format!("io: {}", e))),
        };
        
        // Create file table
        let file = lua.create_table()?;
        let c = content.clone();
        let read_fn = lua.create_function(move |_, fmt: String| {
            if fmt == "*a" { Ok(c.clone()) }
            else if fmt == "*l" { Ok(c.lines().next().unwrap_or_default().to_string()) }
            else { Ok(c.clone()) }
        })?;
        file.set("read", read_fn)?;
        let close_fn = lua.create_function(|_, ()| Ok(()))?;
        file.set("close", close_fn)?;
        let lines_vec: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        let lines_fn = lua.create_function(move |lua, ()| {
            let lines = lines_vec.clone();
            let idx = std::cell::RefCell::new(0usize);
            Ok(lua.create_function(move |_, ()| {
                *idx.borrow_mut() += 1;
                let i = *idx.borrow();
                if i <= lines.len() { Ok(Some(lines[i-1].clone())) }
                else { Ok(None) }
            }))
        })?;
        file.set("lines", lines_fn)?;
        Ok(file)
    })?;
    
    io.set("open", io_open.clone())?;
    globals.set("io", io)?;
    globals.set("io_open", io_open)?;

    Ok(())
}

fn send_and_wrap(lua: &Lua, req: reqwest::blocking::RequestBuilder) -> mlua::Result<Table> {
    let resp = req
        .send()
        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
    let status = resp.status().as_u16() as i64;
    let ok = resp.status().is_success();
    let body = resp
        .text()
        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
    let t = lua.create_table()?;
    t.set("status", status)?;
    t.set("body", body)?;
    t.set("ok", ok)?;
    Ok(t)
}

/// Strip the dangerous entries that `StdLib::OS` and `StdLib::PACKAGE`
/// expose by default.
fn neutralise_dangerous(lua: &Lua, opts: &LuaPluginOptions) -> mlua::Result<()> {
    let globals = lua.globals();

    if let Ok(os_tbl) = globals.get::<Table>("os") {
        for name in ["execute", "exit", "remove", "rename", "tmpname", "setlocale"] {
            let banned = name.to_string();
            let f = lua.create_function(move |_, ()| {
                Err::<(), _>(mlua::Error::RuntimeError(format!(
                    "os.{banned} is disabled in the ProGit plugin sandbox"
                )))
            })?;
            os_tbl.set(name, f)?;
        }
        if !opts.env_access {
            let f = lua.create_function(|_, _name: String| {
                Err::<Option<String>, _>(mlua::Error::RuntimeError(
                    "os.getenv is disabled (capability 'env' not granted)".into(),
                ))
            })?;
            os_tbl.set("getenv", f)?;
        }
    }

    if let Ok(pkg_tbl) = globals.get::<Table>("package") {
        for name in ["loadlib", "searchpath"] {
            let banned = name.to_string();
            let f = lua.create_function(move |_, ()| {
                Err::<(), _>(mlua::Error::RuntimeError(format!(
                    "package.{banned} is disabled in the sandbox"
                )))
            })?;
            pkg_tbl.set(name, f)?;
        }
    }

    // Note: io shim is now set up in setup_safe_stdlib

    Ok(())
}

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

    fn loose_opts() -> LuaPluginOptions {
        let mut opts = LuaPluginOptions::default();
        opts.network = false;
        opts.max_instructions = 0;
        opts
    }

    #[test]
    fn loads_minimal_plugin() {
        let script = r#"
            plugin = {
                name = "test", version = "1.0.0", author = "t",
                hooks = { on_issue_created = true }
            }
            function on_issue_created(issue)
                return { ok = true }
            end
        "#;
        let p = LuaPlugin::from_string_with_options(script, "test", loose_opts()).unwrap();
        assert_eq!(p.metadata().name, "test");
    }

    #[test]
    fn os_execute_is_blocked() {
        let script = r#"
            plugin = { name="x", version="1", author="y", hooks = {} }
            os.execute("ls")
        "#;
        let err = LuaPlugin::from_string_with_options(script, "x", loose_opts())
            .err()
            .expect("os.execute should be blocked");
        let msg = format!("{err}");
        assert!(msg.contains("disabled"), "got: {msg}");
    }

    #[test]
    fn io_module_shim_works() {
        // io is now a safe shim, not nil
        let script = r#"
            plugin = { name="x", version="1", author="y", hooks = {} }
            assert(type(io) == "table", "io should be a table")
            assert(type(io.open) == "function", "io.open should be a function")
        "#;
        LuaPlugin::from_string_with_options(script, "x", loose_opts()).unwrap();
    }

    #[test]
    fn debug_module_is_absent() {
        let script = r#"
            plugin = { name="x", version="1", author="y", hooks = {} }
            assert(debug == nil, "debug should be nil")
        "#;
        LuaPlugin::from_string_with_options(script, "x", loose_opts()).unwrap();
    }

    #[test]
    fn http_blocked_without_network_capability() {
        let script = r#"
            plugin = { name="x", version="1", author="y", hooks = { on_issue_created = true } }
            function on_issue_created(_)
                local r = http.get("https://example.com")
                return { ok = r.ok }
            end
        "#;
        let opts = loose_opts();
        let mut p = LuaPlugin::from_string_with_options(script, "x", opts).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let err = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .err()
            .expect("network should be denied");
        assert!(format!("{err}").contains("network"));
    }

    #[test]
    fn storage_round_trip() {
        let script = r#"
            plugin = { name="store-test", version="1", author="t",
                hooks = { on_issue_created = true } }
            function on_issue_created(_)
                storage.set("k", { v = 42 })
                local got = storage.get("k")
                return { v = got.v }
            end
        "#;
        let temp = tempfile::tempdir().unwrap();
        let mut opts = loose_opts();
        opts.repo_root = Some(temp.path().to_path_buf());
        let mut p = LuaPlugin::from_string_with_options(script, "store-test", opts).unwrap();
        let ctx = PluginContext {
            repo_path: temp.path().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let r = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .unwrap();
        assert_eq!(r["v"], 42);
    }

    #[test]
    fn sober_capability_is_blocked_without_host() {
        let script = r#"
            plugin = { name="sober-denied", version="1", author="t",
                hooks = { on_issue_created = true } }
            function on_issue_created(_)
                return sober.run("doctor", {})
            end
        "#;
        let mut p = LuaPlugin::from_string_with_options(script, "sober-denied", loose_opts()).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let err = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .err()
            .expect("sober should require host capability");
        assert!(format!("{err}").contains("sober.run requires"));
    }

    #[test]
    fn sober_capability_round_trips_through_host() {
        let script = r#"
            plugin = { name="sober-ok", version="1", author="t",
                hooks = { on_issue_created = true } }
            function on_issue_created(_)
                return sober.run("preflight", { base = "HEAD" })
            end
        "#;
        let mut opts = loose_opts();
        opts.sober = Some(SoberHost::new(|invocation| {
            assert_eq!(invocation.action, "preflight");
            assert_eq!(invocation.options["base"], "HEAD");
            SoberInvocationResult {
                ok: true,
                data: serde_json::json!({ "action": invocation.action, "ok": true }),
                error: None,
            }
        }));
        let mut p = LuaPlugin::from_string_with_options(script, "sober-ok", opts).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let r = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .unwrap();
        assert_eq!(r["ok"], true);
        assert_eq!(r["data"]["action"], "preflight");
    }

    #[test]
    fn instruction_cap_trips_runaway_loop() {
        // [HAZMAT] LuaJIT's tracing JIT can compile tight integer loops to
        // native code that bypasses debug hooks. We turn JIT off in this
        // test so we are verifying the *mechanism* (hook → counter → abort)
        // rather than fighting the JIT. In production, plugins that touch
        // tables / strings / IO trigger hooks frequently enough that the
        // cap fires within milliseconds anyway. A plugin that genuinely
        // wants to spin a JIT-traceable loop forever still hits the
        // memory cap or the host's overall watchdog.
        let script = r#"
            jit.off()
            plugin = { name="loopy", version="1", author="t",
                hooks = { on_issue_created = true } }
            function on_issue_created(_)
                local i = 0
                while true do i = i + 1 end
                return { i = i }
            end
        "#;
        let mut opts = loose_opts();
        opts.max_instructions = 100_000;
        let mut p = LuaPlugin::from_string_with_options(script, "loopy", opts).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let err = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .err()
            .expect("runaway loop should hit the instruction cap");
        assert!(format!("{err}").contains("instruction budget"), "{err}");
    }

    #[test]
    fn highlight_round_trips_through_lua() {
        let script = r#"
            plugin = { name="hl", version="1", author="t", hooks = {} }
            function plugin.highlight(req)
                return {
                    spans = {
                        { text = "fn ", fg = { r = 200, g = 0, b = 0 }, bold = true },
                        { text = req.content:sub(4) },
                    }
                }
            end
        "#;
        let mut p = LuaPlugin::from_string_with_options(script, "hl", loose_opts()).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let resp = p
            .highlight(&HighlightRequest {
                language: Some("rust".into()),
                content: "fn main() {}".into(),
            })
            .expect("highlight should not error")
            .expect("plugin should return spans");
        assert_eq!(resp.spans.len(), 2);
        assert_eq!(resp.spans[0].text, "fn ");
        assert_eq!(resp.spans[0].fg, Some(crate::render::Rgb::new(200, 0, 0)));
        assert!(resp.spans[0].bold);
        assert_eq!(resp.spans[1].text, "main() {}");
    }

    #[test]
    fn highlight_returns_none_when_plugin_does_not_implement_it() {
        let script = r#"
            plugin = { name="nohl", version="1", author="t", hooks = {} }
        "#;
        let mut p = LuaPlugin::from_string_with_options(script, "nohl", loose_opts()).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let resp = p
            .highlight(&HighlightRequest {
                language: None,
                content: "x".into(),
            })
            .unwrap();
        assert!(resp.is_none(), "plugin without highlight() should yield None");
    }

    #[test]
    fn back_compat_global_log_info_works() {
        let script = r#"
            plugin = { name="bc", version="1", author="t",
                hooks = { on_issue_created = true } }
            function on_issue_created(_)
                log_info("hello from v0.1 style")
                return { ok = true }
            end
        "#;
        let mut p = LuaPlugin::from_string_with_options(script, "bc", loose_opts()).unwrap();
        let ctx = PluginContext {
            repo_path: std::env::temp_dir().to_string_lossy().to_string(),
            user: None,
            env: Default::default(),
            config: Default::default(),
        };
        p.init(&ctx).unwrap();
        let r = p
            .execute_hook(&PluginHook::OnIssueCreated, &serde_json::json!({}))
            .unwrap();
        assert_eq!(r["ok"], true);
    }
}