apcore 0.20.0

Schema-driven module standard for AI-perceivable interfaces
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
// APCore Protocol — System modules registration
// Spec reference: Built-in system modules (F10, F11, F19) +
//                 system-modules.md §1.1–§1.5 hardening (Issue #45).

pub mod audit;
pub mod control;
pub mod health;
pub mod manifest;
pub mod overrides;
pub mod usage;

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use parking_lot::RwLock;

use serde_json::json;
use thiserror::Error;
use tokio::sync::Mutex;

use crate::config::Config;
use crate::errors::{ErrorCode, ModuleError};
use crate::events::emitter::{ApCoreEvent, EventEmitter};
use crate::events::subscribers::create_subscriber;
use crate::executor::Executor;
use crate::middleware::PlatformNotifyMiddleware;
use crate::module::Module;
use crate::observability::error_history::{ErrorHistory, ErrorHistoryMiddleware};
use crate::observability::metrics::MetricsCollector;
use crate::observability::usage::{UsageCollector, UsageMiddleware};
use crate::registry::registry::{ModuleDescriptor, Registry};

pub use audit::{AuditAction, AuditChange, AuditEntry, AuditStore, InMemoryAuditStore};
pub use control::UpdateConfigModule;
pub(crate) use control::{ReloadModule, ToggleFeatureModule};

// ---------------------------------------------------------------------------
// ToggleState — thread-safe enable/disable tracking
// ---------------------------------------------------------------------------

/// Thread-safe set of disabled module IDs.
pub struct ToggleState {
    disabled: RwLock<HashSet<String>>,
}

impl ToggleState {
    #[must_use]
    pub fn new() -> Self {
        Self {
            disabled: RwLock::new(HashSet::new()),
        }
    }

    pub fn is_disabled(&self, module_id: &str) -> bool {
        self.disabled.read().contains(module_id)
    }

    pub fn disable(&self, module_id: &str) {
        self.disabled.write().insert(module_id.to_string());
    }

    pub fn enable(&self, module_id: &str) {
        self.disabled.write().remove(module_id);
    }

    pub fn clear(&self) {
        self.disabled.write().clear();
    }
}

impl Default for ToggleState {
    fn default() -> Self {
        Self::new()
    }
}

// Global default instance.
static GLOBAL_TOGGLE_STATE: OnceLock<ToggleState> = OnceLock::new();

fn global_toggle_state() -> &'static ToggleState {
    GLOBAL_TOGGLE_STATE.get_or_init(ToggleState::new)
}

/// Check if a module is disabled using the default global toggle state.
#[must_use]
pub fn is_module_disabled(module_id: &str) -> bool {
    global_toggle_state().is_disabled(module_id)
}

