greentic-ext-runtime 1.2.26

Wasmtime-based runtime for Greentic Designer Extensions
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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
use std::collections::HashMap;
use std::sync::Arc;

use arc_swap::ArcSwap;
use tokio::sync::broadcast;
use wasmtime::Engine;

use crate::capability::{CapabilityRegistry, OfferedBinding};
use crate::discovery::DiscoveryPaths;
use crate::error::RuntimeError;
use crate::loaded::{ExtensionId, HostOverrides, LoadedExtension, LoadedExtensionRef};

/// Filename of the persistent enable/disable state document, located at
/// `<home>/extensions-state.json`. Kept in sync with the constant of the
/// same name in `greentic-ext-state` (single source of truth lives there;
/// this duplicate exists only because the runtime intentionally does not
/// depend on `greentic-ext-state` to avoid a circular crate dependency).
const STATE_FILENAME: &str = "extensions-state.json";

/// Configuration passed to [`ExtensionRuntime::new`].
///
/// Carries both the filesystem discovery paths and the [`HostOverrides`]
/// bundle that every dispatch call injects into the wasmtime `HostState`.
/// Callers that only need defaults (tests, simple CLI tools) can use
/// [`RuntimeConfig::from_paths`]; production callers that need real
/// i18n/secrets/HTTP backends chain [`RuntimeConfig::with_host_overrides`]
/// before handing the config to the runtime.
#[derive(Clone, Debug)]
pub struct RuntimeConfig {
    pub paths: DiscoveryPaths,
    /// Host-function overrides threaded into every WASM dispatch.
    /// Defaults to [`HostOverrides::default()`] (key-translator, empty
    /// secrets, no HTTP client, empty allow-list, no broker weak ref).
    /// Production callers replace this via [`RuntimeConfig::with_host_overrides`]
    /// or the ergonomic [`ExtensionRuntime::with_host_overrides`] builder.
    pub host_overrides: HostOverrides,
}

impl RuntimeConfig {
    /// Construct a config from discovery paths, using production-safe
    /// [`HostOverrides::default()`] (no HTTP client, empty secrets/i18n).
    #[must_use]
    pub fn from_paths(paths: DiscoveryPaths) -> Self {
        Self {
            paths,
            host_overrides: HostOverrides::default(),
        }
    }

    /// Replace the [`HostOverrides`] bundle. Returns `self` for builder-style
    /// chaining:
    ///
    /// ```ignore
    /// let config = RuntimeConfig::from_paths(paths)
    ///     .with_host_overrides(production_overrides);
    /// ```
    #[must_use]
    pub fn with_host_overrides(mut self, overrides: HostOverrides) -> Self {
        self.host_overrides = overrides;
        self
    }
}

pub struct ExtensionRuntime {
    engine: Engine,
    config: RuntimeConfig,
    loaded: ArcSwap<HashMap<ExtensionId, LoadedExtensionRef>>,
    capability_registry: ArcSwap<CapabilityRegistry>,
    events: broadcast::Sender<RuntimeEvent>,
}

#[derive(Debug, Clone)]
pub enum RuntimeEvent {
    ExtensionInstalled(ExtensionId),
    ExtensionUpdated {
        id: ExtensionId,
        prev_version: String,
    },
    ExtensionRemoved(ExtensionId),
    CapabilityRegistryRebuilt,
    /// `~/.greentic/extensions-state.json` was created or modified. Subscribers
    /// should reload extension state and re-apply their enable/disable filter.
    StateFileChanged,
}

/// Returned by [`ExtensionRuntime::start_watcher`]. Dropping this stops the
/// watcher thread cleanly (within ~200 ms).
pub struct WatcherGuard {
    stop_tx: Option<std::sync::mpsc::Sender<()>>,
    join: Option<std::thread::JoinHandle<()>>,
}

impl Drop for WatcherGuard {
    fn drop(&mut self) {
        // Drop stop_tx first to signal the thread, then join.
        drop(self.stop_tx.take());
        if let Some(handle) = self.join.take() {
            let _ = handle.join();
        }
    }
}

impl ExtensionRuntime {
    pub fn new(config: RuntimeConfig) -> Result<Self, RuntimeError> {
        let mut ec = wasmtime::Config::new();
        ec.wasm_component_model(true);

        // Persist compiled component artifacts to an on-disk cache. Without
        // this, every `Component::from_file` recompiles the WASM via Cranelift
        // on each boot — the dominant designer startup cost (~28 extensions,
        // several seconds). The default cache keys on the module bytes plus the
        // compiler settings, so a warm cache turns subsequent boots into a
        // deserialize instead of a recompile. Failing to initialise the cache
        // is non-fatal: we log and fall back to the no-cache (recompile) path.
        match wasmtime::Cache::from_file(None) {
            Ok(cache) => {
                ec.cache(Some(cache));
            }
            Err(e) => {
                tracing::warn!("wasmtime compilation cache disabled: {e}");
            }
        }

        let engine = Engine::new(&ec).map_err(|e| RuntimeError::Wasmtime(e.into()))?;
        let (tx, _) = broadcast::channel(64);
        Ok(Self {
            engine,
            config,
            loaded: ArcSwap::from_pointee(HashMap::new()),
            capability_registry: ArcSwap::from_pointee(CapabilityRegistry::default()),
            events: tx,
        })
    }

    /// Construct a runtime with **no extensions loaded**, for downstream
    /// unit tests that need an `ExtensionRuntime` instance but do not
    /// exercise real WASM dispatch.
    ///
    /// Uses production-safe [`HostOverrides::default()`] and a throwaway
    /// discovery path that is never read (no extension is ever loaded).
    /// `list_tools` returns empty; `invoke_tool` returns a not-found error.
    ///
    /// This exists so crates like `greentic-aw-runtime` can build an
    /// `Arc<ExtensionRuntime>` in `--features test-mock` unit tests
    /// without a live extension directory. Do NOT use in production.
    #[must_use]
    pub fn for_test() -> Self {
        let paths =
            DiscoveryPaths::new(std::path::PathBuf::from("/nonexistent/aw-ext-runtime-test"));
        Self::new(RuntimeConfig::from_paths(paths))
            .expect("for_test ExtensionRuntime construction is infallible")
    }

