terraphim_orchestrator 1.20.2

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
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
//! Integration tests for ROC v1 Step F — verdict polling + AutoMerge enqueue.
//!
//! These tests exercise [`AgentOrchestrator::poll_pending_reviews_for_project`]
//! against an in-memory [`PrTracker`] (no mocks, no network, no Gitea). They
//! assert that the orchestrator enqueues [`DispatchTask::AutoMerge`] exactly
//! when every gate in [`AutoMergeCriteria::default`] is satisfied and never
//! more than once per `(project, pr_number, head_sha)` triple.
//!
//! See `cto-executive-system/plans/adf-rate-of-change-design.md` §Step F and
//! Gitea issue `terraphim/adf-fleet#34`.

use std::collections::HashMap;
use std::path::PathBuf;

use async_trait::async_trait;
use terraphim_orchestrator::pr_gate::{CommitStatusState, CommitStatusSummary};
use terraphim_orchestrator::pr_poller::{PrComment, PrSummary, PrTracker};
use terraphim_orchestrator::pr_review::AutoMergeCriteria;
use terraphim_orchestrator::{
    AgentOrchestrator, CompoundReviewConfig, DispatchTask, NightwatchConfig, OrchestratorConfig,
};

/// Test fixture bodies copied verbatim from the structural-pr-review skill.
const GO_5_5_CLEAN: &str = include_str!("fixtures/pr_review/go_5_5_clean.md");
const NOGO_2_5: &str = include_str!("fixtures/pr_review/nogo_2_5.md");
const MALFORMED_NO_CONFIDENCE: &str = include_str!("fixtures/pr_review/malformed_no_confidence.md");

/// Reviewer login emitted by the structural-pr-review skill.
const PR_REVIEWER: &str = "pr-reviewer";

/// Project id used throughout these tests. Any non-empty string works; we
/// pick a concrete value to make rate-limiter / dedupe scoping explicit.
const PROJECT: &str = "alpha";

/// Minimal [`OrchestratorConfig`] for the dispatcher-shaped tests below.
/// No agents, no trackers, no projects — the poller drives itself off the
/// in-memory `InMemoryPrTracker` passed directly into
/// `poll_pending_reviews_for_project`.
fn minimal_config(working_dir: PathBuf) -> OrchestratorConfig {
    let worktree_root = working_dir.join(".worktrees");
    OrchestratorConfig {
        project_sources: Vec::new(),
        working_dir,
        nightwatch: NightwatchConfig::default(),
        compound_review: CompoundReviewConfig {
            cli_tool: None,
            provider: None,
            model: None,
            schedule: "0 2 * * *".to_string(),
            max_duration_secs: 60,
            repo_path: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."),
            create_prs: false,
            worktree_root,
            base_branch: "main".to_string(),
            max_concurrent_agents: 1,
            ..Default::default()
        },
        workflow: None,
        agents: vec![],
        restart_cooldown_secs: 60,
        max_restart_count: 10,
        restart_budget_window_secs: 43_200,
        disk_usage_threshold: 100,
        tick_interval_secs: 30,
        handoff_buffer_ttl_secs: None,
        persona_data_dir: None,
        skill_data_dir: None,
        flows: vec![],
        flow_state_dir: None,
        gitea: None,
        mentions: None,
        webhook: None,
        role_config_path: None,
        routing: None,
        #[cfg(feature = "quickwit")]
        quickwit: None,
        projects: vec![],
        include: vec![],
        providers: vec![],
        provider_budget_state_file: None,
        pause_dir: None,
        project_circuit_breaker_threshold: 3,
        fleet_escalation_owner: None,
        fleet_escalation_repo: None,
        post_merge_gate: None,
        auto_merge: None,
        learning: terraphim_orchestrator::LearningConfig::default(),
        evolution: terraphim_orchestrator::EvolutionConfig::default(),
        pr_dispatch: None,
        pr_dispatch_per_project: Default::default(),
        gitea_skill_repo: None,
        direct_dispatch: None,
        gate_reconcile_interval_ticks: 20,
    }
}

