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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! Task Orchestrator - Bridges TaskManager and AgentPool
//!
//! [`TaskOrchestrator`] runs a scheduling loop that queries ready tasks from the
//! dependency graph, spawns agents via the pool, and feeds results back into the
//! task manager. This provides centralized status tracking with concurrent agent
//! execution and dependency-aware ordering.
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use tokio::sync::RwLock;
use brainwires_core::{Task, TaskPriority, TaskStatus};
use crate::communication::{AgentMessage, CommunicationHub};
use crate::pool::AgentPool;
use crate::task_agent::{TaskAgentConfig, TaskAgentResult};
use crate::task_manager::TaskManager;
use crate::task_manager::TaskStats;
const DEFAULT_POLL_INTERVAL_MS: u64 = 250;
// ── Public types ────────────────────────────────────────────────────────────
/// What happens when an agent's task fails.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum FailurePolicy {
/// Stop scheduling new tasks and drain running agents (default).
#[default]
StopOnFirstFailure,
/// Keep scheduling independent tasks that aren't blocked by the failure.
ContinueOnFailure,
}
/// Configuration for the orchestration loop.
#[derive(Debug, Clone)]
pub struct TaskOrchestratorConfig {
/// Behaviour on agent failure.
pub failure_policy: FailurePolicy,
/// Default agent config used when no per-task override exists.
pub default_agent_config: TaskAgentConfig,
/// Polling interval in milliseconds. Default: 250.
pub poll_interval_ms: u64,
/// Identifier used in CommunicationHub messages.
pub orchestrator_id: String,
}
impl Default for TaskOrchestratorConfig {
fn default() -> Self {
Self {
failure_policy: FailurePolicy::default(),
default_agent_config: TaskAgentConfig::default(),
poll_interval_ms: DEFAULT_POLL_INTERVAL_MS,
orchestrator_id: "orchestrator".to_string(),
}
}
}
/// Specification for creating a task via the convenience API.
#[derive(Debug, Clone)]
pub struct TaskSpec {
/// Task description.
pub description: String,
/// Task priority.
pub priority: TaskPriority,
/// Indices into the spec list that this task depends on.
pub depends_on_indices: Vec<usize>,
/// Per-task agent config override (falls back to default).
pub agent_config: Option<TaskAgentConfig>,
}
/// Result of a complete orchestration run.
#[derive(Debug)]
pub struct OrchestrationResult {
/// `true` when every task succeeded.
pub all_succeeded: bool,
/// Per-task agent results keyed by task ID.
pub task_results: HashMap<String, TaskAgentResult>,
/// Task IDs that were never started (e.g. blocked by a failure).
pub unstarted_tasks: Vec<String>,
/// Final task statistics snapshot.
pub stats: TaskStats,
}
// ── TaskOrchestrator ────────────────────────────────────────────────────────
/// Bridges [`TaskManager`] and [`AgentPool`] with a dependency-aware
/// scheduling loop.
pub struct TaskOrchestrator {
task_manager: Arc<TaskManager>,
agent_pool: Arc<AgentPool>,
communication_hub: Arc<CommunicationHub>,
config: TaskOrchestratorConfig,
/// Per-task agent config overrides.
per_task_configs: Arc<RwLock<HashMap<String, TaskAgentConfig>>>,
/// Maps agent_id -> task_id for running agents.
agent_to_task: Arc<RwLock<HashMap<String, String>>>,
/// Abort flag — set by `abort()`.
aborted: Arc<tokio::sync::Notify>,
abort_flag: Arc<std::sync::atomic::AtomicBool>,
}
impl TaskOrchestrator {
/// Create a new orchestrator.
pub fn new(
task_manager: Arc<TaskManager>,
agent_pool: Arc<AgentPool>,
communication_hub: Arc<CommunicationHub>,
config: TaskOrchestratorConfig,
) -> Self {
Self {
task_manager,
agent_pool,
communication_hub,
config,
per_task_configs: Arc::new(RwLock::new(HashMap::new())),
agent_to_task: Arc::new(RwLock::new(HashMap::new())),
aborted: Arc::new(tokio::sync::Notify::new()),
abort_flag: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}
/// Set a per-task agent config override.
pub async fn set_task_config(&self, task_id: impl Into<String>, config: TaskAgentConfig) {
self.per_task_configs
.write()
.await
.insert(task_id.into(), config);
}
/// Bulk-set per-task agent config overrides.
pub async fn set_task_configs(&self, configs: HashMap<String, TaskAgentConfig>) {
let mut map = self.per_task_configs.write().await;
map.extend(configs);
}
/// Convenience API: create tasks with dependencies in the TaskManager,
/// then run the scheduling loop.
///
/// `parent_task_id` is an optional root task under which all specs are
/// created as subtasks.
pub async fn create_and_run(
&self,
parent_task_id: Option<&str>,
specs: Vec<TaskSpec>,
) -> Result<OrchestrationResult> {
// Create tasks and collect their IDs (index-ordered).
let mut task_ids: Vec<String> = Vec::with_capacity(specs.len());
for spec in &specs {
let id = self
.task_manager
.create_task(
spec.description.clone(),
parent_task_id.map(|s| s.to_string()),
spec.priority,
)
.await?;
task_ids.push(id);
}
// Wire up dependencies by index.
for (i, spec) in specs.iter().enumerate() {
for &dep_idx in &spec.depends_on_indices {
if dep_idx >= task_ids.len() {
return Err(anyhow!(
"TaskSpec[{}] depends_on_indices contains out-of-range index {}",
i,
dep_idx
));
}
self.task_manager
.add_dependency(&task_ids[i], &task_ids[dep_idx])
.await?;
}
// Store per-task config overrides.
if let Some(ref cfg) = spec.agent_config {
self.set_task_config(&task_ids[i], cfg.clone()).await;
}
}
// Determine root: either explicit parent or the first created task.
let root = parent_task_id
.map(|s| s.to_string())
.or_else(|| task_ids.first().cloned());
match root {
Some(id) => self.run(&id).await,
None => {
// Empty spec list — nothing to do.
Ok(OrchestrationResult {
all_succeeded: true,
task_results: HashMap::new(),
unstarted_tasks: Vec::new(),
stats: self.task_manager.get_stats().await,
})
}
}
}
/// Main scheduling loop over existing tasks in the TaskManager.
///
/// Runs until all tasks reachable from `root_task_id` are completed/failed
/// or the failure policy halts scheduling.
pub async fn run(&self, root_task_id: &str) -> Result<OrchestrationResult> {
let mut task_results: HashMap<String, TaskAgentResult> = HashMap::new();
let mut halted = false;
let poll = tokio::time::Duration::from_millis(self.config.poll_interval_ms);
loop {
// Check abort flag.
if self.abort_flag.load(std::sync::atomic::Ordering::Relaxed) {
halted = true;
}
// ── 1. Harvest completed agents ──────────────────────────────
let completed = self.agent_pool.cleanup_completed().await;
for (agent_id, result) in completed {
let task_id = { self.agent_to_task.write().await.remove(&agent_id) };
if let Some(task_id) = task_id {
match result {
Ok(agent_result) => {
if agent_result.success {
let summary = agent_result.summary.clone();
self.task_manager
.complete_task(&task_id, summary.clone())
.await?;
if let Err(e) = self
.communication_hub
.broadcast(
self.config.orchestrator_id.clone(),
AgentMessage::AgentCompleted {
agent_id: agent_id.clone(),
task_id: task_id.clone(),
summary,
},
)
.await
{
tracing::warn!(agent_id = %agent_id, task_id = %task_id, "Failed to broadcast agent completion: {}", e);
}
} else {
let error = agent_result.summary.clone();
self.task_manager.fail_task(&task_id, error.clone()).await?;
if let Err(e) = self
.communication_hub
.broadcast(
self.config.orchestrator_id.clone(),
AgentMessage::AgentCompleted {
agent_id: agent_id.clone(),
task_id: task_id.clone(),
summary: format!("FAILED: {}", error),
},
)
.await
{
tracing::warn!(agent_id = %agent_id, task_id = %task_id, "Failed to broadcast agent failure: {}", e);
}
if self.config.failure_policy == FailurePolicy::StopOnFirstFailure {
halted = true;
}
}
task_results.insert(task_id, agent_result);
}
Err(e) => {
let error = format!("Agent panicked: {}", e);
self.task_manager.fail_task(&task_id, error.clone()).await?;
if let Err(e) = self
.communication_hub
.broadcast(
self.config.orchestrator_id.clone(),
AgentMessage::AgentCompleted {
agent_id: agent_id.clone(),
task_id: task_id.clone(),
summary: error,
},
)
.await
{
tracing::warn!(agent_id = %agent_id, task_id = %task_id, "Failed to broadcast agent panic: {}", e);
}
if self.config.failure_policy == FailurePolicy::StopOnFirstFailure {
halted = true;
}
}
}
}
}
// ── 2. Schedule new tasks (unless halted) ────────────────────
if !halted {
let ready = self.task_manager.get_ready_tasks().await;
// Filter out tasks already assigned to an agent.
let assigned: std::collections::HashSet<String> = {
let map = self.agent_to_task.read().await;
map.values().cloned().collect()
};
let available_slots = {
let stats = self.agent_pool.stats().await;
stats.max_agents.saturating_sub(stats.running)
};
let mut spawned = 0usize;
for task in &ready {
if spawned >= available_slots {
break;
}
if assigned.contains(&task.id) {
continue;
}
// Skip tasks already InProgress (shouldn't happen, but be safe).
if task.status == TaskStatus::InProgress {
continue;
}
// Skip parent/container tasks — they auto-complete via
// check_parent_completion when all children finish.
if !task.children.is_empty() {
continue;
}
// Resolve config for this task.
let agent_config = {
let overrides = self.per_task_configs.read().await;
overrides
.get(&task.id)
.cloned()
.unwrap_or_else(|| self.config.default_agent_config.clone())
};
// Build a core Task for the agent pool.
let agent_task = Task::new(task.id.clone(), task.description.clone());
// Start + assign in TaskManager.
self.task_manager.start_task(&task.id).await?;
match self
.agent_pool
.spawn_agent(agent_task, Some(agent_config))
.await
{
Ok(agent_id) => {
self.task_manager.assign_task(&task.id, &agent_id).await?;
self.agent_to_task
.write()
.await
.insert(agent_id.clone(), task.id.clone());
if let Err(e) = self
.communication_hub
.broadcast(
self.config.orchestrator_id.clone(),
AgentMessage::AgentSpawned {
agent_id,
task_id: task.id.clone(),
},
)
.await
{
tracing::warn!(task_id = %task.id, "Failed to broadcast agent spawn: {}", e);
}
spawned += 1;
}
Err(e) => {
tracing::warn!(task_id = %task.id, error = %e, "failed to spawn agent");
// Revert status back to Pending so it can be retried.
self.task_manager
.update_status(&task.id, TaskStatus::Pending, None)
.await?;
}
}
}
}
// ── 3. Check termination ─────────────────────────────────────
let running = {
let map = self.agent_to_task.read().await;
map.len()
};
if running == 0 {
// No running agents. If halted or no more schedulable tasks, we're done.
let ready = self.task_manager.get_ready_tasks().await;
let assigned: std::collections::HashSet<String> = {
let map = self.agent_to_task.read().await;
map.values().cloned().collect()
};
// Only leaf tasks (no children) are schedulable.
let schedulable: Vec<_> = ready
.iter()
.filter(|t| !assigned.contains(&t.id) && t.children.is_empty())
.collect();
if halted || schedulable.is_empty() {
break;
}
}
tokio::time::sleep(poll).await;
}
// ── Build result ────────────────────────────────────────────────
let stats = self.task_manager.get_stats().await;
let all_tasks = self.task_manager.get_task_tree(Some(root_task_id)).await;
let unstarted: Vec<String> = all_tasks
.iter()
.filter(|t| t.status == TaskStatus::Pending || t.status == TaskStatus::Blocked)
.map(|t| t.id.clone())
.collect();
let all_succeeded = stats.failed == 0 && unstarted.is_empty();
Ok(OrchestrationResult {
all_succeeded,
task_results,
unstarted_tasks: unstarted,
stats,
})
}
/// Cancel all running agents and return.
pub async fn abort(&self) {
self.abort_flag
.store(true, std::sync::atomic::Ordering::Relaxed);
self.aborted.notify_one();
self.agent_pool.shutdown().await;
self.agent_to_task.write().await.clear();
}
/// Live task statistics snapshot.
pub async fn progress(&self) -> TaskStats {
self.task_manager.get_stats().await
}
/// Map of currently running agent_id -> task_id.
pub async fn running_agents(&self) -> HashMap<String, String> {
self.agent_to_task.read().await.clone()
}
}
// ── Tests ───────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::communication::CommunicationHub;
use crate::file_locks::FileLockManager;
use crate::pool::AgentPool;
use crate::task_agent::TaskAgentConfig;
use async_trait::async_trait;
use brainwires_core::{
ChatOptions, ChatResponse, Message, Provider, StreamChunk, Tool, ToolContext, ToolResult,
ToolUse, Usage,
};
use brainwires_tool_system::ToolExecutor;
use futures::stream::BoxStream;
// ── Mock provider that returns "Done" immediately ────────────────────
struct MockProvider(ChatResponse);
impl MockProvider {
fn done(text: &str) -> Self {
Self(ChatResponse {
message: Message::assistant(text),
finish_reason: Some("stop".to_string()),
usage: Usage::default(),
})
}
}
#[async_trait]
impl Provider for MockProvider {
fn name(&self) -> &str {
"mock"
}
async fn chat(
&self,
_: &[Message],
_: Option<&[Tool]>,
_: &ChatOptions,
) -> Result<ChatResponse> {
Ok(self.0.clone())
}
fn stream_chat<'a>(
&'a self,
_: &'a [Message],
_: Option<&'a [Tool]>,
_: &'a ChatOptions,
) -> BoxStream<'a, Result<StreamChunk>> {
Box::pin(futures::stream::empty())
}
}
struct NoOpExecutor;
#[async_trait]
impl ToolExecutor for NoOpExecutor {
async fn execute(&self, tu: &ToolUse, _: &ToolContext) -> Result<ToolResult> {
Ok(ToolResult::success(tu.id.clone(), "ok".to_string()))
}
fn available_tools(&self) -> Vec<Tool> {
vec![]
}
}
// ── Helpers ──────────────────────────────────────────────────────────
fn make_deps(max_pool: usize) -> (Arc<TaskManager>, Arc<AgentPool>, Arc<CommunicationHub>) {
let hub = Arc::new(CommunicationHub::new());
let flm = Arc::new(FileLockManager::new());
let provider: Arc<dyn Provider> = Arc::new(MockProvider::done("Done"));
let executor: Arc<dyn ToolExecutor> = Arc::new(NoOpExecutor);
let tm = Arc::new(TaskManager::new());
let pool = Arc::new(AgentPool::new(
max_pool,
provider,
executor,
Arc::clone(&hub),
flm,
"/tmp",
));
(tm, pool, hub)
}
fn no_validation() -> TaskAgentConfig {
TaskAgentConfig {
validation_config: None,
..Default::default()
}
}
fn make_orchestrator(
tm: Arc<TaskManager>,
pool: Arc<AgentPool>,
hub: Arc<CommunicationHub>,
) -> TaskOrchestrator {
TaskOrchestrator::new(
tm,
pool,
hub,
TaskOrchestratorConfig {
default_agent_config: no_validation(),
..Default::default()
},
)
}
// ── Tests ────────────────────────────────────────────────────────────
#[tokio::test]
async fn test_empty_orchestration() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
// Create a root task with no children.
let root = tm
.create_task("root".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
// Mark it completed so the loop has nothing to do.
tm.complete_task(&root, "already done".to_string())
.await
.unwrap();
let result = orch.run(&root).await.unwrap();
assert!(result.all_succeeded);
assert!(result.task_results.is_empty());
assert!(result.unstarted_tasks.is_empty());
}
#[tokio::test]
async fn test_single_task() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
let root = tm
.create_task("build widget".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let result = orch.run(&root).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 1);
assert!(result.task_results.contains_key(&root));
}
#[tokio::test]
async fn test_sequential_dependency_chain() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
// Create a chain: A -> B -> C (C depends on B, B depends on A).
// Use a parent to group them so get_task_tree works.
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let a = tm
.create_task(
"step A".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
let b = tm
.create_task(
"step B".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
let c = tm
.create_task(
"step C".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
tm.add_dependency(&b, &a).await.unwrap();
tm.add_dependency(&c, &b).await.unwrap();
let result = orch.run(&parent).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 3);
}
#[tokio::test]
async fn test_parallel_independent_tasks() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let _a = tm
.create_task(
"task A".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
let _b = tm
.create_task(
"task B".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
let _c = tm
.create_task(
"task C".to_string(),
Some(parent.clone()),
TaskPriority::Normal,
)
.await
.unwrap();
let result = orch.run(&parent).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 3);
}
#[tokio::test]
async fn test_diamond_dependency() {
// A -> (B, C) -> D
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let a = tm
.create_task("A".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let b = tm
.create_task("B".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let c = tm
.create_task("C".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let d = tm
.create_task("D".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
tm.add_dependency(&b, &a).await.unwrap();
tm.add_dependency(&c, &a).await.unwrap();
tm.add_dependency(&d, &b).await.unwrap();
tm.add_dependency(&d, &c).await.unwrap();
let result = orch.run(&parent).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 4);
}
#[tokio::test]
async fn test_stop_on_first_failure() {
// Use a provider that returns a failure response.
let hub = Arc::new(CommunicationHub::new());
let flm = Arc::new(FileLockManager::new());
// A provider whose "Done" text triggers agent success, but we need
// a way to fail. TaskAgent treats a "stop" finish_reason as success
// when the assistant text is non-empty. So we use a two-task setup
// where we manually fail one task to test the policy.
let provider: Arc<dyn Provider> = Arc::new(MockProvider::done("Done"));
let executor: Arc<dyn ToolExecutor> = Arc::new(NoOpExecutor);
let tm = Arc::new(TaskManager::new());
let pool = Arc::new(AgentPool::new(
5,
provider,
executor,
Arc::clone(&hub),
flm,
"/tmp",
));
let orch = TaskOrchestrator::new(
Arc::clone(&tm),
Arc::clone(&pool),
hub,
TaskOrchestratorConfig {
failure_policy: FailurePolicy::StopOnFirstFailure,
default_agent_config: no_validation(),
..Default::default()
},
);
// A -> B (sequential), so if A succeeds normally, B should follow.
// For this test, we create independent tasks so the orchestrator sees
// failures on independent paths.
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let a = tm
.create_task("A".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let _b = tm
.create_task("B".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
// Pre-fail task A so the orchestrator picks it up as failed immediately.
tm.fail_task(&a, "forced failure".to_string())
.await
.unwrap();
let result = orch.run(&parent).await.unwrap();
// A is failed, B may or may not have run depending on timing.
assert!(!result.all_succeeded);
}
#[tokio::test]
async fn test_continue_on_failure() {
let hub = Arc::new(CommunicationHub::new());
let flm = Arc::new(FileLockManager::new());
let provider: Arc<dyn Provider> = Arc::new(MockProvider::done("Done"));
let executor: Arc<dyn ToolExecutor> = Arc::new(NoOpExecutor);
let tm = Arc::new(TaskManager::new());
let pool = Arc::new(AgentPool::new(
5,
provider,
executor,
Arc::clone(&hub),
flm,
"/tmp",
));
let orch = TaskOrchestrator::new(
Arc::clone(&tm),
Arc::clone(&pool),
hub,
TaskOrchestratorConfig {
failure_policy: FailurePolicy::ContinueOnFailure,
default_agent_config: no_validation(),
..Default::default()
},
);
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let a = tm
.create_task("A".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let b_id = tm
.create_task("B".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
// Pre-fail A, B is independent and should still run.
tm.fail_task(&a, "forced failure".to_string())
.await
.unwrap();
let result = orch.run(&parent).await.unwrap();
// B should have completed even though A failed.
assert!(!result.all_succeeded); // A failed so not all_succeeded.
assert!(result.task_results.contains_key(&b_id));
}
#[tokio::test]
async fn test_pool_capacity_respect() {
// Pool size 1, 3 independent tasks — only one at a time.
let (tm, pool, hub) = make_deps(1);
let orch = make_orchestrator(tm.clone(), pool, hub);
let parent = tm
.create_task("parent".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let _a = tm
.create_task("A".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let _b = tm
.create_task("B".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let _c = tm
.create_task("C".to_string(), Some(parent.clone()), TaskPriority::Normal)
.await
.unwrap();
let result = orch.run(&parent).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 3);
}
#[tokio::test]
async fn test_assigned_to_tracking() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
let root = tm
.create_task("build widget".to_string(), None, TaskPriority::Normal)
.await
.unwrap();
let result = orch.run(&root).await.unwrap();
assert!(result.all_succeeded);
// After completion, assigned_to should have been set.
let task = tm.get_task(&root).await.unwrap();
assert!(task.assigned_to.is_some());
}
#[tokio::test]
async fn test_create_and_run() {
let (tm, pool, hub) = make_deps(5);
let orch = make_orchestrator(tm.clone(), pool, hub);
let specs = vec![
TaskSpec {
description: "step A".to_string(),
priority: TaskPriority::Normal,
depends_on_indices: vec![],
agent_config: None,
},
TaskSpec {
description: "step B".to_string(),
priority: TaskPriority::Normal,
depends_on_indices: vec![0],
agent_config: None,
},
TaskSpec {
description: "step C".to_string(),
priority: TaskPriority::Normal,
depends_on_indices: vec![0],
agent_config: None,
},
TaskSpec {
description: "step D".to_string(),
priority: TaskPriority::Normal,
depends_on_indices: vec![1, 2],
agent_config: None,
},
];
let result = orch.create_and_run(None, specs).await.unwrap();
assert!(result.all_succeeded);
assert_eq!(result.task_results.len(), 4);
}
}