    /// Replace the [`HostOverrides`] bundle used for every dispatch. Call
    /// once at startup with adapters that wrap real backends (i18n
    /// catalogue, secrets store, allow-listed HTTP client). Without this,
    /// host fns resolve through [`HostOverrides::default`] — fine for unit
    /// tests, not for production: i18n returns the key, secrets are empty,
    /// http allow-list is empty.
    ///
    /// This is a thin ergonomic wrapper over
    /// [`RuntimeConfig::with_host_overrides`] for callers that already hold
    /// an `ExtensionRuntime` instance:
    ///
    /// ```ignore
    /// let runtime = ExtensionRuntime::new(config)?
    ///     .with_host_overrides(production_overrides);
    /// ```
    #[must_use]
    pub fn with_host_overrides(mut self, host_overrides: HostOverrides) -> Self {
        self.config.host_overrides = host_overrides;
        self
    }

    #[must_use]
    pub fn engine(&self) -> &Engine {
        &self.engine
    }

    /// Sister modules (`runtime_roles`) reach for the active overrides via
    /// this accessor instead of touching `config` directly.
    #[must_use]
    pub(crate) fn host_overrides(&self) -> &HostOverrides {
        &self.config.host_overrides
    }

    #[must_use]
    pub fn subscribe(&self) -> broadcast::Receiver<RuntimeEvent> {
        self.events.subscribe()
    }

    #[must_use]
    pub fn config(&self) -> &RuntimeConfig {
        &self.config
    }

    #[must_use]
    pub fn loaded(&self) -> Arc<HashMap<ExtensionId, LoadedExtensionRef>> {
        self.loaded.load_full()
    }

    #[must_use]
    pub fn capability_registry(&self) -> Arc<CapabilityRegistry> {
        self.capability_registry.load_full()
    }

    pub fn register_loaded_from_dir(&mut self, dir: &std::path::Path) -> Result<(), RuntimeError> {
        Self::verify_dir_signature(dir)?;
        let loaded = LoadedExtension::load_from_dir(&self.engine, dir)?;
        let id = loaded.id.clone();

        // Build new registry: clone existing offerings, add new extension's offerings.
        let mut new_registry = CapabilityRegistry::new();
        for existing in self.capability_registry.load().offerings() {
            new_registry.add_offering(existing.clone());
        }
        for cap in &loaded.describe.capabilities.offered {
            let version: semver::Version = cap.version.parse().map_err(|e: semver::Error| {
                RuntimeError::Wasmtime(anyhow::anyhow!("bad offered version: {e}"))
            })?;
            new_registry.add_offering(OfferedBinding {
                extension_id: id.as_str().to_string(),
                cap_id: cap.id.clone(),
                version,
                kind: loaded.kind,
                export_path: String::new(),
            });
        }

        // Atomically swap in new loaded map and registry.
        let mut new_map = (**self.loaded.load()).clone();
        new_map.insert(id.clone(), Arc::new(loaded));
        self.loaded.store(Arc::new(new_map));
        self.capability_registry.store(Arc::new(new_registry));

        let _ = self.events.send(RuntimeEvent::ExtensionInstalled(id));
        Ok(())
    }

    fn verify_dir_signature(dir: &std::path::Path) -> Result<(), RuntimeError> {
        #[cfg(feature = "dev-allow-unsigned")]
        if std::env::var("GREENTIC_EXT_ALLOW_UNSIGNED").is_ok() {
            tracing::warn!(
                extension_dir = %dir.display(),
                "GREENTIC_EXT_ALLOW_UNSIGNED is set — signature verification skipped"
            );
            return Ok(());
        }
        let path = dir.join("describe.json");
        let raw = std::fs::read_to_string(&path)?;
        // Migrate a v1 describe to the current shape before deserializing, the
        // same way `LoadedExtension::load_from_dir` does — the bundled fallback
        // extensions are all v1 and would otherwise fail here with a raw
        // "expected struct Knowledge". Unsigned describes (all bundled ones)
        // carry no signature, so the self-consistency check below is unaffected
        // by the migration.
        let describe_value: serde_json::Value = serde_json::from_str(&raw)?;
        let describe = crate::loaded::describe_from_value(describe_value)
            .map_err(|e| RuntimeError::Wasmtime(anyhow::anyhow!("read describe.json: {e}")))?;
        // Integrity: the describe is unmodified since signing. This is NOT
        // authenticity — it proves nothing about *who* signed (an attacker can
        // re-sign with their own key). Anchored authenticity
        // (`verify_describe_with_key` against a trust-store / RootVerifier key)
        // is the audit C1 follow-up; it needs a runtime trust store and the
        // org-provisioned prod root key (both currently blocked).
        greentic_extension_sdk_contract::verify_describe_self_consistent(&describe).map_err(
            |e| RuntimeError::SignatureInvalid {
                extension_id: describe.metadata.id.clone(),
                reason: e.to_string(),
            },
        )?;
        let pub_prefix = describe.signature.as_ref().map_or_else(
            || "?".to_string(),
            |s| s.public_key.chars().take(16).collect::<String>(),
        );
        tracing::info!(
            extension_id = %describe.metadata.id,
            key_prefix = %pub_prefix,
            "extension signature verified"
        );
        Self::verify_dir_manifest(dir, &describe)?;
        Ok(())
    }