/// In-memory [`PrTracker`] used by every test in this file. It holds a fixed
/// list of open PRs and a map of PR number -> comments. No mocks: the impl
/// is a plain struct doing plain lookups.
#[derive(Default)]
struct InMemoryPrTracker {
    prs: Vec<PrSummary>,
    comments_by_pr: HashMap<u64, Vec<PrComment>>,
    statuses_by_pr: HashMap<u64, Vec<CommitStatusSummary>>,
}

impl InMemoryPrTracker {
    fn new() -> Self {
        Self::default()
    }

    fn with_pr(mut self, pr: PrSummary, comments: Vec<PrComment>) -> Self {
        self.comments_by_pr.insert(pr.number, comments);
        self.prs.push(pr);
        self
    }

    /// Attach commit statuses to a PR keyed by PR number. The in-memory case
    /// keys on PR number (head SHA staleness is exercised separately by the
    /// structural footer check), so the supplied statuses are returned for any
    /// requested head SHA.
    fn with_statuses(mut self, pr_number: u64, statuses: &[(&str, CommitStatusState)]) -> Self {
        self.statuses_by_pr.insert(
            pr_number,
            statuses.iter().map(|(c, s)| status(c, *s)).collect(),
        );
        self
    }
}

#[async_trait]
impl PrTracker for InMemoryPrTracker {
    async fn list_open_prs(&self) -> Result<Vec<PrSummary>, String> {
        Ok(self.prs.clone())
    }

    async fn fetch_pr_comments(&self, pr_number: u64) -> Result<Vec<PrComment>, String> {
        Ok(self
            .comments_by_pr
            .get(&pr_number)
            .cloned()
            .unwrap_or_default())
    }

    async fn list_head_commit_statuses(
        &self,
        pr_number: u64,
        _head_sha: &str,
    ) -> Result<Vec<CommitStatusSummary>, String> {
        Ok(self
            .statuses_by_pr
            .get(&pr_number)
            .cloned()
            .unwrap_or_default())
    }
}

/// Build a single [`CommitStatusSummary`] with no timestamp (the verdict-poll
/// path classifies on missing/pending/fail, independent of timestamps).
fn status(ctx: &str, state: CommitStatusState) -> CommitStatusSummary {
    CommitStatusSummary {
        context: ctx.to_string(),
        state,
        created_at_unix: None,
    }
}

/// Build a [`PrSummary`] with sensible defaults. Tests override any field
/// they care about via struct update syntax.
fn pr_summary(number: u64, author: &str, head: &str, diff_loc: u32) -> PrSummary {
    PrSummary {
        number,
        author_login: author.to_string(),
        head_sha: head.to_string(),
        base_ref: "main".to_string(),
        diff_loc,
    }
}

fn reviewer_comment(id: u64, body: &str, updated_at: &str) -> PrComment {
    PrComment {
        id,
        user_login: PR_REVIEWER.to_string(),
        body: body.to_string(),
        updated_at: updated_at.to_string(),
    }
}

/// Helper: how many AutoMerge tasks are currently in the dispatcher queue?
fn auto_merge_depth(orch: &AgentOrchestrator) -> u64 {
    orch.dispatcher()
        .stats()
        .by_source
        .get("auto_merge")
        .copied()
        .unwrap_or(0)
}

// -------- Test 1: green review + all gates cleared -> enqueue AutoMerge --------

#[tokio::test]
async fn auto_merge_requires_all_gates() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(101, "claude-code", "2ef451d8", 42),
        vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
    );

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        1,
        "a clean 5/5 review with 0 P0/P1 and all acceptance criteria checked must enqueue AutoMerge"
    );

    let next = orch.dispatcher().peek().cloned();
    match next {
        Some(DispatchTask::AutoMerge {
            pr_number,
            project,
            head_sha,
        }) => {
            assert_eq!(pr_number, 101);
            assert_eq!(project, PROJECT);
            assert_eq!(head_sha, "2ef451d8");
        }
        other => panic!("expected DispatchTask::AutoMerge, got {:?}", other),
    }
}

// -------- Test 2: P1 finding present -> blocked --------

#[tokio::test]
async fn auto_merge_blocked_on_p1_present() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(202, "claude-code", "62672e38", 42),
        vec![reviewer_comment(2, NOGO_2_5, "2026-01-02T00:00:00Z")],
    );

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "a review with 2 P0 + 1 P1 findings must block AutoMerge even before other gates"
    );
}

// -------- Test 3: non-agent author -> blocked --------

