ao-core 0.1.0

Core traits and types for the ao-rs agent orchestrator framework
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
//! End-to-end integration test: lifecycle → reaction engine → notifier.
//!
//! Exercises the full notification pipeline using mock plugins and a
//! recording notifier. Proves that a status transition dispatches the
//! right reaction and the notifier registry delivers to the right
//! plugins.

use ao_core::{
    error::Result,
    events::OrchestratorEvent,
    lifecycle::LifecycleManager,
    notifier::{
        NotificationPayload, NotificationRouting, Notifier, NotifierError, NotifierRegistry,
    },
    reaction_engine::ReactionEngine,
    reactions::{EventPriority, ReactionAction, ReactionConfig},
    scm::{CiStatus, MergeReadiness, PrState, PullRequest, ReviewDecision},
    session_manager::SessionManager,
    traits::{Agent, Runtime, Scm},
    types::{ActivityState, Session, SessionId, SessionStatus},
};
use async_trait::async_trait;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

static DIR_COUNTER: AtomicUsize = AtomicUsize::new(0);

fn unique_temp_dir(label: &str) -> PathBuf {
    let n = DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    std::env::temp_dir().join(format!("ao-e2e-{label}-{nanos}-{n}"))
}

fn fake_session(short: &str, project: &str) -> Session {
    Session {
        id: SessionId(format!("{short}-0000-0000-0000-000000000000")),
        project_id: project.to_string(),
        status: SessionStatus::Working,
        agent: "claude-code".to_string(),
        agent_config: None,
        branch: format!("ao-{short}"),
        task: "test task".to_string(),
        workspace_path: Some(PathBuf::from("/tmp/fake-ws")),
        runtime_handle: Some(format!("tmux-{short}")),
        runtime: "tmux".into(),
        activity: Some(ActivityState::Ready),
        created_at: ao_core::now_ms(),
        cost: None,
        issue_id: None,
        issue_url: None,
        claimed_pr_number: None,
        claimed_pr_url: None,
        initial_prompt_override: None,
        spawned_by: None,
        last_merge_conflict_dispatched: None,
        last_review_backlog_fingerprint: None,
    }
}

fn fake_pr() -> PullRequest {
    PullRequest {
        number: 42,
        title: "fix tests".to_string(),
        branch: "ao-test".to_string(),
        base_branch: "main".to_string(),
        url: "https://github.com/test/test/pull/42".to_string(),
        owner: "test".to_string(),
        repo: "test".to_string(),
        is_draft: false,
    }
}

// ---------------------------------------------------------------------------
// Mock plugins
// ---------------------------------------------------------------------------

struct MockRuntime {
    alive: AtomicBool,
}

impl MockRuntime {
    fn new() -> Self {
        Self {
            alive: AtomicBool::new(true),
        }
    }
}

#[async_trait]
impl Runtime for MockRuntime {
    async fn create(
        &self,
        _id: &str,
        _cwd: &std::path::Path,
        _cmd: &str,
        _env: &[(String, String)],
    ) -> Result<String> {
        Ok("mock-handle".into())
    }
    async fn send_message(&self, _handle: &str, _msg: &str) -> Result<()> {
        Ok(())
    }
    async fn is_alive(&self, _handle: &str) -> Result<bool> {
        Ok(self.alive.load(Ordering::SeqCst))
    }
    async fn destroy(&self, _handle: &str) -> Result<()> {
        Ok(())
    }
}

struct MockAgent;

#[async_trait]
impl Agent for MockAgent {
    fn launch_command(&self, _s: &Session) -> String {
        "echo mock".into()
    }
    fn environment(&self, _s: &Session) -> Vec<(String, String)> {
        vec![]
    }
    fn initial_prompt(&self, _s: &Session) -> String {
        "mock prompt".into()
    }
    async fn detect_activity(&self, _s: &Session) -> Result<ActivityState> {
        Ok(ActivityState::Ready)
    }
}

struct MockScm {
    pr: Mutex<Option<PullRequest>>,
    ci: Mutex<CiStatus>,
}

impl MockScm {
    fn new() -> Self {
        Self {
            pr: Mutex::new(None),
            ci: Mutex::new(CiStatus::Passing),
        }
    }

    fn set_pr(&self, pr: Option<PullRequest>) {
        *self.pr.lock().unwrap() = pr;
    }

    fn set_ci(&self, ci: CiStatus) {
        *self.ci.lock().unwrap() = ci;
    }
}