    /// Verify the unpacked extension dir against its `manifest.json`
    /// (whole-archive integrity ledger).
    ///
    /// Audit P5 hardening — fail **closed**:
    /// - A missing `manifest.json` is now a hard error. Pre-ledger packs only
    ///   load under the `dev-allow-unsigned` escape (checked upstream in
    ///   [`verify_dir_signature`]); production refuses an unverifiable pack.
    /// - The describe's manifest binding (`manifestSha256`) must match the
    ///   on-disk `manifest.json`, so the (signed) describe transitively commits
    ///   to the ledger — an attacker cannot swap the manifest without breaking
    ///   the describe signature ([`verify_manifest_binding`]).
    /// - Every file the manifest lists must then hash to the recorded sha256.
    ///
    /// Closes audit P0 #2 (wasm + sibling archive entries unsigned) and the C2
    /// binding gap on the consumer side.
    fn verify_dir_manifest(
        dir: &std::path::Path,
        describe: &greentic_extension_sdk_contract::DescribeJson,
    ) -> Result<(), RuntimeError> {
        use sha2::{Digest, Sha256};
        let extension_id = describe.metadata.id.as_str();
        let manifest_path = dir.join(greentic_extension_sdk_contract::MANIFEST_ENTRY_NAME);
        if !manifest_path.exists() {
            return Err(RuntimeError::SignatureInvalid {
                extension_id: extension_id.to_string(),
                reason: "manifest.json absent — refusing to load an extension without a \
                         whole-archive integrity ledger (set GREENTIC_EXT_ALLOW_UNSIGNED \
                         with the dev-allow-unsigned build for local dev)"
                    .to_string(),
            });
        }
        let raw = std::fs::read(&manifest_path)?;
        // Binding: the signed describe commits to exactly this manifest, so the
        // signature transitively covers the ledger (audit C2). Rejects both a
        // swapped manifest and an unbound (legacy) describe carrying a manifest.
        greentic_extension_sdk_contract::verify_manifest_binding(describe, &raw).map_err(|e| {
            RuntimeError::SignatureInvalid {
                extension_id: extension_id.to_string(),
                reason: format!("manifest binding: {e}"),
            }
        })?;
        let manifest: greentic_extension_sdk_contract::Manifest = serde_json::from_slice(&raw)
            .map_err(|e| RuntimeError::SignatureInvalid {
                extension_id: extension_id.to_string(),
                reason: format!("manifest.json parse: {e}"),
            })?;
        if manifest.schema != greentic_extension_sdk_contract::MANIFEST_SCHEMA_V1 {
            return Err(RuntimeError::SignatureInvalid {
                extension_id: extension_id.to_string(),
                reason: format!("manifest schema unsupported: {}", manifest.schema),
            });
        }
        for entry in &manifest.entries {
            let path = dir.join(&entry.path);
            if !path.exists() {
                return Err(RuntimeError::SignatureInvalid {
                    extension_id: extension_id.to_string(),
                    reason: format!("manifest lists missing file: {}", entry.path),
                });
            }
            let bytes = std::fs::read(&path)?;
            let computed = format!("{:x}", Sha256::digest(&bytes));
            if computed != entry.sha256 {
                return Err(RuntimeError::SignatureInvalid {
                    extension_id: extension_id.to_string(),
                    reason: format!(
                        "manifest sha256 mismatch for {}: expected {} got {}",
                        entry.path, entry.sha256, computed
                    ),
                });
            }
        }
        tracing::info!(
            extension_id = %extension_id,
            entries = manifest.entries.len(),
            "whole-archive manifest verified"
        );
        Ok(())
    }

    /// Spawns a watcher background thread. Events trigger reload of the
    /// affected extension's directory. Returns a stop sender — dropping or
    /// sending on it signals the watcher thread to exit. Also returns the
    /// thread `JoinHandle` for callers that want to wait for clean shutdown.
    pub fn start_watcher(self: Arc<Self>) -> Result<WatcherGuard, RuntimeError> {
        let mut paths: Vec<std::path::PathBuf> =
            self.config.paths.all().into_iter().cloned().collect();
        // Also watch the parent of the extensions root so we receive events
        // for `<home>/extensions-state.json`. Best-effort: if the home dir
        // doesn't exist or has no parent we silently skip — the kind dirs
        // are still watched.
        if let Some(home) = self.config.paths.home()
            && home.exists()
            && !paths.iter().any(|p| p == home)
        {
            paths.push(home.to_path_buf());
        }
        let (rx, watch_handle) = crate::watcher::watch(&paths)?;
        let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
        let this = self.clone();
        let join = std::thread::spawn(move || {
            // Own the watch_handle here — dropping it closes the fs watcher
            // and the tx side of the FsEvent channel when this thread exits.
            let _watch_handle = watch_handle;
            loop {
                // Check stop signal (Ok = message received, Disconnected = sender dropped).
                match stop_rx.try_recv() {
                    Ok(()) | Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
                    Err(std::sync::mpsc::TryRecvError::Empty) => {}
                }
                match rx.recv_timeout(std::time::Duration::from_millis(200)) {
                    Ok(event) => {
                        if let Err(e) = this.handle_fs_event(&event) {
                            tracing::warn!(error = %e, "hot reload failed");
                        }
                    }
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                    Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
                }
            }
        });
        Ok(WatcherGuard {
            stop_tx: Some(stop_tx),
            join: Some(join),
        })
    }

    fn handle_fs_event(&self, event: &crate::watcher::FsEvent) -> Result<(), RuntimeError> {
        use crate::watcher::FsEvent;
        let path = match event {
            FsEvent::Added(p) | FsEvent::Modified(p) | FsEvent::Removed(p) => p.clone(),
        };

        // Classify state file events first. The state file lives at
        // `<home>/extensions-state.json`, which is outside the per-kind
        // extension dirs, so `find_extension_dir` would return None — but
        // matching by filename is cheaper and unambiguous.
        if path.file_name().is_some_and(|n| n == STATE_FILENAME) {
            let _ = self.events.send(RuntimeEvent::StateFileChanged);
            return Ok(());
        }

        let ext_dir = find_extension_dir(&path);
        match event {
            FsEvent::Removed(_) => {
                if let Some(dir) = ext_dir {
                    self.handle_removal(&dir);
                }
            }
            FsEvent::Added(_) | FsEvent::Modified(_) => {
                if let Some(dir) = ext_dir {
                    self.handle_added_or_modified(&dir)?;
                }
            }
        }
        Ok(())
    }

    fn handle_removal(&self, dir: &std::path::Path) {
        let current = self.loaded.load();
        let Some((id, _)) = current.iter().find(|(_, v)| v.source_dir == dir) else {
            return;
        };
        let id = id.clone();
        let mut new_map = (**current).clone();
        new_map.remove(&id);
        self.loaded.store(Arc::new(new_map));
        let _ = self.events.send(RuntimeEvent::ExtensionRemoved(id));
    }