#[tokio::test]
async fn auto_merge_blocked_on_non_agent_author() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    // Reuse the clean fixture but swap the author login to a human.
    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(303, "alice-human", "2ef451d8", 42),
        vec![reviewer_comment(3, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
    );

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "require_agent_author gate must block AutoMerge for human-authored PRs"
    );
}

// -------- Test 4: diff LoC over the cap -> blocked --------

#[tokio::test]
async fn auto_merge_blocked_on_large_diff() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    // 5/5 clean review, agent author, but diff_loc exceeds the 500 LoC cap.
    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(404, "claude-code", "2ef451d8", 501),
        vec![reviewer_comment(4, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
    );

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "max_diff_loc=500 must block AutoMerge for a 501-LoC diff"
    );
}

// -------- Test 5: idempotency across ticks --------

#[tokio::test]
async fn auto_merge_idempotent_across_ticks() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(505, "claude-code", "2ef451d8", 42),
        vec![reviewer_comment(5, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
    );

    // First tick enqueues exactly one AutoMerge task.
    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;
    assert_eq!(auto_merge_depth(&orch), 1, "first tick must enqueue");

    // Repeated polls for the same (pr_number, head_sha) within the same
    // orchestrator instance must never enqueue a duplicate. The rate
    // limiter and the dedupe set each enforce this separately; both paths
    // hold the observable invariant that the queue depth stays at 1.
    for _ in 0..5 {
        orch.poll_pending_reviews_for_project(
            PROJECT,
            &tracker,
            &AutoMergeCriteria::default(),
            &[],
        )
        .await;
    }
    assert_eq!(
        auto_merge_depth(&orch),
        1,
        "repeated polls over the same revision must never enqueue a duplicate AutoMerge"
    );
}

// -------- Test 6: PR with no reviewer comment -> skipped silently --------

#[tokio::test]
async fn poll_skips_prs_without_reviewer_comment() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    // One PR with a non-reviewer comment (human noise) and no reviewer
    // verdict yet. The poller should treat this as "no verdict, skip".
    let noise = PrComment {
        id: 9,
        user_login: "alice-human".to_string(),
        body: "looks good to me".to_string(),
        updated_at: "2026-01-02T00:00:00Z".to_string(),
    };
    let tracker = InMemoryPrTracker::new()
        .with_pr(pr_summary(606, "claude-code", "2ef451d8", 42), vec![noise]);

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "no reviewer comment means no verdict to act on; AutoMerge queue must be empty"
    );
}

// -------- Test 7: malformed verdict -> parse error, no enqueue, no panic --------

#[tokio::test]
async fn poll_handles_verdict_parse_error_gracefully() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(707, "claude-code", "6becb2f7", 42),
        vec![reviewer_comment(
            7,
            MALFORMED_NO_CONFIDENCE,
            "2026-01-02T00:00:00Z",
        )],
    );

    // This call must not panic and must not enqueue anything.
    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "malformed reviewer comment must be logged and skipped, never enqueued"
    );
}

// ===================================================================
// #2116: status-gate layer (required_merge_contexts)
// ===================================================================
//
// Every case below uses GO_5_5_CLEAN (a clean 5/5 structural verdict whose
// footer SHA is `2ef451d8`) authored by an agent, so the structural layer
// passes -- isolating the new status layer. The PR head is `2ef451d8` so the
// structural SHA-bind passes, except in the explicit stale-SHA case.

/// Empty `required_merge_contexts` => the status layer is a no-op and the
/// decision collapses to today's structural-only gate. Proves backward compat.
#[tokio::test]
async fn empty_required_contexts_preserves_today_behaviour() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new().with_pr(
        pr_summary(801, "claude-code", "2ef451d8", 42),
        vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
    );

    orch.poll_pending_reviews_for_project(PROJECT, &tracker, &AutoMergeCriteria::default(), &[])
        .await;

    assert_eq!(
        auto_merge_depth(&orch),
        1,
        "empty required-context set must behave exactly as today (structural verdict only)"
    );
}

