apcore 0.22.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
// Built-in ACL condition handlers and handler trait.
//
// Defines the ACLConditionHandler trait, three basic handlers
// (identity_types, roles, max_call_depth), and two compound operators ($or, $not).

use async_trait::async_trait;
use parking_lot::RwLock;
use serde_json::Value;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};

use crate::context::Context;

// Per-call slot for the latest handler error message. Mirrors Python's
// `_handler_error_var` ContextVar and TypeScript's `_lastHandlerError`
// — a handler that detects an internal failure can record it here, and
// `ACL::build_audit_entry` reads it back when emitting the audit record.
//
// Python uses a single `contextvars.ContextVar` that works on both its sync
// and async `check()` paths. Rust has no single primitive with that property,
// so we keep TWO scopes that the read/write helpers consult transparently:
//
//   * `HANDLER_ERROR` — a tokio task-local, used by the async `async_check()`
//     path. Concurrent ACL evaluations on different tokio tasks cannot see
//     each other's errors.
//   * `HANDLER_ERROR_SYNC` — a thread-local, used by the synchronous `check()`
//     path (A-D-002). Tokio task-locals are unavailable on a purely
//     synchronous call, so the async-only scope left `handler_error` always
//     null on the sync path even when a condition handler reported an error.
//
// `report_handler_error` writes to whichever scope is active; `take_*` /
// `current_*` reads mirror that. A sync scope is only "active" inside
// `with_handler_error_capture_sync`, so a stray report outside any check is a
// no-op (matching the async task-local's behavior).
tokio::task_local! {
    pub(crate) static HANDLER_ERROR: RefCell<Option<String>>;
}

thread_local! {
    // `(active_depth, slot)`. The depth guards against a stray
    // `report_handler_error` leaking into an unrelated later read: writes and
    // reads only apply while a `with_handler_error_capture_sync` scope is open.
    static HANDLER_ERROR_SYNC: RefCell<(u32, Option<String>)> = const { RefCell::new((0, None)) };
}

/// Record a handler-evaluation error for the current ACL check.
///
/// Cross-language parity with apcore-python `_handler_error_var.set(...)` and
/// apcore-typescript `_lastHandlerError = ...`. Writes to the active async
/// task-local scope if one exists, otherwise to the active synchronous
/// thread-local scope. If called outside any active capture scope (i.e.
/// outside an ACL check entirely), the call is a no-op so handlers never panic
/// on a missing scope.
pub fn report_handler_error(message: impl Into<String>) {
    let msg = message.into();
    // Prefer the async task-local scope when present.
    if HANDLER_ERROR
        .try_with(|cell| {
            *cell.borrow_mut() = Some(msg.clone());
        })
        .is_ok()
    {
        return;
    }
    // Fall back to the synchronous thread-local scope, if one is active.
    HANDLER_ERROR_SYNC.with(|cell| {
        let mut state = cell.borrow_mut();
        if state.0 > 0 {
            state.1 = Some(msg);
        }
    });
}

/// Read the handler error recorded for the current ACL check, if any.
///
/// Checks the async task-local scope first, then the synchronous thread-local
/// scope. Returns `None` outside any active capture scope. Used by
/// `ACL::build_audit_entry` so a handler error populates the audit entry on
/// both the sync and async paths (A-D-002).
pub(crate) fn current_handler_error() -> Option<String> {
    if let Ok(v) = HANDLER_ERROR.try_with(|cell| cell.borrow().clone()) {
        if v.is_some() {
            return v;
        }
    }
    HANDLER_ERROR_SYNC.with(|cell| cell.borrow().1.clone())
}

/// Run an async evaluation under a fresh handler-error capture scope.
///
/// The scope's final `Option<String>` is returned alongside the evaluation
/// result so callers can attach it to an `AuditEntry`. Mirrors the Python
/// `with _handler_error_var.set(None)` context-manager pattern.
pub async fn with_handler_error_capture<F, T>(fut: F) -> (T, Option<String>)
where
    F: std::future::Future<Output = T>,
{
    let cell = RefCell::new(None);
    let result = HANDLER_ERROR.scope(cell, async move {
        let value = fut.await;
        let captured = HANDLER_ERROR.with(|c| c.borrow().clone());
        (value, captured)
    });
    result.await
}