    fn handle_added_or_modified(&self, dir: &std::path::Path) -> Result<(), RuntimeError> {
        let loaded = crate::loaded::LoadedExtension::load_from_dir(&self.engine, dir)?;
        let id = loaded.id.clone();
        let mut new_map = (**self.loaded.load()).clone();
        let prev_version = new_map
            .get(&id)
            .map(|e| e.describe.metadata.version.clone());
        new_map.insert(id.clone(), Arc::new(loaded));
        self.loaded.store(Arc::new(new_map));
        let event = match prev_version {
            Some(prev) => RuntimeEvent::ExtensionUpdated {
                id,
                prev_version: prev,
            },
            None => RuntimeEvent::ExtensionInstalled(id),
        };
        let _ = self.events.send(event);
        Ok(())
    }
}

impl ExtensionRuntime {
    /// Invoke a named tool on a loaded extension.
    ///
    /// Builds a fresh wasmtime Store + Instance, calls
    /// `greentic:extension-design/tools::invoke-tool` (resolved
    /// newest-first across 0.3.0/0.2.0/0.1.0; WIT errors surface as
    /// `RuntimeError::Extension`), and returns the JSON result string.
    pub fn invoke_tool(
        &self,
        ext_id: &str,
        tool_name: &str,
        args_json: &str,
    ) -> Result<String, RuntimeError> {
        self.invoke_tool_ctx(
            ext_id,
            tool_name,
            args_json,
            &crate::host_ports::HostCallContext::default(),
        )
    }

    /// Like [`Self::invoke_tool`] but threads a per-call
    /// [`crate::host_ports::HostCallContext`] (e.g. the caller's tenant slug)
    /// into the host ports for this dispatch. Multi-tenant hosts (the
    /// designer) use this so the LLM port can resolve roles per-tenant.
    pub fn invoke_tool_ctx(
        &self,
        ext_id: &str,
        tool_name: &str,
        args_json: &str,
        ctx: &crate::host_ports::HostCallContext,
    ) -> Result<String, RuntimeError> {
        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(&self.engine, self.config.host_overrides.clone(), ctx)
            .map_err(RuntimeError::Wasmtime)?;

        // Resolve the nested export: first the interface instance, then the function.
        // This is the wasmtime 43 pattern: get_export_index(store, parent, name).
        // The interface is resolved newest-first across the design version table;
        // the matched version selects which `extension-error` ABI to deserialize
        // (6-variant base at 0.3.0, 4-variant base at 0.2.0/0.1.0). The
        // invoke-tool signature is identical across versions — only the error
        // variant set differs.
        let (iface_idx, iface_name, version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-design/tools",
            DESIGN_VERSIONS,
        )?;
        warn_if_legacy_contract(ext_id, version, DESIGN_VERSIONS[0]);
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "invoke-tool")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'invoke-tool'"
                ))
            })?;

        let call_args = (tool_name.to_string(), args_json.to_string());
        // post_return is deprecated/no-op in wasmtime 43 — not called.
        let mapped: Result<String, crate::types::HostExtensionError> = if version == "0.3.0" {
            use crate::host_bindings::design_v03::greentic::extension_base0_2_0::types::ExtensionError as E2;
            let func = instance
                .get_typed_func::<(String, String), (Result<String, E2>,)>(&mut store, &func_idx)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            let (r,) = func
                .call(&mut store, call_args)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            r.map_err(crate::ext_error::from_design_v03)
        } else {
            use crate::host_bindings::greentic::extension_base0_1_0::types::ExtensionError as E1;
            let func = instance
                .get_typed_func::<(String, String), (Result<String, E1>,)>(&mut store, &func_idx)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            let (r,) = func
                .call(&mut store, call_args)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            r.map_err(crate::ext_error::from_design_v01)
        };

        mapped.map_err(RuntimeError::Extension)
    }
}

impl ExtensionRuntime {
    /// Evaluate a guardrail extension against `input_json` and return the
    /// verdict as a JSON string.
    ///
    /// Loads the extension identified by `ext_id`, resolves the
    /// `greentic:extension-design/guardrail@0.3.0` interface, calls the
    /// `evaluate` export, and maps the returned `verdict` variant to
    /// [`crate::GuardrailVerdictWire`] serialised as JSON.
    ///
    /// `input_json` must be a JSON object with fields matching the WIT
    /// `guardrail-input` record:
    ///
    /// ```json
    /// {
    ///   "direction": "inbound",
    ///   "content": "…",
    ///   "agent_id": "…",
    ///   "session_id": "…",
    ///   "tenant_id": "…",
    ///   "env_id": "…",
    ///   "context": null
    /// }
    /// ```
    ///
    /// Returns the verdict as JSON, e.g. `{"kind":"accept"}` or
    /// `{"kind":"deny","code":"…","message":"…","details":null}`.
    ///
    /// # Errors
    ///
    /// - [`RuntimeError::NotFound`] when no extension is loaded at `ext_id`.
    /// - [`RuntimeError::Wasmtime`] when store/instance construction fails,
    ///   the interface is not exported, the typed-func call fails, or
    ///   `input_json` cannot be deserialised.
    pub fn evaluate_guardrail(
        &self,
        ext_id: &str,
        input_json: &str,
    ) -> Result<String, RuntimeError> {
        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        // Guardrail interface only exists at 0.3.0 — a single-version table.
        let (iface_idx, iface_name, _version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-design/guardrail",
            GUARDRAIL_VERSIONS,
        )?;

        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "evaluate")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'evaluate'"
                ))
            })?;

        let wire =
            crate::guardrail_map::call_evaluate(&mut store, &instance, &func_idx, input_json)?;

        serde_json::to_string(&wire).map_err(|e| RuntimeError::Wasmtime(e.into()))
    }
}