/// One required context missing on the head => HumanReviewNeeded (depth 0).
#[tokio::test]
async fn one_required_context_missing_blocks() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new()
        .with_pr(
            pr_summary(802, "claude-code", "2ef451d8", 42),
            vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
        )
        .with_statuses(802, &[("adf/test", CommitStatusState::Success)]);

    let required = vec!["adf/test".to_string(), "adf/validation".to_string()];
    orch.poll_pending_reviews_for_project(
        PROJECT,
        &tracker,
        &AutoMergeCriteria::default(),
        &required,
    )
    .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "a missing required context (adf/validation) must block auto-merge"
    );
}

/// All required contexts `success` on the head => Merge (depth 1).
#[tokio::test]
async fn all_required_contexts_success_merges() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new()
        .with_pr(
            pr_summary(803, "claude-code", "2ef451d8", 42),
            vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
        )
        .with_statuses(
            803,
            &[
                ("adf/test", CommitStatusState::Success),
                ("adf/validation", CommitStatusState::Success),
                ("adf/verification", CommitStatusState::Success),
                ("adf/pr-reviewer", CommitStatusState::Success),
            ],
        );

    let required = vec![
        "adf/test".to_string(),
        "adf/validation".to_string(),
        "adf/verification".to_string(),
        "adf/pr-reviewer".to_string(),
    ];
    orch.poll_pending_reviews_for_project(
        PROJECT,
        &tracker,
        &AutoMergeCriteria::default(),
        &required,
    )
    .await;

    assert_eq!(
        auto_merge_depth(&orch),
        1,
        "all required contexts success on head + clean structural verdict must enqueue AutoMerge"
    );
}

/// All required contexts `success` BUT the structural verdict footer SHA does
/// not prefix-match the PR head => HumanReviewNeeded (stale review, depth 0).
#[tokio::test]
async fn success_on_stale_sha_blocks() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    // PR head is a DIFFERENT SHA than the verdict footer `2ef451d8`.
    let tracker = InMemoryPrTracker::new()
        .with_pr(
            pr_summary(804, "claude-code", "deadbeef99aa", 42),
            vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
        )
        .with_statuses(
            804,
            &[
                ("adf/test", CommitStatusState::Success),
                ("adf/validation", CommitStatusState::Success),
            ],
        );

    let required = vec!["adf/test".to_string(), "adf/validation".to_string()];
    orch.poll_pending_reviews_for_project(
        PROJECT,
        &tracker,
        &AutoMergeCriteria::default(),
        &required,
    )
    .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "structural verdict reviewed a stale SHA must block even when all statuses are green"
    );
}

/// A required context in `failure` state => HumanReviewNeeded (depth 0).
#[tokio::test]
async fn failed_required_context_blocks() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new()
        .with_pr(
            pr_summary(805, "claude-code", "2ef451d8", 42),
            vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
        )
        .with_statuses(
            805,
            &[
                ("adf/test", CommitStatusState::Success),
                ("adf/validation", CommitStatusState::Failure),
                ("adf/verification", CommitStatusState::Success),
            ],
        );

    let required = vec![
        "adf/test".to_string(),
        "adf/validation".to_string(),
        "adf/verification".to_string(),
    ];
    orch.poll_pending_reviews_for_project(
        PROJECT,
        &tracker,
        &AutoMergeCriteria::default(),
        &required,
    )
    .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "a failed required context (adf/validation) must block auto-merge"
    );
}

/// A required context still `pending` => HumanReviewNeeded (depth 0).
#[tokio::test]
async fn pending_required_context_blocks() {
    let mut orch =
        AgentOrchestrator::new(minimal_config(tempfile::tempdir().unwrap().keep())).unwrap();

    let tracker = InMemoryPrTracker::new()
        .with_pr(
            pr_summary(806, "claude-code", "2ef451d8", 42),
            vec![reviewer_comment(1, GO_5_5_CLEAN, "2026-01-02T00:00:00Z")],
        )
        .with_statuses(
            806,
            &[
                ("adf/test", CommitStatusState::Success),
                ("adf/verification", CommitStatusState::Pending),
            ],
        );

    let required = vec!["adf/test".to_string(), "adf/verification".to_string()];
    orch.poll_pending_reviews_for_project(
        PROJECT,
        &tracker,
        &AutoMergeCriteria::default(),
        &required,
    )
    .await;

    assert_eq!(
        auto_merge_depth(&orch),
        0,
        "a pending required context (adf/verification) must block auto-merge"
    );
}