/// Return `Err(ModuleError)` with `ErrorCode::ModuleDisabled` if the module is disabled.
pub fn check_module_disabled(module_id: &str) -> Result<(), ModuleError> {
    if is_module_disabled(module_id) {
        return Err(ModuleError::new(
            ErrorCode::ModuleDisabled,
            format!("Module '{module_id}' is disabled"),
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Sensitive key detection
// ---------------------------------------------------------------------------

pub(crate) const SENSITIVE_SEGMENTS: &[&str] =
    &["token", "secret", "key", "password", "auth", "credential"];

pub(crate) fn is_sensitive_key(key: &str) -> bool {
    let lower = key.to_lowercase();
    // W-6: Match exact segments ("key") or underscore-compound segments ("api_key",
    // "auth_token") without false-positives on "keyboard" or "authentication".
    lower.split('.').any(|seg| {
        SENSITIVE_SEGMENTS.iter().any(|&s| {
            seg == s || seg.ends_with(&format!("_{s}")) || seg.starts_with(&format!("{s}_"))
        })
    })
}

// ---------------------------------------------------------------------------
// Restricted config keys
// ---------------------------------------------------------------------------

// W-7: Lists keys that must not be changed at runtime via update_config.
// Scope: runtime-safety critical keys only. Schema-level immutability is
// enforced at load time; this list protects against inadvertent runtime mutations.
pub(crate) const RESTRICTED_KEYS: &[&str] = &["sys_modules.enabled"];

// ---------------------------------------------------------------------------
// Shared helpers (used by control.rs)
// ---------------------------------------------------------------------------

pub(crate) fn require_string(
    inputs: &serde_json::Value,
    field: &str,
) -> Result<String, ModuleError> {
    inputs
        .get(field)
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(std::string::ToString::to_string)
        .ok_or_else(|| {
            ModuleError::new(
                ErrorCode::GeneralInvalidInput,
                format!("'{field}' is required and must be a non-empty string"),
            )
        })
}

pub(crate) fn missing_field_error(field: &str) -> ModuleError {
    ModuleError::new(
        ErrorCode::GeneralInvalidInput,
        format!("'{field}' is required"),
    )
}

/// Emit an event; errors are logged and not propagated (error isolation).
pub(crate) async fn emit_event(
    emitter: &Arc<Mutex<EventEmitter>>,
    event_type: &str,
    module_id: &str,
    timestamp: &str,
    data: serde_json::Value,
) {
    let event = ApCoreEvent {
        event_type: event_type.to_string(),
        timestamp: timestamp.to_string(),
        data,
        module_id: Some(module_id.to_string()),
        severity: "info".to_string(),
    };
    let em = emitter.lock().await;
    em.emit(&event).await;
}

/// Default `caller_id` when the `Context` has none (Issue #45.2 — contextual
/// auditing). Cross-language parity: `apcore-python` and `apcore-typescript`
/// both fall back to the literal `"@external"` string.
pub(crate) const DEFAULT_EXTERNAL_CALLER: &str = "@external";

/// Identity attribute names whose values are replaced with `<redacted>` in
/// audit-event payloads. Mirrors `apcore-python._IDENTITY_SENSITIVE_SUBSTRINGS`
/// (Issue #45.2). The list is intentionally a superset of the canonical
/// `obs.redaction.sensitive_keys` so bearer tokens, signed cookies, and
/// credentials can never leak through the contextual-audit channel even when
/// global redaction is disabled.
const IDENTITY_SENSITIVE_SUBSTRINGS: &[&str] = &[
    "token",
    "secret",
    "password",
    "passwd",
    "key",
    "auth",
    "credential",
    "cookie",
    "session",
    "bearer",
];

const IDENTITY_REDACTED_TOKEN: &str = "<redacted>";

fn redact_identity_attr(name: &str, value: &serde_json::Value) -> serde_json::Value {
    let lower = name.to_lowercase();
    if IDENTITY_SENSITIVE_SUBSTRINGS
        .iter()
        .any(|sub| lower.contains(sub))
    {
        return serde_json::Value::String(IDENTITY_REDACTED_TOKEN.to_string());
    }
    value.clone()
}

/// Augment an audit-event payload with caller identity extracted from the
/// `Context` (Issue #45.2). Adds:
///   * `caller_id` — taken from `ctx.caller_id`, defaulted to `"@external"`
///     when the context is unauthenticated or the field is empty.
///   * `identity` — a redaction-safe snapshot (`id`, `type`, optional `roles`,
///     plus any non-sensitive `attrs` entries verbatim; sensitive attrs are
///     replaced with `"<redacted>"`). Omitted entirely when `ctx.identity`
///     is `None`.
///   * `actor_id` / `actor_type` — flat aliases preserved for backward
///     compatibility with pre-D-31 consumers.
///
/// The `data` argument is mutated in place and returned for ergonomic chaining.
pub(crate) fn augment_with_context_identity(
    mut data: serde_json::Value,
    ctx: &crate::context::Context<serde_json::Value>,
) -> serde_json::Value {
    if let Some(obj) = data.as_object_mut() {
        let caller_id = ctx
            .caller_id
            .as_ref()
            .filter(|s| !s.is_empty())
            .cloned()
            .unwrap_or_else(|| DEFAULT_EXTERNAL_CALLER.to_string());
        obj.insert("caller_id".to_string(), serde_json::json!(caller_id));
        if let Some(identity) = ctx.identity.as_ref() {
            // Flat aliases (legacy).
            obj.insert("actor_id".to_string(), serde_json::json!(identity.id()));
            obj.insert(
                "actor_type".to_string(),
                serde_json::json!(identity.identity_type()),
            );

            // Canonical nested snapshot.
            let mut snapshot = serde_json::Map::new();
            snapshot.insert("id".to_string(), serde_json::json!(identity.id()));
            snapshot.insert(
                "type".to_string(),
                serde_json::json!(identity.identity_type()),
            );
            let roles = identity.roles();
            if !roles.is_empty() {
                snapshot.insert("roles".to_string(), serde_json::json!(roles));
            }
            for (key, value) in identity.attrs() {
                if matches!(key.as_str(), "id" | "type" | "roles") {
                    continue;
                }
                snapshot.insert(key.clone(), redact_identity_attr(key, value));
            }
            obj.insert("identity".to_string(), serde_json::Value::Object(snapshot));
        }
    }
    data
}

// ---------------------------------------------------------------------------
// SysModuleError — strict registration failure (Issue #45 §1.5)
// ---------------------------------------------------------------------------

/// Error type returned by `register_sys_modules`. The `RegistrationFailed`
/// variant carries the offending `module_id` so callers can route the failure
/// to module-specific recovery logic.
#[derive(Debug, Error)]
pub enum SysModuleError {
    #[error("system module '{module_id}' failed to register: {source}")]
    RegistrationFailed {
        module_id: String,
        #[source]
        source: ModuleError,
    },
}

impl SysModuleError {
    #[must_use]
    pub fn module_id(&self) -> &str {
        match self {
            Self::RegistrationFailed { module_id, .. } => module_id,
        }
    }

    #[must_use]
    pub fn error_code(&self) -> ErrorCode {
        ErrorCode::SysModuleRegistrationFailed
    }
}

// ---------------------------------------------------------------------------
// SysModulesContext — typed return value for register_sys_modules
// ---------------------------------------------------------------------------

/// Holds references to components created during sys-module registration.
pub struct SysModulesContext {
    pub registered_modules: HashMap<String, serde_json::Value>,
    pub emitter: Arc<Mutex<EventEmitter>>,
    pub toggle_state: Arc<ToggleState>,
    pub error_history: ErrorHistory,
    pub usage_collector: UsageCollector,
    pub audit_store: Option<Arc<dyn AuditStore>>,
}

// ---------------------------------------------------------------------------
// SysModulesOptions — optional inputs for hardening features (§1.1, §1.2, §1.5)
// ---------------------------------------------------------------------------

/// Optional knobs accepted by [`register_sys_modules_with_options`].
///
/// Defaults preserve pre-hardening behavior: no overrides file, no audit store,
/// `fail_on_error: false`. Cross-language: maps to the `audit_store`,
/// `overrides_path`, and `fail_on_error` parameters in the Python and
/// TypeScript SDKs.
#[derive(Default, Clone)]
pub struct SysModulesOptions {
    /// When set, runtime overrides are loaded from this YAML path on startup
    /// and persisted on every `update_config` / `toggle_feature` call. Use
    /// [`Self::overrides_store`] for non-file-backed persistence.
    pub overrides_path: Option<PathBuf>,
    /// Pluggable [`OverridesStore`] backend. When set, takes precedence over
    /// `overrides_path` and is wired into `UpdateConfigModule` /
    /// `ToggleFeatureModule` for read-modify-write persistence. Cross-language:
    /// matches the `overrides_store` parameter in `apcore-python` and
    /// `apcore-typescript`.
    ///
    /// [`OverridesStore`]: overrides::OverridesStore
    pub overrides_store: Option<Arc<dyn overrides::OverridesStore>>,
    /// When set, every state-changing control call appends an `AuditEntry`.
    /// When `None`, audit entries are logged at INFO level and discarded.
    pub audit_store: Option<Arc<dyn AuditStore>>,
    /// When `true`, any module-registration failure halts startup with an
    /// `Err(SysModuleError::RegistrationFailed)`. Default is `false`, which
    /// matches the lenient behavior of the Python/TypeScript SDKs.
    pub fail_on_error: bool,
}

// ---------------------------------------------------------------------------
// register_sys_modules — main entry, breaking change in 0.20.0 (§1.5)
// ---------------------------------------------------------------------------

/// Register built-in system modules into the registry.
///
/// **Breaking change in 0.20.0** (system-modules.md §1.5): the return type is
/// now `Result<SysModulesContext, SysModuleError>`. When `sys_modules.enabled`
/// is `false`, the function returns `Ok(SysModulesContext { … empty … })`
/// rather than `Option::None` so callers can always destructure the value.
///
/// For overrides persistence and audit trails, use
/// [`register_sys_modules_with_options`].
///
/// Workflow (per spec §9.15):
/// 1. Check `sys_modules.enabled` — return an empty `SysModulesContext` if `false`.
/// 2. Load `overrides_path` (if any) into the live `Config` after the base load.
/// 3. Create `ErrorHistory` + `ErrorHistoryMiddleware`.
/// 4. Create `UsageCollector` + `UsageMiddleware`.
/// 5. Register health, manifest, and usage modules.
/// 6. If `sys_modules.events.enabled`: register control modules + `EventEmitter`.
pub fn register_sys_modules(
    registry: Arc<Registry>,
    executor: &Executor,
    config: &Config,
    metrics_collector: Option<MetricsCollector>,
) -> Result<SysModulesContext, SysModuleError> {
    register_sys_modules_with_options(
        registry,
        executor,
        config,
        metrics_collector,
        SysModulesOptions::default(),
    )
}

/// Variant of [`register_sys_modules`] accepting hardening options. See
/// [`SysModulesOptions`] for details.
#[allow(clippy::too_many_lines)] // complex orchestration; extraction would obscure the registration flow
#[allow(clippy::needless_pass_by_value)] // public API: Arc<Registry> and Option<MetricsCollector> consumed by sub-modules
pub fn register_sys_modules_with_options(
    registry: Arc<Registry>,
    executor: &Executor,
    config: &Config,
    metrics_collector: Option<MetricsCollector>,
    options: SysModulesOptions,
) -> Result<SysModulesContext, SysModuleError> {
    let SysModulesOptions {
        overrides_path,
        overrides_store,
        audit_store,
        fail_on_error,
    } = options;

    let toggle_state = Arc::new(ToggleState::new());

    let enabled = config
        .get("sys_modules.enabled")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    if !enabled {
        return Ok(SysModulesContext {
            registered_modules: HashMap::new(),
            emitter: Arc::new(Mutex::new(EventEmitter::new())),
            toggle_state,
            error_history: ErrorHistory::with_limits(50, 1000),
            usage_collector: UsageCollector::new(),
            audit_store,
        });
    }

    // --- §1.1: load overrides into a mutable Config clone, then share it ---
    let mut effective_config = config.clone();
    if let Some(path) = overrides_path.as_deref() {
        overrides::load_overrides(path, &mut effective_config, Some(&toggle_state));
    }

    // --- Step 2: ErrorHistory + middleware ---
    #[allow(clippy::cast_possible_truncation)] // config value won't exceed platform usize limits
    let max_per_module = effective_config
        .get("sys_modules.error_history.max_entries_per_module")
        .and_then(|v| v.as_u64())
        .unwrap_or(50) as usize;
    #[allow(clippy::cast_possible_truncation)] // config value won't exceed platform usize limits
    let max_total = effective_config
        .get("sys_modules.error_history.max_total_entries")
        .and_then(|v| v.as_u64())
        .unwrap_or(1000) as usize;
    let error_history = ErrorHistory::with_limits(max_per_module, max_total);
    let eh_middleware = ErrorHistoryMiddleware::new(error_history.clone());
    if let Err(e) = executor.use_middleware(Box::new(eh_middleware)) {
        tracing::error!(error = %e, middleware = "ErrorHistoryMiddleware", "sys middleware registration failed");
    }

    // --- Step 3: UsageCollector + middleware ---
    let usage_collector = UsageCollector::new();
    let usage_middleware = UsageMiddleware::new(usage_collector.clone());
    if let Err(e) = executor.use_middleware(Box::new(usage_middleware)) {
        tracing::error!(error = %e, middleware = "UsageMiddleware", "sys middleware registration failed");
    }

    let config_arc = Arc::new(Mutex::new(effective_config.clone()));

    // Build the EventEmitter up-front as an owned value so we can populate
    // its subscribers from config synchronously, then wrap it in the Arc<Mutex<_>>
    // shared with sys modules.
    let mut emitter = EventEmitter::new();

    let events_enabled = effective_config
        .get("sys_modules.events.enabled")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // §1.1 + §1.2 wire `overrides_path` / `overrides_store` / `audit_store`
    // through the control modules — but control modules are only registered
    // when events are enabled. Surface a warning instead of silently dropping
    // the options so misconfiguration shows up at startup, not as missing
    // audit entries.
    if !events_enabled
        && (overrides_path.is_some() || overrides_store.is_some() || audit_store.is_some())
    {
        tracing::warn!(
            overrides_path_set = overrides_path.is_some(),
            overrides_store_set = overrides_store.is_some(),
            audit_store_set = audit_store.is_some(),
            "SysModulesOptions overrides/audit options set but \
             sys_modules.events.enabled=false — control modules are not \
             registered, so these options have no effect. Enable events to \
             activate runtime overrides and audit trails."
        );
    }

    if events_enabled {
        // Instantiate subscribers from config while we still own `emitter`
        // directly — no lock required.
        if let Some(subs) = effective_config.get("sys_modules.events.subscribers") {
            if let Some(arr) = subs.as_array() {
                for sub_config in arr {
                    match create_subscriber(sub_config) {
                        Ok(subscriber) => emitter.subscribe(subscriber),
                        Err(e) => {
                            tracing::warn!(error = %e, "Failed to create subscriber from config");
                        }
                    }
                }
            }
        }
    }

    let emitter_arc = Arc::new(Mutex::new(emitter));

    // --- Step 4: Build module list (health + manifest + usage always) ---
    let mut modules: Vec<(&str, Box<dyn Module>, Vec<String>)> = vec![
        (
            "system.health.summary",
            Box::new(health::HealthSummaryModule::new(
                Arc::clone(&registry),
                metrics_collector.clone(),
                error_history.clone(),
                Arc::clone(&config_arc),
            )),
            vec!["system".into(), "health".into()],
        ),
        (
            "system.health.module",
            Box::new(health::HealthModule::new(
                Arc::clone(&registry),
                metrics_collector.clone(),
                error_history.clone(),
            )),
            vec!["system".into(), "health".into()],
        ),
        (
            "system.manifest.module",
            Box::new(manifest::ManifestModule::new(
                Arc::clone(&registry),
                Arc::clone(&config_arc),
            )),
            vec!["system".into(), "manifest".into()],
        ),
        (
            "system.manifest.full",
            Box::new(manifest::ManifestFullModule::new(
                Arc::clone(&registry),
                Arc::clone(&config_arc),
            )),
            vec!["system".into(), "manifest".into()],
        ),
        (
            "system.usage.summary",
            Box::new(usage::UsageSummaryModule::new(usage_collector.clone())),
            vec!["system".into(), "usage".into()],
        ),
        (
            "system.usage.module",
            Box::new(usage::UsageModule::new(
                Arc::clone(&registry),
                usage_collector.clone(),
            )),
            vec!["system".into(), "usage".into()],
        ),
    ];

    // --- Step 5: Control modules only if events.enabled ---
    if events_enabled {
        let error_rate_threshold = effective_config
            .get("sys_modules.events.thresholds.error_rate")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.1);
        let latency_p99_threshold = effective_config
            .get("sys_modules.events.thresholds.latency_p99_ms")
            .and_then(|v| v.as_f64())
            .unwrap_or(5000.0);
        let pn_middleware = PlatformNotifyMiddleware::new(
            EventEmitter::new(),
            metrics_collector.clone(),
            error_rate_threshold,
            latency_p99_threshold,
        );
        if let Err(e) = executor.use_middleware(Box::new(pn_middleware)) {
            tracing::error!(error = %e, middleware = "PlatformNotifyMiddleware", "sys middleware registration failed");
        }

        modules.push((
            "system.control.update_config",
            Box::new(
                UpdateConfigModule::new(Arc::clone(&config_arc), Arc::clone(&emitter_arc))
                    .with_overrides_path(overrides_path.clone())
                    .with_overrides_store(overrides_store.clone())
                    .with_audit_store(audit_store.clone()),
            ),
            vec!["system".into(), "control".into()],
        ));
        modules.push((
            "system.control.reload_module",
            Box::new(
                ReloadModule::new(Arc::clone(&registry), Arc::clone(&emitter_arc))
                    .with_audit_store(audit_store.clone()),
            ),
            vec!["system".into(), "control".into()],
        ));
        modules.push((
            "system.control.toggle_feature",
            Box::new(
                ToggleFeatureModule::new(
                    Arc::clone(&registry),
                    Arc::clone(&emitter_arc),
                    Arc::clone(&toggle_state),
                )
                .with_overrides_path(overrides_path.clone())
                .with_overrides_store(overrides_store.clone())
                .with_audit_store(audit_store.clone()),
            ),
            vec!["system".into(), "control".into()],
        ));
    }

    // --- Register all modules ---
    let mut registered: HashMap<String, serde_json::Value> = HashMap::new();

    for (id, module, tags) in modules {
        let is_control = tags.contains(&"control".to_string());
        let descriptor = ModuleDescriptor {
            module_id: id.to_string(),
            name: None,
            description: module.description().to_string(),
            documentation: None,
            input_schema: module.input_schema(),
            output_schema: module.output_schema(),
            version: "1.0.0".to_string(),
            tags,
            annotations: Some(crate::module::ModuleAnnotations {
                requires_approval: is_control,
                readonly: !is_control,
                idempotent: !is_control,
                ..Default::default()
            }),
            examples: vec![],
            metadata: std::collections::HashMap::new(),
            display: None,
            sunset_date: None,
            dependencies: vec![],
            enabled: true,
        };
        let info = json!({
            "name": id,
            "description": module.description(),
        });
        match registry.register_internal(id, module, descriptor) {
            Ok(()) => {
                registered.insert(id.to_string(), info);
            }
            Err(e) => {
                if fail_on_error {
                    return Err(SysModuleError::RegistrationFailed {
                        module_id: id.to_string(),
                        source: e,
                    });
                }
                tracing::error!(module_id = %id, error = %e, "System module failed to register; continuing");
            }
        }
    }

    // Step 5d: Bridge registry events to ApCoreEvents (Issue #36).
    //
    // Each registry hook dual-emits the canonical
    // `apcore.registry.<event>` name AND the legacy bare-name event
    // (`module_registered`, `module_unregistered`) so existing subscribers
    // continue to fire while consumers migrate to the canonical names. The
    // legacy event payload includes `deprecated: true`.
    //
    // Registry callbacks are synchronous, so each hook spawns a task to
    // dispatch the async emit — fire-and-forget, error-isolated.
    if events_enabled {
        let emitter_for_register = Arc::clone(&emitter_arc);
        registry.on(
            "register",
            Box::new(move |module_id: &str, _module: &dyn Module| {
                tracing::info!(module_id = %module_id, "module_registered");
                let emitter = Arc::clone(&emitter_for_register);
                let module_id_owned = module_id.to_string();
                if let Ok(handle) = tokio::runtime::Handle::try_current() {
                    handle.spawn(async move {
                        let canonical = ApCoreEvent::with_module(
                            "apcore.registry.module_registered",
                            json!({}),
                            &module_id_owned,
                            "info",
                        );
                        let legacy = ApCoreEvent::with_module(
                            "module_registered",
                            json!({
                                "deprecated": true,
                                "canonical_event": "apcore.registry.module_registered",
                            }),
                            &module_id_owned,
                            "info",
                        );
                        let em = emitter.lock().await;
                        em.emit(&canonical).await;
                        em.emit(&legacy).await;
                    });
                }
            }),
        );
        let emitter_for_unregister = Arc::clone(&emitter_arc);
        registry.on(
            "unregister",
            Box::new(move |module_id: &str, _module: &dyn Module| {
                tracing::info!(module_id = %module_id, "module_unregistered");
                let emitter = Arc::clone(&emitter_for_unregister);
                let module_id_owned = module_id.to_string();
                if let Ok(handle) = tokio::runtime::Handle::try_current() {
                    handle.spawn(async move {
                        let canonical = ApCoreEvent::with_module(
                            "apcore.registry.module_unregistered",
                            json!({}),
                            &module_id_owned,
                            "info",
                        );
                        let legacy = ApCoreEvent::with_module(
                            "module_unregistered",
                            json!({
                                "deprecated": true,
                                "canonical_event": "apcore.registry.module_unregistered",
                            }),
                            &module_id_owned,
                            "info",
                        );
                        let em = emitter.lock().await;
                        em.emit(&canonical).await;
                        em.emit(&legacy).await;
                    });
                }
            }),
        );
    }

    Ok(SysModulesContext {
        registered_modules: registered,
        emitter: emitter_arc,
        toggle_state,
        error_history,
        usage_collector,
        audit_store,
    })
}