impl ExtensionRuntime {
    /// Validate extension-specific content against the extension's schema.
    ///
    /// Calls `greentic:extension-design/validation::validate-content`
    /// (resolved against `@0.2.0` first, then `@0.1.0`).
    /// `content_type` is an extension-defined label (e.g. `"AdaptiveCard"`
    /// for the adaptive-cards extension); `content_json` is the content
    /// payload as a JSON string.
    ///
    /// Returns a [`types::ValidateResult`] with a `valid` flag and a list of
    /// diagnostics (error/warning/info/hint severities). Extensions that
    /// don't export this interface surface a `Wasmtime` error — callers
    /// that want graceful degradation should treat "interface not exported"
    /// as "no validation available" rather than a hard failure.
    pub fn validate_content(
        &self,
        ext_id: &str,
        content_type: &str,
        content_json: &str,
    ) -> Result<crate::types::ValidateResult, RuntimeError> {
        use crate::host_bindings::exports::greentic::extension_design0_2_0::validation::{
            Diagnostic as WitDiagnostic, ValidateResult as WitValidateResult,
        };
        use crate::host_bindings::greentic::extension_base0_1_0::types::Severity as WitSeverity;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name) = resolve_design_iface(
            &mut store,
            &instance,
            "greentic:extension-design/validation",
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "validate-content")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'validate-content'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(String, String), (WitValidateResult,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (result,) = func
            .call(
                &mut store,
                (content_type.to_string(), content_json.to_string()),
            )
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let diagnostics = result
            .diagnostics
            .into_iter()
            .map(|d: WitDiagnostic| crate::types::Diagnostic {
                severity: match d.severity {
                    WitSeverity::Error => crate::types::Severity::Error,
                    WitSeverity::Warning => crate::types::Severity::Warning,
                    WitSeverity::Info => crate::types::Severity::Info,
                    WitSeverity::Hint => crate::types::Severity::Hint,
                },
                code: d.code,
                message: d.message,
                path: d.path,
            })
            .collect();

        Ok(crate::types::ValidateResult {
            valid: result.valid,
            diagnostics,
        })
    }
}

/// Map a v2 describe `Tool` contribution to a host-side [`crate::types::ToolDefinition`].
///
/// `description` and `input_schema_json` come from the declarative
/// `describe.json` tool entry (`Tool.description` / `Tool.input_schema`, the
/// latter a JSON-Schema string mirroring `NodeType.config_schema`). A tool that
/// omits them surfaces empty values, so callers can still offer the tool — but
/// an empty input schema means the LLM cannot infer the tool's arguments.
#[must_use]
pub fn contribution_tool_to_definition(
    t: &greentic_extension_sdk_contract::describe::contributions::Tool,
) -> crate::types::ToolDefinition {
    crate::types::ToolDefinition {
        name: t.name.clone(),
        description: t.description.clone().unwrap_or_default(),
        input_schema_json: t.input_schema.clone().unwrap_or_default(),
        output_schema_json: None,
        capabilities: t.capabilities.clone(),
        agentic_worker_metadata: None,
        secret_requirements: t.secret_requirements.clone(),
    }
}

impl ExtensionRuntime {
    /// List all tools exposed by a loaded design extension.
    ///
    /// Calls `greentic:extension-design/tools::list-tools` (resolved
    /// against `@0.2.0` first, then `@0.1.0`) for v1-contract
    /// extensions. **v2 contract** (`apiVersion == "greentic.ai/v2"`)
    /// reads the tools from `describe.contributions.tools[]` — the
    /// runtime WIT no longer exports `list-tools` in that contract.
    /// The declarative v2 entries only carry `name` + `export`, so
    /// `description` / `input_schema_json` come back empty; callers
    /// that need full schemas must introspect the named WIT export.
    pub fn list_tools(
        &self,
        ext_id: &str,
    ) -> Result<Vec<crate::types::ToolDefinition>, RuntimeError> {
        use crate::host_bindings::exports::greentic::extension_design0_2_0::tools::ToolDefinition as WitToolDef;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        // v2 declarative path: tools live in describe.json, not in WIT.
        if loaded.describe.api_version == "greentic.ai/v2" {
            return Ok(loaded
                .describe
                .contributions
                .tools
                .iter()
                .map(contribution_tool_to_definition)
                .collect());
        }

        // v1 WIT-call path.
        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name) =
            resolve_design_iface(&mut store, &instance, "greentic:extension-design/tools")?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "list-tools")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'list-tools'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(), (Vec<WitToolDef>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (defs,) = func
            .call(&mut store, ())
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(defs
            .into_iter()
            .map(|d| crate::types::ToolDefinition {
                name: d.name,
                description: d.description,
                input_schema_json: d.input_schema_json,
                output_schema_json: d.output_schema_json,
                capabilities: d.capabilities,
                agentic_worker_metadata: d.agentic_worker_metadata,
                secret_requirements: Vec::new(),
            })
            .collect())
    }
}

impl ExtensionRuntime {
    /// Retrieve system prompt fragments from a loaded design extension.
    ///
    /// Calls `greentic:extension-design/prompting::system-prompt-fragments`
    /// (resolved against `@0.2.0` first, then `@0.1.0`).
    pub fn prompt_fragments(
        &self,
        ext_id: &str,
    ) -> Result<Vec<crate::types::PromptFragment>, RuntimeError> {
        use crate::host_bindings::exports::greentic::extension_design0_2_0::prompting::PromptFragment as WitFrag;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name) =
            resolve_design_iface(&mut store, &instance, "greentic:extension-design/prompting")?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "system-prompt-fragments")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'system-prompt-fragments'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(), (Vec<WitFrag>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (frags,) = func
            .call(&mut store, ())
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(frags
            .into_iter()
            .map(|f| crate::types::PromptFragment {
                section: f.section,
                content_markdown: f.content_markdown,
                priority: f.priority,
            })
            .collect())
    }
}