/// Run a synchronous evaluation under a fresh handler-error capture scope.
///
/// Synchronous analogue of [`with_handler_error_capture`] for the sync
/// `ACL::check()` path (A-D-002). Opens a thread-local scope for the duration
/// of `f`, restoring the previous slot on exit so nested checks are isolated.
/// Mirrors Python's `_handler_error_var.set(None)` / `.reset(token)` pairing.
pub fn with_handler_error_capture_sync<F, T>(f: F) -> (T, Option<String>)
where
    F: FnOnce() -> T,
{
    // Open a fresh slot, saving the previous one so a nested check restores it.
    let previous = HANDLER_ERROR_SYNC.with(|cell| {
        let mut state = cell.borrow_mut();
        state.0 += 1;
        state.1.take()
    });

    let value = f();

    let captured = HANDLER_ERROR_SYNC.with(|cell| {
        let mut state = cell.borrow_mut();
        let captured = state.1.take();
        state.0 -= 1;
        // Restore the enclosing scope's slot (None at the outermost level).
        state.1 = previous;
        captured
    });

    (value, captured)
}

/// Extract a human-readable message from a panic payload.
///
/// Shared by the sync and async ACL condition-evaluation paths (A-D-011) so a
/// panicking custom handler produces a consistent `handler_error` string.
pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "<non-string panic payload>".to_string()
    }
}

/// Trait for evaluating a single ACL condition.
#[async_trait]
pub trait ACLConditionHandler: Send + Sync {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool;
}

/// Global registry of condition handlers (sync entry point — consulted by
/// `ACL::check` and as the fallback for `async_check`).
pub static CONDITION_HANDLERS: LazyLock<RwLock<HashMap<String, Arc<dyn ACLConditionHandler>>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

/// Separate registry for handlers explicitly registered as async-only via
/// `ACL::register_async_condition`. `async_check` consults this map first
/// and falls back to [`CONDITION_HANDLERS`] when no async-specific handler
/// is registered for a key. Mirrors apcore-python `_async_condition_handlers`
/// and apcore-typescript `_asyncConditionHandlers` (closes A-D-ACL-002).
pub static ASYNC_CONDITION_HANDLERS: LazyLock<
    RwLock<HashMap<String, Arc<dyn ACLConditionHandler>>>,
> = LazyLock::new(|| RwLock::new(HashMap::new()));

/// Register a condition handler globally. Replaces any existing handler for the same key.
///
/// See also [`ACL::register_condition`](crate::ACL::register_condition) for the convenience
/// static method on the ACL type, which delegates here.
pub fn register_condition(key: impl Into<String>, handler: Arc<dyn ACLConditionHandler>) {
    let mut map = CONDITION_HANDLERS.write();
    map.insert(key.into(), handler);
}

/// Register an async-only condition handler.
///
/// Handlers registered here are consulted by [`evaluate_conditions_async`]
/// *before* the sync registry, allowing async-only logic to override a sync
/// handler with the same key without affecting the sync `ACL::check` path.
/// Cross-language parity with apcore-python `register_async_condition` and
/// apcore-typescript `registerAsyncCondition` (closes A-D-ACL-002).
pub fn register_async_condition(key: impl Into<String>, handler: Arc<dyn ACLConditionHandler>) {
    let mut map = ASYNC_CONDITION_HANDLERS.write();
    map.insert(key.into(), handler);
}

// ---------------------------------------------------------------------------
// Free async evaluator (used by compound operators and re-exported to ACL)
// ---------------------------------------------------------------------------