#[async_trait]
impl Scm for MockScm {
    fn name(&self) -> &str {
        "mock-scm"
    }
    async fn detect_pr(&self, _s: &Session) -> Result<Option<PullRequest>> {
        Ok(self.pr.lock().unwrap().clone())
    }
    async fn pr_state(&self, _pr: &PullRequest) -> Result<PrState> {
        Ok(PrState::Open)
    }
    async fn ci_checks(&self, _pr: &PullRequest) -> Result<Vec<ao_core::scm::CheckRun>> {
        Ok(vec![])
    }
    async fn ci_status(&self, _pr: &PullRequest) -> Result<CiStatus> {
        Ok(*self.ci.lock().unwrap())
    }
    async fn reviews(&self, _pr: &PullRequest) -> Result<Vec<ao_core::scm::Review>> {
        Ok(vec![])
    }
    async fn review_decision(&self, _pr: &PullRequest) -> Result<ReviewDecision> {
        Ok(ReviewDecision::None)
    }
    async fn pending_comments(
        &self,
        _pr: &PullRequest,
    ) -> Result<Vec<ao_core::scm::ReviewComment>> {
        Ok(vec![])
    }
    async fn mergeability(&self, _pr: &PullRequest) -> Result<MergeReadiness> {
        Ok(MergeReadiness {
            mergeable: false,
            ci_passing: false,
            approved: false,
            no_conflicts: true,
            blockers: vec!["test".into()],
        })
    }
    async fn merge(
        &self,
        _pr: &PullRequest,
        _method: Option<ao_core::scm::MergeMethod>,
    ) -> Result<()> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Recording + failing notifiers
// ---------------------------------------------------------------------------

struct RecordingNotifier {
    name: String,
    payloads: Mutex<Vec<NotificationPayload>>,
}

impl RecordingNotifier {
    fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            payloads: Mutex::new(Vec::new()),
        }
    }

    fn recorded(&self) -> Vec<NotificationPayload> {
        self.payloads.lock().unwrap().clone()
    }
}

#[async_trait]
impl Notifier for RecordingNotifier {
    fn name(&self) -> &str {
        &self.name
    }
    async fn send(&self, payload: &NotificationPayload) -> std::result::Result<(), NotifierError> {
        self.payloads.lock().unwrap().push(payload.clone());
        Ok(())
    }
}

struct FailingNotifier;

#[async_trait]
impl Notifier for FailingNotifier {
    fn name(&self) -> &str {
        "fail"
    }
    async fn send(&self, _payload: &NotificationPayload) -> std::result::Result<(), NotifierError> {
        Err(NotifierError::Io("intentional test failure".into()))
    }
}

// ---------------------------------------------------------------------------
// Setup helper
// ---------------------------------------------------------------------------

struct TestHarness {
    lifecycle: LifecycleManager,
    sessions: Arc<SessionManager>,
    scm: Arc<MockScm>,
    recorder: Arc<RecordingNotifier>,
    extra_recorders: HashMap<String, Arc<RecordingNotifier>>,
    _base: PathBuf,
}

async fn setup(
    label: &str,
    reaction_config: HashMap<String, ReactionConfig>,
    routing: HashMap<EventPriority, Vec<String>>,
    extra_recorders: Vec<(String, Arc<RecordingNotifier>)>,
    extra_notifiers: Vec<(String, Arc<dyn Notifier>)>,
) -> TestHarness {
    let base = unique_temp_dir(label);
    std::fs::create_dir_all(base.join("sessions/test")).unwrap();

    let sessions = Arc::new(SessionManager::new(base.clone()));
    let runtime: Arc<dyn Runtime> = Arc::new(MockRuntime::new());
    let agent: Arc<dyn Agent> = Arc::new(MockAgent);
    let scm: Arc<MockScm> = Arc::new(MockScm::new());

    let lifecycle = LifecycleManager::new(sessions.clone(), runtime.clone(), agent);

    // Build notifier registry with routing and recorder.
    let mut registry = NotifierRegistry::new(NotificationRouting::from_map(routing));
    let recorder = Arc::new(RecordingNotifier::new("recorder"));
    registry.register("recorder", recorder.clone());
    let mut extra_recorder_map = HashMap::new();
    for (name, recorder) in extra_recorders {
        registry.register(&name, recorder.clone());
        extra_recorder_map.insert(name, recorder);
    }
    for (name, notifier) in extra_notifiers {
        registry.register(&name, notifier);
    }

    let engine = Arc::new(
        ReactionEngine::new(reaction_config, runtime, lifecycle.events_sender())
            .with_scm(scm.clone() as Arc<dyn Scm>)
            .with_notifier_registry(registry),
    );

    let lifecycle = lifecycle
        .with_reaction_engine(engine)
        .with_scm(scm.clone() as Arc<dyn Scm>);

    TestHarness {
        lifecycle,
        sessions,
        scm,
        recorder,
        extra_recorders: extra_recorder_map,
        _base: base,
    }
}