impl ExtensionRuntime {
    /// List knowledge entries, optionally filtered by category.
    ///
    /// Calls `greentic:extension-design/knowledge::list-entries`
    /// (resolved against `@0.2.0` first, then `@0.1.0`).
    pub fn knowledge_list(
        &self,
        ext_id: &str,
        category_filter: Option<&str>,
    ) -> Result<Vec<crate::types::KnowledgeEntrySummary>, RuntimeError> {
        use crate::host_bindings::exports::greentic::extension_design0_2_0::knowledge::EntrySummary as WitSummary;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name) =
            resolve_design_iface(&mut store, &instance, "greentic:extension-design/knowledge")?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "list-entries")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'list-entries'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(Option<String>,), (Vec<WitSummary>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (entries,) = func
            .call(&mut store, (category_filter.map(String::from),))
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(entries.into_iter().map(wit_summary_to_host).collect())
    }

    /// Retrieve a single knowledge entry by ID.
    ///
    /// Calls `greentic:extension-design/knowledge::get-entry`, resolving the
    /// interface newest-first across `@0.3.0`/`@0.2.0`/`@0.1.0`. The matched
    /// version selects which `extension-error` ABI to deserialize (6-variant
    /// base at `@0.3.0`, 4-variant base at `@0.2.0`/`@0.1.0`); WIT errors
    /// surface as `RuntimeError::Extension`.
    pub fn knowledge_get(
        &self,
        ext_id: &str,
        entry_id: &str,
    ) -> Result<crate::types::KnowledgeEntry, RuntimeError> {
        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name, version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-design/knowledge",
            DESIGN_VERSIONS,
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "get-entry")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'get-entry'"
                ))
            })?;

        let call_args = (entry_id.to_string(),);
        let mapped: Result<crate::types::KnowledgeEntry, crate::types::HostExtensionError> =
            if version == "0.3.0" {
                use crate::host_bindings::design_v03::exports::greentic::extension_design0_3_0::knowledge::{
                    Entry as WitEntry, ExtensionError as E2,
                };
                let func = instance
                    .get_typed_func::<(String,), (Result<WitEntry, E2>,)>(&mut store, &func_idx)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                let (r,) = func
                    .call(&mut store, call_args)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                r.map(|e| crate::types::KnowledgeEntry {
                    id: e.id,
                    title: e.title,
                    category: e.category,
                    tags: e.tags,
                    content_json: e.content_json,
                })
                .map_err(crate::ext_error::from_design_v03)
            } else {
                use crate::host_bindings::exports::greentic::extension_design0_2_0::knowledge::{
                    Entry as WitEntry, ExtensionError as E1,
                };
                let func = instance
                    .get_typed_func::<(String,), (Result<WitEntry, E1>,)>(&mut store, &func_idx)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                let (r,) = func
                    .call(&mut store, call_args)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                r.map(|e| crate::types::KnowledgeEntry {
                    id: e.id,
                    title: e.title,
                    category: e.category,
                    tags: e.tags,
                    content_json: e.content_json,
                })
                .map_err(crate::ext_error::from_design_v01)
            };

        mapped.map_err(RuntimeError::Extension)
    }

    /// Suggest knowledge entries matching a query.
    ///
    /// Calls `greentic:extension-design/knowledge::suggest-entries`
    /// (resolved against `@0.2.0` first, then `@0.1.0`).
    pub fn knowledge_suggest(
        &self,
        ext_id: &str,
        query: &str,
        limit: u32,
    ) -> Result<Vec<crate::types::KnowledgeEntrySummary>, RuntimeError> {
        use crate::host_bindings::exports::greentic::extension_design0_2_0::knowledge::EntrySummary as WitSummary;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name) =
            resolve_design_iface(&mut store, &instance, "greentic:extension-design/knowledge")?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "suggest-entries")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'suggest-entries'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(String, u32), (Vec<WitSummary>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (entries,) = func
            .call(&mut store, (query.to_string(), limit))
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(entries.into_iter().map(wit_summary_to_host).collect())
    }
}

/// Convert a bindgen `EntrySummary` to the host-side type.
fn wit_summary_to_host(
    s: crate::host_bindings::exports::greentic::extension_design0_2_0::knowledge::EntrySummary,
) -> crate::types::KnowledgeEntrySummary {
    crate::types::KnowledgeEntrySummary {
        id: s.id,
        title: s.title,
        category: s.category,
        tags: s.tags,
    }
}

impl ExtensionRuntime {
    /// Ask a deploy extension to validate a credentials JSON payload for the
    /// given target. Returns diagnostics; empty slice means valid.
    pub fn validate_credentials(
        &self,
        ext_id: &str,
        target_id: &str,
        credentials_json: &str,
    ) -> Result<Vec<crate::types::Diagnostic>, RuntimeError> {
        use crate::host_bindings::deploy::exports::greentic::extension_deploy0_1_0::targets::Diagnostic as WitDiagnostic;
        use crate::host_bindings::deploy::greentic::extension_base0_1_0::types::Severity as WitSeverity;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name, _version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-deploy/targets",
            DEPLOY_VERSIONS,
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "validate-credentials")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'validate-credentials'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(String, String), (Vec<WitDiagnostic>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (result,) = func
            .call(
                &mut store,
                (target_id.to_string(), credentials_json.to_string()),
            )
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(result
            .into_iter()
            .map(|d| crate::types::Diagnostic {
                severity: match d.severity {
                    WitSeverity::Error => crate::types::Severity::Error,
                    WitSeverity::Warning => crate::types::Severity::Warning,
                    WitSeverity::Info => crate::types::Severity::Info,
                    WitSeverity::Hint => crate::types::Severity::Hint,
                },
                code: d.code,
                message: d.message,
                path: d.path,
            })
            .collect())
    }
}

impl ExtensionRuntime {
    /// Return the JSON Schema (as a string) describing credentials required
    /// by the given deploy target.
    pub fn credential_schema(&self, ext_id: &str, target_id: &str) -> Result<String, RuntimeError> {
        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name, version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-deploy/targets",
            DEPLOY_VERSIONS,
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "credential-schema")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'credential-schema'"
                ))
            })?;

        let call_args = (target_id.to_string(),);
        let mapped: Result<String, crate::types::HostExtensionError> = if version == "0.2.0" {
            use crate::host_bindings::deploy_v02::greentic::extension_base0_2_0::types::ExtensionError as E2;
            let func = instance
                .get_typed_func::<(String,), (Result<String, E2>,)>(&mut store, &func_idx)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            let (r,) = func
                .call(&mut store, call_args)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            r.map_err(crate::ext_error::from_deploy_v02)
        } else {
            use crate::host_bindings::deploy::greentic::extension_base0_1_0::types::ExtensionError as E1;
            let func = instance
                .get_typed_func::<(String,), (Result<String, E1>,)>(&mut store, &func_idx)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            let (r,) = func
                .call(&mut store, call_args)
                .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
            r.map_err(crate::ext_error::from_deploy_v01)
        };

        mapped.map_err(RuntimeError::Extension)
    }
}