/// Evaluate all conditions with AND logic using the handler registry.
///
/// Resolves each condition key by consulting [`ASYNC_CONDITION_HANDLERS`]
/// first (async-only overrides), then falling back to [`CONDITION_HANDLERS`]
/// (the sync registry). Unknown keys are treated as unsatisfied
/// (fail-closed). Handlers are cloned out of the registries before any
/// `.await` so no `parking_lot` read guard is held across await points.
pub async fn evaluate_conditions_async<S: ::std::hash::BuildHasher>(
    conditions: &HashMap<String, Value, S>,
    ctx: &Context<Value>,
) -> bool {
    let mut to_evaluate: Vec<(String, Arc<dyn ACLConditionHandler>, Value)> =
        Vec::with_capacity(conditions.len());
    {
        let async_handlers = ASYNC_CONDITION_HANDLERS.read();
        let sync_handlers = CONDITION_HANDLERS.read();
        for (key, value) in conditions {
            let handler = if let Some(h) = async_handlers.get(key.as_str()) {
                h.clone()
            } else if let Some(h) = sync_handlers.get(key.as_str()) {
                h.clone()
            } else {
                tracing::warn!("Unknown ACL condition '{}' — treated as unsatisfied", key);
                return false;
            };
            to_evaluate.push((key.clone(), handler, value.clone()));
        }
    }
    for (key, handler, value) in &to_evaluate {
        // A-D-011 (SECURITY): a panicking custom handler must NOT unwind out of
        // the ACL gate. Catch the panic, record it as a handler error, and fail
        // closed (deny). Mirrors Python `try/except` and TypeScript `try/catch`
        // around handler.evaluate.
        use futures_util::FutureExt;
        let fut = std::panic::AssertUnwindSafe(handler.evaluate(value, ctx)).catch_unwind();
        match fut.await {
            Ok(true) => {}
            Ok(false) => return false,
            Err(payload) => {
                let msg = panic_message(payload.as_ref());
                tracing::error!(
                    condition = %key,
                    panic = %msg,
                    "ACL condition handler panicked — denying (fail-closed)"
                );
                report_handler_error(format!("{key}: handler panicked: {msg}"));
                return false;
            }
        }
    }
    true
}

// ---------------------------------------------------------------------------
// Basic handlers
// ---------------------------------------------------------------------------

/// Check context.identity.type is in the allowed list.
pub struct IdentityTypesHandler;

#[async_trait]
impl ACLConditionHandler for IdentityTypesHandler {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool {
        let Some(arr) = value.as_array() else {
            return false;
        };
        let Some(identity) = &ctx.identity else {
            return false;
        };
        arr.iter()
            .any(|v| v.as_str().is_some_and(|s| s == identity.identity_type()))
    }
}

/// Check at least one role overlaps between identity and required roles.
pub struct RolesHandler;

#[async_trait]
impl ACLConditionHandler for RolesHandler {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool {
        let Some(arr) = value.as_array() else {
            return false;
        };
        let Some(identity) = &ctx.identity else {
            return false;
        };
        arr.iter().any(|v| {
            v.as_str()
                .is_some_and(|s| identity.roles().contains(&s.to_string()))
        })
    }
}

/// Check call chain length does not exceed threshold.
///
/// Accepts both the bare-integer form `max_call_depth: 5` and the dict form
/// `max_call_depth: { lte: 5 }`, mirroring apcore-python and apcore-typescript
/// (sync finding A-D-024). Other forms are rejected (fail-closed) per spec.
pub struct MaxCallDepthHandler;

#[async_trait]
impl ACLConditionHandler for MaxCallDepthHandler {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool {
        let threshold = match value {
            Value::Number(n) => n.as_u64(),
            Value::Object(map) => map.get("lte").and_then(serde_json::Value::as_u64),
            _ => None,
        };
        match threshold {
            Some(max) => (ctx.call_chain.len() as u64) <= max,
            None => false,
        }
    }
}

// ---------------------------------------------------------------------------
// Compound handlers
// ---------------------------------------------------------------------------

/// $or: list of condition dicts. Returns true if ANY sub-set passes.
/// Delegates to `evaluate_conditions_async` so async handlers in sub-conditions
/// are fully awaited (fixes the prior sync-path footgun).
pub(crate) struct OrHandler;

impl OrHandler {
    pub(crate) fn new() -> Self {
        Self
    }
}

#[async_trait]
impl ACLConditionHandler for OrHandler {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool {
        let Some(arr) = value.as_array() else {
            return false;
        };
        for sub in arr {
            if let Some(obj) = sub.as_object() {
                let map: HashMap<String, Value> =
                    obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                if evaluate_conditions_async(&map, ctx).await {
                    return true;
                }
            }
        }
        false
    }
}

/// $not: single condition dict. Returns true if the sub-set FAILS.
/// Delegates to `evaluate_conditions_async` for the same reason as `OrHandler`.
pub(crate) struct NotHandler;

impl NotHandler {
    pub(crate) fn new() -> Self {
        Self
    }
}

#[async_trait]
impl ACLConditionHandler for NotHandler {
    async fn evaluate(&self, value: &Value, ctx: &Context<Value>) -> bool {
        match value.as_object() {
            Some(obj) => {
                let map: HashMap<String, Value> =
                    obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                !evaluate_conditions_async(&map, ctx).await
            }
            None => false,
        }
    }
}

