apcore 0.18.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
// APCore Protocol — System modules registration
// Spec reference: Built-in system modules (F10, F11, F19)

pub mod control;
pub mod health;
pub mod manifest;
pub mod usage;

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

use parking_lot::RwLock;

use serde_json::json;
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 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 {
    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.
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;
    if let Err(e) = em.emit(&event).await {
        tracing::warn!(error = %e, event_type = %event_type, "Event emit failed");
    }
}

// ---------------------------------------------------------------------------
// 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,
}

// ---------------------------------------------------------------------------
// register_sys_modules
// ---------------------------------------------------------------------------

/// Register built-in system modules into the registry.
///
/// Workflow (per spec §9.15):
/// 1. Check `sys_modules.enabled` — return `None` if false.
/// 2. Create `ErrorHistory` + `ErrorHistoryMiddleware`, register on executor.
/// 3. Create `UsageCollector` + `UsageMiddleware`, register on executor.
/// 4. Register health, manifest, and usage modules (always).
/// 5. If `sys_modules.events.enabled`: register control modules + EventEmitter.
///
/// The registry is shared via `Arc<Registry>` — `Registry` provides interior
/// mutability, so no external `Mutex` wrapper is needed and this function is
/// fully synchronous and runtime-agnostic.
#[allow(clippy::too_many_lines)] // complex orchestration function; 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(
    registry: Arc<Registry>,
    executor: &Executor,
    config: &Config,
    metrics_collector: Option<MetricsCollector>,
) -> Option<SysModulesContext> {
    let enabled = config
        .get("sys_modules.enabled")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    if !enabled {
        return None;
    }

    // --- Step 2: ErrorHistory + middleware ---
    #[allow(clippy::cast_possible_truncation)] // config value won't exceed platform usize limits
    let max_per_module = 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 = 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());
    let _ = executor.use_middleware(Box::new(eh_middleware));

    // --- Step 3: UsageCollector + middleware ---
    let usage_collector = UsageCollector::new();
    let usage_middleware = UsageMiddleware::new(usage_collector.clone());
    let _ = executor.use_middleware(Box::new(usage_middleware));

    let config_arc = Arc::new(Mutex::new(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 = config
        .get("sys_modules.events.enabled")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    if events_enabled {
        // Instantiate subscribers from config while we still own `emitter`
        // directly — no lock required.
        if let Some(subs) = 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));
    let toggle_state = Arc::new(ToggleState::new());

    // --- 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 {
        // Step 5a: PlatformNotifyMiddleware (gets its own EventEmitter instance).
        let error_rate_threshold = config
            .get("sys_modules.events.thresholds.error_rate")
            .and_then(|v| v.as_f64())
            .unwrap_or(0.1);
        let latency_p99_threshold = 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,
        );
        let _ = executor.use_middleware(Box::new(pn_middleware));

        // Step 5c: Control modules
        modules.push((
            "system.control.update_config",
            Box::new(UpdateConfigModule::new(
                Arc::clone(&config_arc),
                Arc::clone(&emitter_arc),
            )),
            vec!["system".into(), "control".into()],
        ));
        modules.push((
            "system.control.reload_module",
            Box::new(ReloadModule::new(
                Arc::clone(&registry),
                Arc::clone(&emitter_arc),
            )),
            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),
            )),
            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 {
            name: id.to_string(),
            annotations: crate::module::ModuleAnnotations {
                requires_approval: is_control,
                readonly: !is_control,
                idempotent: !is_control,
                ..Default::default()
            },
            input_schema: module.input_schema(),
            output_schema: module.output_schema(),
            enabled: true,
            tags,
            dependencies: vec![],
        };
        let info = json!({
            "name": id,
            "description": module.description(),
        });
        match registry.register_internal(id, module, descriptor) {
            Ok(()) => {
                registered.insert(id.to_string(), info);
            }
            Err(e) => {
                tracing::warn!(module_id = %id, error = %e, "Failed to register sys module");
            }
        }
    }

    // Step 5d: Bridge registry events to tracing logs.
    if events_enabled {
        registry.on(
            "register",
            Box::new(move |module_id: &str, _module: &dyn Module| {
                tracing::info!(module_id = %module_id, "module_registered");
            }),
        );
        registry.on(
            "unregister",
            Box::new(move |module_id: &str, _module: &dyn Module| {
                tracing::info!(module_id = %module_id, "module_unregistered");
            }),
        );
    }

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