impl ExtensionRuntime {
    /// Enumerate targets exported by a loaded deploy extension.
    ///
    /// Returns the `list-targets` output as host-side `TargetSummary` values.
    pub fn list_targets(
        &self,
        ext_id: &str,
    ) -> Result<Vec<crate::types::TargetSummary>, RuntimeError> {
        use crate::host_bindings::deploy::exports::greentic::extension_deploy0_1_0::targets::TargetSummary as WitTargetSummary;

        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name, _version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-deploy/targets",
            DEPLOY_VERSIONS,
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "list-targets")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'list-targets'"
                ))
            })?;

        let func = instance
            .get_typed_func::<(), (Vec<WitTargetSummary>,)>(&mut store, &func_idx)
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        let (result,) = func
            .call(&mut store, ())
            .map_err(|e| RuntimeError::Wasmtime(e.into()))?;

        Ok(result
            .into_iter()
            .map(|t| crate::types::TargetSummary {
                id: t.id,
                display_name: t.display_name,
                description: t.description,
                icon_path: t.icon_path,
                supports_rollback: t.supports_rollback,
            })
            .collect())
    }
}

/// Resolve a `greentic:extension-design/<iface>` export by trying `@0.2.0`
/// first and falling back to `@0.1.0`.
///
/// The runtime bumped its WIT to `@0.2.0` in v1.2.x, but several extensions
/// in the wild (http, llm-generic, webhook, platform-bootstrap, ...) were
/// built against `@0.1.0` and have not yet been rebuilt. Without a
/// fallback, every dispatch into those extensions fails with
/// `extension does not export interface 'greentic:extension-design/
/// tools@0.2.0'`. Returning the resolved iface name (with version suffix)
/// lets the nested `func_idx` lookup error name the version that was
/// actually picked.
///
/// `roles@0.2.0` deliberately uses its own dedicated lookup (see
/// `runtime_roles.rs`); it never existed at `@0.1.0`, so no fallback is
/// appropriate there.
/// Tracks extension ids already warned about a legacy WIT contract, so the
/// deprecation notice fires once per extension per process instead of on
/// every dispatch. Bounded by the number of distinct loaded extensions.
static LEGACY_CONTRACT_WARNED: std::sync::OnceLock<
    std::sync::Mutex<std::collections::HashSet<String>>,
> = std::sync::OnceLock::new();

/// Emit a one-shot deprecation warning if `version` is not the newest entry
/// in `newest`. No-op when the extension is already on the current contract
/// or has been warned before.
fn warn_if_legacy_contract(ext_id: &str, version: &str, newest: &str) {
    if version == newest {
        return;
    }
    let set = LEGACY_CONTRACT_WARNED
        .get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()));
    let mut guard = match set.lock() {
        Ok(g) => g,
        Err(poisoned) => poisoned.into_inner(),
    };
    if guard.insert(ext_id.to_string()) {
        tracing::warn!(
            extension = %ext_id,
            contract = version,
            newest = newest,
            "extension uses a deprecated WIT contract version; rebuild against the current contract (unified 6-variant extension-error)"
        );
    }
}