/// Register all built-in handlers. Called once during initialization.
pub fn register_builtin_handlers() {
    register_condition("identity_types", Arc::new(IdentityTypesHandler));
    register_condition("roles", Arc::new(RolesHandler));
    register_condition("max_call_depth", Arc::new(MaxCallDepthHandler));
    register_condition("$or", Arc::new(OrHandler::new()));
    register_condition("$not", Arc::new(NotHandler::new()));
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::{Context, Identity};

    fn make_ctx(identity_type: &str, roles: Vec<&str>, call_depth: usize) -> Context<Value> {
        let identity = Identity::new(
            "test-id".to_string(),
            identity_type.to_string(),
            roles.into_iter().map(String::from).collect(),
            HashMap::new(),
        );
        let mut ctx = Context::new(identity);
        for i in 0..call_depth {
            ctx.call_chain.push(format!("module.{i}"));
        }
        ctx
    }

    fn anon_ctx() -> Context<Value> {
        Context::<Value>::anonymous()
    }

    // -------------------------------------------------------------------------
    // IdentityTypesHandler
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn identity_types_matches_correct_type() {
        let handler = IdentityTypesHandler;
        let ctx = make_ctx("user", vec![], 0);
        let value = serde_json::json!(["user", "service"]);
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn identity_types_rejects_wrong_type() {
        let handler = IdentityTypesHandler;
        let ctx = make_ctx("agent", vec![], 0);
        let value = serde_json::json!(["user", "service"]);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn identity_types_rejects_non_array_value() {
        let handler = IdentityTypesHandler;
        let ctx = make_ctx("user", vec![], 0);
        let value = serde_json::json!("user"); // not an array
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn identity_types_rejects_no_identity() {
        let handler = IdentityTypesHandler;
        let ctx = anon_ctx();
        let value = serde_json::json!(["user"]);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // RolesHandler
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn roles_matches_overlapping_role() {
        let handler = RolesHandler;
        let ctx = make_ctx("user", vec!["admin", "viewer"], 0);
        let value = serde_json::json!(["admin"]);
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn roles_rejects_no_overlap() {
        let handler = RolesHandler;
        let ctx = make_ctx("user", vec!["viewer"], 0);
        let value = serde_json::json!(["admin"]);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn roles_rejects_no_identity() {
        let handler = RolesHandler;
        let ctx = anon_ctx();
        let value = serde_json::json!(["admin"]);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // MaxCallDepthHandler
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn max_call_depth_allows_under_limit() {
        let handler = MaxCallDepthHandler;
        let ctx = make_ctx("user", vec![], 3);
        let value = serde_json::json!(5u64);
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn max_call_depth_allows_at_limit() {
        let handler = MaxCallDepthHandler;
        let ctx = make_ctx("user", vec![], 5);
        let value = serde_json::json!(5u64);
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn max_call_depth_rejects_over_limit() {
        let handler = MaxCallDepthHandler;
        let ctx = make_ctx("user", vec![], 6);
        let value = serde_json::json!(5u64);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn max_call_depth_rejects_non_numeric_value() {
        let handler = MaxCallDepthHandler;
        let ctx = make_ctx("user", vec![], 0);
        let value = serde_json::json!("five"); // not a number
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // OrHandler
    // -------------------------------------------------------------------------

    /// Simple async handler for compound-operator tests: checks `{"pass": true}`.
    struct PassHandler;

    #[async_trait]
    impl ACLConditionHandler for PassHandler {
        async fn evaluate(&self, value: &Value, _ctx: &Context<Value>) -> bool {
            value.as_bool().unwrap_or(false)
        }
    }

    /// Register "pass" handler and ensure built-ins are present before compound tests.
    fn setup_compound_test_handlers() {
        register_condition("pass", Arc::new(PassHandler));
        // Ensure the OrHandler / NotHandler themselves are registered so nested
        // compound operators work in the integration tests below.
        register_builtin_handlers();
    }

    #[tokio::test]
    async fn or_handler_true_if_any_sub_passes() {
        setup_compound_test_handlers();
        let handler = OrHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!([
            {"pass": false},
            {"pass": true},
        ]);
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn or_handler_false_if_none_pass() {
        setup_compound_test_handlers();
        let handler = OrHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!([
            {"pass": false},
            {"pass": false},
        ]);
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn or_handler_rejects_non_array_value() {
        let handler = OrHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!({"pass": true}); // not an array
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // NotHandler
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn not_handler_inverts_passing_condition() {
        setup_compound_test_handlers();
        let handler = NotHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!({"pass": true});
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn not_handler_inverts_failing_condition() {
        setup_compound_test_handlers();
        let handler = NotHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!({"pass": false});
        assert!(handler.evaluate(&value, &ctx).await);
    }

    #[tokio::test]
    async fn not_handler_rejects_non_object_value() {
        let handler = NotHandler::new();
        let ctx = anon_ctx();
        let value = serde_json::json!([{"pass": true}]); // not an object
        assert!(!handler.evaluate(&value, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // register_condition
    // -------------------------------------------------------------------------

    #[test]
    fn register_condition_stores_and_overwrites() {
        register_condition("_test_handler", Arc::new(MaxCallDepthHandler));
        // Overwrite — should not panic
        register_condition("_test_handler", Arc::new(MaxCallDepthHandler));
        let map = CONDITION_HANDLERS.read();
        assert!(map.contains_key("_test_handler"));
    }

    // -------------------------------------------------------------------------
    // register_async_condition — separate registry from sync (A-D-ACL-002)
    // -------------------------------------------------------------------------

    /// Async-only handler that always returns true.
    struct AsyncOnlyTrue;

    #[async_trait]
    impl ACLConditionHandler for AsyncOnlyTrue {
        async fn evaluate(&self, _value: &Value, _ctx: &Context<Value>) -> bool {
            true
        }
    }

    #[tokio::test]
    async fn register_async_condition_uses_separate_registry() {
        // Register the same key in both registries with opposite outcomes —
        // the async path MUST consult the async registry first.
        struct SyncDeny;
        #[async_trait]
        impl ACLConditionHandler for SyncDeny {
            async fn evaluate(&self, _value: &Value, _ctx: &Context<Value>) -> bool {
                false
            }
        }

        let key = "_test_async_vs_sync";
        register_condition(key, Arc::new(SyncDeny));
        register_async_condition(key, Arc::new(AsyncOnlyTrue));

        // Async path resolves the async-only handler → true.
        let mut conditions: HashMap<String, Value> = HashMap::new();
        conditions.insert(key.to_string(), Value::Null);
        let ctx = anon_ctx();
        assert!(evaluate_conditions_async(&conditions, &ctx).await);

        // Sync registry still contains the deny handler.
        let sync_map = CONDITION_HANDLERS.read();
        assert!(sync_map.contains_key(key));
        let async_map = ASYNC_CONDITION_HANDLERS.read();
        assert!(async_map.contains_key(key));
    }

    #[tokio::test]
    async fn async_check_falls_back_to_sync_registry_when_no_async_handler() {
        // Only register on the sync side — async evaluation MUST still find it.
        let key = "_test_async_fallback";
        register_condition(key, Arc::new(AsyncOnlyTrue));

        let mut conditions: HashMap<String, Value> = HashMap::new();
        conditions.insert(key.to_string(), Value::Null);
        let ctx = anon_ctx();
        assert!(evaluate_conditions_async(&conditions, &ctx).await);
    }

    // -------------------------------------------------------------------------
    // handler_error capture (A-D-ACL-001)
    // -------------------------------------------------------------------------

    #[tokio::test]
    async fn handler_error_capture_returns_reported_message() {
        let (decision, captured) = with_handler_error_capture(async {
            report_handler_error("simulated handler failure");
            false
        })
        .await;
        assert!(!decision);
        assert_eq!(captured.as_deref(), Some("simulated handler failure"));
    }

    #[tokio::test]
    async fn handler_error_capture_isolates_per_scope() {
        // Two independent scopes must not see each other's errors.
        let ((), first) = with_handler_error_capture(async {
            report_handler_error("first call");
        })
        .await;
        let ((), second) = with_handler_error_capture(async {
            // No report inside this scope.
        })
        .await;
        assert_eq!(first.as_deref(), Some("first call"));
        assert!(second.is_none());
    }

    #[test]
    fn report_handler_error_outside_scope_is_noop() {
        // Calling outside an active capture scope must not panic — it falls
        // through silently because the task-local has no slot.
        report_handler_error("dropped on the floor");
    }
}