fn drain_events(
    rx: &mut tokio::sync::broadcast::Receiver<OrchestratorEvent>,
) -> Vec<OrchestratorEvent> {
    let mut events = Vec::new();
    while let Ok(e) = rx.try_recv() {
        events.push(e);
    }
    events
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Full chain: lifecycle tick → SCM detects CI failure → reaction engine
/// dispatches ci-failed → notifier registry resolves → recorder receives.
#[tokio::test]
async fn lifecycle_tick_triggers_notify_through_to_plugin() {
    let mut reactions = HashMap::new();
    reactions.insert(
        "ci-failed".to_string(),
        ReactionConfig {
            auto: true,
            action: ReactionAction::Notify,
            message: Some("CI broke, please fix".into()),
            priority: Some(EventPriority::Action),
            retries: None,
            escalate_after: None,
            threshold: None,
            include_summary: false,
            merge_method: None,
        },
    );

    let mut routing = HashMap::new();
    routing.insert(EventPriority::Action, vec!["recorder".to_string()]);

    let h = setup("notify-e2e", reactions, routing, vec![], vec![]).await;

    // Save a Working session, then set SCM to return a PR with failing CI.
    let session = fake_session("e2e1", "test");
    h.sessions.save(&session).await.unwrap();
    h.scm.set_pr(Some(fake_pr()));
    h.scm.set_ci(CiStatus::Failing);

    // Tick the lifecycle — should transition Working → CiFailed.
    let mut rx = h.lifecycle.subscribe();
    let mut seen = HashSet::new();
    h.lifecycle.tick(&mut seen).await.unwrap();

    // Verify the recorder received the notification.
    let recorded = h.recorder.recorded();
    assert_eq!(recorded.len(), 1, "expected exactly one notification");
    let p = &recorded[0];
    assert_eq!(p.reaction_key, "ci-failed");
    assert_eq!(p.priority, EventPriority::Action);
    assert_eq!(p.body, "CI broke, please fix");
    assert!(!p.escalated);
    assert_eq!(p.action, ReactionAction::Notify);

    // Verify events include StatusChanged and ReactionTriggered.
    let events = drain_events(&mut rx);
    assert!(
        events.iter().any(|e| matches!(
            e,
            OrchestratorEvent::StatusChanged {
                from: SessionStatus::Working,
                to: SessionStatus::CiFailed,
                ..
            }
        )),
        "expected StatusChanged Working→CiFailed"
    );
    assert!(
        events.iter().any(|e| matches!(
            e,
            OrchestratorEvent::ReactionTriggered {
                action: ReactionAction::Notify,
                ..
            }
        )),
        "expected ReactionTriggered with Notify"
    );
}

/// Escalation path: send-to-agent with retries=0 immediately escalates
/// on first attempt, falling through to dispatch_notify with escalated=true.
#[tokio::test]
async fn escalation_reaches_notifier_with_escalated_flag() {
    let mut reactions = HashMap::new();
    reactions.insert(
        "ci-failed".to_string(),
        ReactionConfig {
            auto: true,
            action: ReactionAction::SendToAgent,
            message: Some("fix CI".into()),
            priority: Some(EventPriority::Action),
            retries: Some(0),
            escalate_after: Some(ao_core::reactions::EscalateAfter::Attempts(0)),
            threshold: None,
            include_summary: false,
            merge_method: None,
        },
    );

    let mut routing = HashMap::new();
    routing.insert(EventPriority::Action, vec!["recorder".to_string()]);

    let h = setup("escalation-e2e", reactions, routing, vec![], vec![]).await;

    let session = fake_session("esc1", "test");
    h.sessions.save(&session).await.unwrap();
    h.scm.set_pr(Some(fake_pr()));
    h.scm.set_ci(CiStatus::Failing);

    let mut rx = h.lifecycle.subscribe();
    let mut seen = HashSet::new();
    h.lifecycle.tick(&mut seen).await.unwrap();

    // Verify the recorder received an escalated notification.
    let recorded = h.recorder.recorded();
    assert_eq!(
        recorded.len(),
        1,
        "expected exactly one escalated notification"
    );
    let p = &recorded[0];
    assert!(p.escalated, "expected escalated=true");
    assert_eq!(p.reaction_key, "ci-failed");

    // Verify ReactionEscalated event was emitted.
    let events = drain_events(&mut rx);
    assert!(
        events
            .iter()
            .any(|e| matches!(e, OrchestratorEvent::ReactionEscalated { .. })),
        "expected ReactionEscalated event"
    );
}

/// Partial failure: one notifier fails, the other still receives the payload.
/// The lifecycle tick completes normally (no crash from the failing plugin).
#[tokio::test]
async fn partial_failure_one_plugin_fails_others_succeed() {
    let mut reactions = HashMap::new();
    reactions.insert(
        "ci-failed".to_string(),
        ReactionConfig {
            auto: true,
            action: ReactionAction::Notify,
            message: Some("CI broke".into()),
            priority: Some(EventPriority::Action),
            retries: None,
            escalate_after: None,
            threshold: None,
            include_summary: false,
            merge_method: None,
        },
    );

    // Route to both recorder and fail.
    let mut routing = HashMap::new();
    routing.insert(
        EventPriority::Action,
        vec!["recorder".to_string(), "fail".to_string()],
    );

    let extra: Vec<(String, Arc<dyn Notifier>)> =
        vec![("fail".to_string(), Arc::new(FailingNotifier))];

    let h = setup("partial-e2e", reactions, routing, vec![], extra).await;

    let session = fake_session("pf1", "test");
    h.sessions.save(&session).await.unwrap();
    h.scm.set_pr(Some(fake_pr()));
    h.scm.set_ci(CiStatus::Failing);

    let mut seen = HashSet::new();
    // Tick should complete without panicking, even though FailingNotifier errors.
    h.lifecycle.tick(&mut seen).await.unwrap();

    // Recorder still received the notification despite the failing sibling.
    let recorded = h.recorder.recorded();
    assert_eq!(
        recorded.len(),
        1,
        "recorder should still receive notification"
    );
    assert_eq!(recorded[0].reaction_key, "ci-failed");
}

/// Fan-out: multiple notifiers at the same priority each receive the payload.
#[tokio::test]
async fn fan_out_multiple_notifiers_receive_payload() {
    let mut reactions = HashMap::new();
    reactions.insert(
        "ci-failed".to_string(),
        ReactionConfig {
            auto: true,
            action: ReactionAction::Notify,
            message: Some("CI broke".into()),
            priority: Some(EventPriority::Action),
            retries: None,
            escalate_after: None,
            threshold: None,
            include_summary: false,
            merge_method: None,
        },
    );

    let mut routing = HashMap::new();
    routing.insert(
        EventPriority::Action,
        vec!["recorder".to_string(), "recorder2".to_string()],
    );

    let recorder2 = Arc::new(RecordingNotifier::new("recorder2"));
    let h = setup(
        "fanout-e2e",
        reactions,
        routing,
        vec![("recorder2".to_string(), recorder2.clone())],
        vec![],
    )
    .await;

    let session = fake_session("fan1", "test");
    h.sessions.save(&session).await.unwrap();
    h.scm.set_pr(Some(fake_pr()));
    h.scm.set_ci(CiStatus::Failing);

    let mut seen = HashSet::new();
    h.lifecycle.tick(&mut seen).await.unwrap();

    let recorded1 = h.recorder.recorded();
    let recorded2 = h
        .extra_recorders
        .get("recorder2")
        .expect("recorder2 should be present")
        .recorded();

    assert_eq!(recorded1.len(), 1);
    assert_eq!(recorded2.len(), 1);
    assert_eq!(recorded1[0].reaction_key, "ci-failed");
    assert_eq!(recorded2[0].reaction_key, "ci-failed");
}

/// Unknown notifier names should be skipped (warn-once) and never crash routing.
#[tokio::test]
async fn unknown_notifier_name_is_skipped_and_does_not_crash() {
    let mut reactions = HashMap::new();
    reactions.insert(
        "ci-failed".to_string(),
        ReactionConfig {
            auto: true,
            action: ReactionAction::Notify,
            message: Some("CI broke".into()),
            priority: Some(EventPriority::Action),
            retries: None,
            escalate_after: None,
            threshold: None,
            include_summary: false,
            merge_method: None,
        },
    );

    let mut routing = HashMap::new();
    routing.insert(
        EventPriority::Action,
        vec!["recorder".to_string(), "typo-notifier".to_string()],
    );

    let h = setup("unknown-e2e", reactions, routing, vec![], vec![]).await;

    let session = fake_session("unk1", "test");
    h.sessions.save(&session).await.unwrap();
    h.scm.set_pr(Some(fake_pr()));
    h.scm.set_ci(CiStatus::Failing);

    let mut seen = HashSet::new();
    // Tick should complete without panicking even though one routing entry is unknown.
    h.lifecycle.tick(&mut seen).await.unwrap();

    let recorded = h.recorder.recorded();
    assert_eq!(recorded.len(), 1, "known notifier should still receive");
    assert_eq!(recorded[0].reaction_key, "ci-failed");
}