/// Resolve `base@<ver>` against the instance's exports, trying `versions`
/// in order (newest first). Returns the export index, the full resolved
/// interface name, and the bare version string that matched — dispatch
/// code branches on the version to pick the matching typed signature.
pub(crate) fn resolve_iface_versions(
    store: &mut wasmtime::Store<crate::host_state::HostState>,
    instance: &wasmtime::component::Instance,
    base: &str,
    versions: &[&'static str],
) -> Result<
    (
        wasmtime::component::ComponentExportIndex,
        String,
        &'static str,
    ),
    RuntimeError,
> {
    for &v in versions {
        let name = format!("{base}@{v}");
        if let Some(idx) = instance.get_export_index(&mut *store, None, &name) {
            return Ok((idx, name, v));
        }
    }
    Err(RuntimeError::Wasmtime(anyhow::anyhow!(
        "extension does not export interface '{base}' at any supported version ({versions:?})"
    )))
}

/// Version tables per package family — newest first.
const DESIGN_VERSIONS: &[&str] = &["0.3.0", "0.2.0", "0.1.0"];
pub(crate) const DEPLOY_VERSIONS: &[&str] = &["0.2.0", "0.1.0"];
const BUNDLE_VERSIONS: &[&str] = &["0.2.0", "0.1.0"];
/// Guardrail interface only exists at 0.3.0 — single-version table.
const GUARDRAIL_VERSIONS: &[&str] = &["0.3.0"];

fn resolve_design_iface(
    store: &mut wasmtime::Store<crate::host_state::HostState>,
    instance: &wasmtime::component::Instance,
    base: &str,
) -> Result<(wasmtime::component::ComponentExportIndex, String), RuntimeError> {
    resolve_iface_versions(store, instance, base, DESIGN_VERSIONS).map(|(idx, name, _)| (idx, name))
}

fn find_extension_dir(p: &std::path::Path) -> Option<std::path::PathBuf> {
    let mut cur = p;
    loop {
        if cur.join("describe.json").exists() {
            return Some(cur.to_path_buf());
        }
        cur = cur.parent()?;
    }
}

impl ExtensionRuntime {
    /// Render a bundle artefact by dispatching to a loaded bundle
    /// extension's `bundling.render` export.
    ///
    /// Mirrors the in-process call site that replaces the legacy
    /// `greentic-bundle ext render` subprocess pipeline. The host
    /// passes the designer session (flow JSON, content JSON, asset
    /// blobs, capability list) and a recipe-specific config string;
    /// the extension's WASM returns the rendered bytes (typically a
    /// `.gtpack` zip) plus the canonical filename and sha256 the
    /// extension wants written.
    ///
    /// Returns `RuntimeError::NotFound` when no extension is loaded
    /// at `ext_id`. The `bundling` interface is resolved newest-first
    /// across `@0.2.0`/`@0.1.0`; host-level failures surface as
    /// `RuntimeError::Wasmtime`, while the extension's WIT-level error
    /// surfaces as `RuntimeError::Extension` (6-variant base at `@0.2.0`,
    /// 4-variant base at `@0.1.0`).
    pub fn render_bundle(
        &self,
        ext_id: &str,
        recipe_id: &str,
        config_json: &str,
        session: crate::types::BundleSession,
    ) -> Result<crate::types::BundleArtifact, RuntimeError> {
        let loaded = self
            .loaded
            .load()
            .get(&crate::loaded::ExtensionId(ext_id.to_string()))
            .cloned()
            .ok_or_else(|| RuntimeError::NotFound(ext_id.to_string()))?;

        let (mut store, instance) = loaded
            .build_store_and_instance(
                &self.engine,
                self.config.host_overrides.clone(),
                &crate::host_ports::HostCallContext::default(),
            )
            .map_err(RuntimeError::Wasmtime)?;

        let (iface_idx, iface_name, version) = resolve_iface_versions(
            &mut store,
            &instance,
            "greentic:extension-bundle/bundling",
            BUNDLE_VERSIONS,
        )?;
        let func_idx = instance
            .get_export_index(&mut store, Some(&iface_idx), "render")
            .ok_or_else(|| {
                RuntimeError::Wasmtime(anyhow::anyhow!(
                    "interface '{iface_name}' does not export 'render'"
                ))
            })?;

        let mapped: Result<crate::types::BundleArtifact, crate::types::HostExtensionError> =
            if version == "0.2.0" {
                use crate::host_bindings::bundle_v02::exports::greentic::extension_bundle0_2_0::bundling::{
                    BundleArtifact as WitBundleArtifact, DesignerSession as WitDesignerSession,
                };
                use crate::host_bindings::bundle_v02::greentic::extension_base0_2_0::types::ExtensionError as E2;
                let func = instance
                    .get_typed_func::<
                        (String, String, WitDesignerSession),
                        (Result<WitBundleArtifact, E2>,),
                    >(&mut store, &func_idx)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                let wit_session = WitDesignerSession {
                    flows_json: session.flows_json,
                    contents_json: session.contents_json,
                    assets: session.assets,
                    capabilities_used: session.capabilities_used,
                };
                let (r,) = func
                    .call(
                        &mut store,
                        (recipe_id.to_string(), config_json.to_string(), wit_session),
                    )
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                r.map(|a| crate::types::BundleArtifact {
                    filename: a.filename,
                    bytes: a.bytes,
                    sha256: a.sha256,
                })
                .map_err(crate::ext_error::from_bundle_v02)
            } else {
                use crate::host_bindings::bundle::exports::greentic::extension_bundle0_1_0::bundling::{
                    BundleArtifact as WitBundleArtifact, DesignerSession as WitDesignerSession,
                };
                use crate::host_bindings::bundle::greentic::extension_base0_1_0::types::ExtensionError as E1;
                let func = instance
                    .get_typed_func::<
                        (String, String, WitDesignerSession),
                        (Result<WitBundleArtifact, E1>,),
                    >(&mut store, &func_idx)
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                let wit_session = WitDesignerSession {
                    flows_json: session.flows_json,
                    contents_json: session.contents_json,
                    assets: session.assets,
                    capabilities_used: session.capabilities_used,
                };
                let (r,) = func
                    .call(
                        &mut store,
                        (recipe_id.to_string(), config_json.to_string(), wit_session),
                    )
                    .map_err(|e| RuntimeError::Wasmtime(e.into()))?;
                r.map(|a| crate::types::BundleArtifact {
                    filename: a.filename,
                    bytes: a.bytes,
                    sha256: a.sha256,
                })
                .map_err(crate::ext_error::from_bundle_v01)
            };

        mapped.map_err(RuntimeError::Extension)
    }
}

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

    #[test]
    fn list_targets_returns_error_for_unknown_extension() {
        let tmp = tempfile::TempDir::new().unwrap();
        let config =
            RuntimeConfig::from_paths(crate::DiscoveryPaths::new(tmp.path().to_path_buf()));
        let rt = ExtensionRuntime::new(config).unwrap();
        let err = rt.list_targets("does-not-exist").unwrap_err();
        match err {
            RuntimeError::NotFound(id) => assert_eq!(id, "does-not-exist"),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn credential_schema_returns_error_for_unknown_extension() {
        let tmp = tempfile::TempDir::new().unwrap();
        let config =
            RuntimeConfig::from_paths(crate::DiscoveryPaths::new(tmp.path().to_path_buf()));
        let rt = ExtensionRuntime::new(config).unwrap();
        let err = rt
            .credential_schema("does-not-exist", "some-target")
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[test]
    fn validate_credentials_returns_error_for_unknown_extension() {
        let tmp = tempfile::TempDir::new().unwrap();
        let config =
            RuntimeConfig::from_paths(crate::DiscoveryPaths::new(tmp.path().to_path_buf()));
        let rt = ExtensionRuntime::new(config).unwrap();
        let err = rt
            .validate_credentials("does-not-exist", "target", r"{}")
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[test]
    fn render_bundle_returns_error_for_unknown_extension() {
        let tmp = tempfile::TempDir::new().unwrap();
        let config =
            RuntimeConfig::from_paths(crate::DiscoveryPaths::new(tmp.path().to_path_buf()));
        let rt = ExtensionRuntime::new(config).unwrap();
        let err = rt
            .render_bundle(
                "does-not-exist",
                "standard",
                "{}",
                crate::types::BundleSession::default(),
            )
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[test]
    fn for_test_constructs_runtime_with_no_extensions() {
        let runtime = ExtensionRuntime::for_test();
        // No extensions are loaded.
        assert!(
            runtime.loaded().is_empty(),
            "for_test runtime must have zero loaded extensions"
        );
    }
}