-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTeamOrchestrator.cs
More file actions
1115 lines (946 loc) · 39.7 KB
/
TeamOrchestrator.cs
File metadata and controls
1115 lines (946 loc) · 39.7 KB
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using RalphController.Models;
using RalphController.Merge;
using RalphController.Parallel;
using RalphController.Git;
using RalphController.Messaging;
using System.Collections.Concurrent;
using System.Text;
using System.Text.RegularExpressions;
namespace RalphController;
/// <summary>
/// Lead agent coordinator with continuous coordination loop.
/// Replaces 3-phase sequential model with: Decompose → Spawn → Coordinate → Synthesize → Merge
/// </summary>
public class TeamOrchestrator : IDisposable
{
private readonly RalphConfig _config;
private readonly TeamConfig _teamConfig;
private readonly TaskStore _taskStore;
private readonly GitWorktreeManager _gitManager;
private readonly ConflictNegotiator _negotiator;
private readonly MergeManager _mergeManager;
private readonly ConcurrentDictionary<string, TeamAgent> _agents = new();
private readonly ConcurrentDictionary<string, AgentMonitorInfo> _agentMonitor = new();
private readonly SemaphoreSlim _mergeSemaphore;
private MessageBus? _leadBus;
private LeadAgent? _leadAgent;
private CancellationTokenSource? _stopCts;
private bool _disposed;
private volatile TeamOrchestratorState _state = TeamOrchestratorState.Idle;
private readonly List<string> _agentFindings = new();
private readonly Dictionary<string, DateTime> _agentStateTimestamps = new();
public event Action<TeamOrchestratorState>? OnStateChanged;
public event Action<string>? OnOutput;
public event Action<string>? OnError;
public event Action<AgentStatistics>? OnAgentUpdate;
public event Action<TaskStoreStatistics>? OnQueueUpdate;
public event Action<TaskAgent>? OnTaskAgentCreated;
public event Action<TaskAgent>? OnTaskAgentDestroyed;
public TeamOrchestrator(RalphConfig config)
{
_config = config;
_teamConfig = config.Teams ?? new TeamConfig();
var teamName = _teamConfig.TeamName ?? "default";
var storePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".ralph", "teams", teamName, "tasks");
_taskStore = TaskStore.LoadFromDisk(
storePath,
TimeSpan.FromSeconds(_teamConfig.TaskClaimTimeoutSeconds));
var mailboxDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".ralph", "teams", teamName, "mailbox");
_leadBus = MessageBus.CreateForLead(mailboxDir);
_gitManager = new GitWorktreeManager(config.TargetDirectory);
_negotiator = new ConflictNegotiator(config, config.ProviderConfig);
_mergeManager = new MergeManager(_gitManager, _negotiator, _taskStore, _teamConfig, config);
_mergeSemaphore = new SemaphoreSlim(_teamConfig.MaxConcurrentMerges);
}
public TeamOrchestratorState State => _state;
public TaskStore TaskStore => _taskStore;
public IReadOnlyDictionary<string, TeamAgent> Agents => _agents;
public bool DelegateMode => _teamConfig.DelegateMode;
public async Task RunAsync(CancellationToken cancellationToken = default)
{
_stopCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
SetState(TeamOrchestratorState.Initializing);
if (_teamConfig.DelegateMode)
{
OnOutput?.Invoke("Running in DELEGATE MODE — lead coordinates only, no file edits");
}
try
{
// In lead-driven mode, show the lead agent in the TUI immediately
// so the user sees something happening during decomposition.
if (_teamConfig.LeadDriven)
{
var modelLabel = _teamConfig.LeadModel?.DisplayName ?? _config.Provider.ToString();
OnAgentUpdate?.Invoke(new AgentStatistics
{
AgentId = "lead",
Name = $"Lead [{modelLabel}]",
State = AgentState.PlanningWork
});
OnOutput?.Invoke("Lead agent initializing, reading implementation plan...");
}
var tasks = await DecomposeAsync(_stopCts.Token);
if (tasks.Count == 0)
{
OnError?.Invoke("No tasks found after decomposition");
SetState(TeamOrchestratorState.Failed);
return;
}
_taskStore.AddTasks(tasks);
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
if (_teamConfig.LeadDriven)
{
await RunLeadDrivenAsync(_stopCts.Token);
}
else
{
await RunParallelAsync(_stopCts.Token);
}
SetState(TeamOrchestratorState.Complete);
OnOutput?.Invoke("Teams execution complete!");
}
catch (OperationCanceledException)
{
SetState(TeamOrchestratorState.Stopped);
OnOutput?.Invoke("Teams execution cancelled");
}
catch (Exception ex)
{
OnError?.Invoke($"Teams execution failed: {ex.Message}");
SetState(TeamOrchestratorState.Failed);
}
}
/// <summary>
/// Original parallel execution path: Spawn N agents → Coordinate → Synthesize → Merge
/// </summary>
private async Task RunParallelAsync(CancellationToken cancellationToken)
{
await SpawnAgentsAsync(cancellationToken);
await CoordinateAsync(cancellationToken);
await SynthesizeResultsAsync(cancellationToken);
await MergeAndCleanupAsync(cancellationToken);
}
/// <summary>
/// Lead-driven sequential execution: Lead AI decides task order,
/// creates ephemeral TaskAgents with 3-phase sub-agents, merges after each task.
/// </summary>
private async Task RunLeadDrivenAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke("Running in LEAD-DRIVEN mode (sequential, 3-tier)");
SetState(TeamOrchestratorState.Coordinating);
// Clean up stale worktrees
if (_teamConfig.UseWorktrees)
{
var worktreeBaseDir = Path.Combine(_config.TargetDirectory, ".ralph-worktrees");
await _gitManager.CleanupStaleWorktreesAsync(worktreeBaseDir, cancellationToken);
}
OnOutput?.Invoke("Initializing lead agent...");
var leadAgent = new LeadAgent(
_config,
_teamConfig,
_taskStore,
_gitManager,
_mergeManager,
_leadBus);
// Wire lead events to orchestrator events
leadAgent.OnOutput += output => OnOutput?.Invoke(output);
leadAgent.OnError += error => OnError?.Invoke(error);
leadAgent.OnUpdate += stats => OnAgentUpdate?.Invoke(stats);
leadAgent.OnQueueUpdate += stats => OnQueueUpdate?.Invoke(stats);
leadAgent.OnTaskAgentCreated += taskAgent =>
{
OnTaskAgentCreated?.Invoke(taskAgent);
// Also wire TaskAgent updates to orchestrator for TUI
taskAgent.OnUpdate += agentStats => OnAgentUpdate?.Invoke(agentStats);
};
leadAgent.OnTaskAgentDestroyed += taskAgent =>
{
OnTaskAgentDestroyed?.Invoke(taskAgent);
};
leadAgent.OnDecision += decision =>
{
OnOutput?.Invoke($"Lead decision: {decision.Action} {decision.TaskId ?? ""} — {decision.Reason ?? ""}");
};
// Emit initial lead stats so TUI shows the lead immediately
OnAgentUpdate?.Invoke(leadAgent.Statistics);
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
var taskStats = _taskStore.GetStatistics();
OnOutput?.Invoke($"Lead agent ready — {taskStats.Total} tasks queued, starting decision loop...");
_leadAgent = leadAgent;
try
{
await leadAgent.RunAsync(cancellationToken);
}
catch (OperationCanceledException)
{
OnOutput?.Invoke("Lead agent cancelled");
}
catch (Exception ex)
{
OnError?.Invoke($"Lead agent crashed: {ex.Message}");
OnOutput?.Invoke($"Lead agent encountered a fatal error: {ex.Message}");
OnOutput?.Invoke("Attempting to wait for running agents to complete...");
}
finally
{
_leadAgent = null;
leadAgent.Dispose();
}
// Audit phase: spawn audit agents, collect findings, loop if issues found
const int MaxAuditRounds = 3;
for (int auditRound = 1; auditRound <= MaxAuditRounds; auditRound++)
{
cancellationToken.ThrowIfCancellationRequested();
SetState(TeamOrchestratorState.Auditing);
OnOutput?.Invoke($"Starting audit phase (round {auditRound}/{MaxAuditRounds})...");
var findings = await RunAuditPhaseAsync(auditRound, cancellationToken);
if (findings.Count == 0)
{
OnOutput?.Invoke("Audit clean — no issues found.");
break;
}
OnOutput?.Invoke($"Audit found {findings.Count} issue(s). Creating remediation tasks...");
// Append findings to implementation plan
PlanUpdater.AppendAuditFindings(
_config.PlanFilePath, findings, auditRound, msg => OnOutput?.Invoke(msg));
// Create new tasks from findings
var existingCount = _taskStore.GetAll().Count;
var newTasks = findings.Select((f, i) => new AgentTask
{
TaskId = $"audit-{auditRound}-{i + 1}",
Title = f.Title,
Description = f.Description,
Priority = f.Severity?.ToLower() == "critical" ? TaskPriority.Critical
: f.Severity?.ToLower() == "high" ? TaskPriority.High
: TaskPriority.Normal
}).ToList();
_taskStore.AddTasks(newTasks);
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
// Re-run lead agent for the new tasks
OnOutput?.Invoke($"Re-running lead agent for {newTasks.Count} remediation task(s)...");
SetState(TeamOrchestratorState.Coordinating);
var remediationLead = new LeadAgent(
_config, _teamConfig, _taskStore, _gitManager, _mergeManager, _leadBus);
remediationLead.OnOutput += output => OnOutput?.Invoke(output);
remediationLead.OnError += error => OnError?.Invoke(error);
remediationLead.OnUpdate += stats => OnAgentUpdate?.Invoke(stats);
remediationLead.OnQueueUpdate += stats => OnQueueUpdate?.Invoke(stats);
remediationLead.OnTaskAgentCreated += taskAgent =>
{
OnTaskAgentCreated?.Invoke(taskAgent);
taskAgent.OnUpdate += agentStats => OnAgentUpdate?.Invoke(agentStats);
};
remediationLead.OnTaskAgentDestroyed += taskAgent => OnTaskAgentDestroyed?.Invoke(taskAgent);
OnAgentUpdate?.Invoke(remediationLead.Statistics);
_leadAgent = remediationLead;
try
{
await remediationLead.RunAsync(cancellationToken);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
OnError?.Invoke($"Remediation lead crashed: {ex.Message}");
}
finally
{
_leadAgent = null;
remediationLead.Dispose();
}
if (auditRound == MaxAuditRounds)
{
OnError?.Invoke($"Reached max audit rounds ({MaxAuditRounds}). Proceeding despite unresolved findings.");
}
}
// Synthesize results
await SynthesizeResultsAsync(cancellationToken);
// Cleanup persistence files
_taskStore.DeletePersistenceFiles();
}
public async Task<IReadOnlyList<AgentTask>> DecomposeAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke("Decomposing tasks...");
SetState(TeamOrchestratorState.Decomposing);
var existingStats = _taskStore.GetStatistics();
if (existingStats.Total > 0 && existingStats.Pending > 0)
{
OnOutput?.Invoke($"Restored {existingStats.Total} tasks from previous session ({existingStats.Pending} pending, {existingStats.Completed} completed, {existingStats.Failed} failed)");
return _taskStore.GetAll().ToList();
}
// Stale tasks from a previous completed/crashed run — clear them
// before decomposing fresh so old failures don't block the new run.
if (existingStats.Total > 0)
{
OnOutput?.Invoke($"Clearing {existingStats.Total} stale tasks from previous run (no pending work)");
_taskStore.Clear();
}
var tasks = new List<AgentTask>();
var planPath = _config.PlanFilePath;
if (!File.Exists(planPath))
{
OnError?.Invoke($"Implementation plan not found: {planPath}");
return tasks;
}
var lines = await File.ReadAllLinesAsync(planPath, cancellationToken);
var taskIndex = 0;
string? currentCategory = null;
foreach (var line in lines)
{
var trimmedLine = line.Trim();
if (trimmedLine.StartsWith("## "))
{
currentCategory = trimmedLine[3..].Trim();
continue;
}
if (!trimmedLine.StartsWith("- [ ]") && !trimmedLine.StartsWith("- [!]") && !trimmedLine.StartsWith("- [?]"))
{
continue;
}
taskIndex++;
var task = ParseTaskFromLine(trimmedLine, currentCategory, taskIndex);
if (task != null)
{
tasks.Add(task);
}
}
OnOutput?.Invoke($"Decomposed into {tasks.Count} tasks");
return tasks;
}
public async Task SpawnAgentsAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke($"Spawning {_teamConfig.AgentCount} agents...");
SetState(TeamOrchestratorState.Spawning);
// Clean up stale worktrees from interrupted previous runs
if (_teamConfig.UseWorktrees)
{
var worktreeBaseDir = Path.Combine(_config.TargetDirectory, ".ralph-worktrees");
await _gitManager.CleanupStaleWorktreesAsync(worktreeBaseDir, cancellationToken);
OnOutput?.Invoke("Cleaned up stale worktrees from previous run");
}
var sourceBranch = _teamConfig.SourceBranch;
if (string.IsNullOrEmpty(sourceBranch))
{
sourceBranch = await _gitManager.GetCurrentBranchAsync(cancellationToken);
}
var spawnTasks = new List<Task>();
for (int i = 0; i < _teamConfig.AgentCount; i++)
{
var agentId = $"agent-{i + 1}";
var agent = new TeamAgent(
_config,
_teamConfig,
agentId,
i,
_gitManager,
_teamConfig.GetAgentModel(i));
agent.SetTaskStore(_taskStore);
agent.SetMergeManager(_mergeManager);
agent.SetMergeLock(_mergeSemaphore);
var mailboxDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".ralph", "teams", _teamConfig.TeamName ?? "default", "mailbox");
agent.SetMessageBus(new MessageBus(mailboxDir, agentId));
agent.OnOutput += output => OnOutput?.Invoke($"[{agentId}] {output}");
agent.OnError += error => OnError?.Invoke($"[{agentId}] {error}");
agent.OnStateChanged += state =>
{
_agentStateTimestamps[agentId] = DateTime.UtcNow;
OnAgentUpdate?.Invoke(agent.Statistics);
};
agent.OnIdle += a => RunHookAsync("TeammateIdle", a.AgentId);
agent.OnTaskComplete += (task, result) =>
{
_taskStore.Complete(task.TaskId, result);
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
RunHookAsync("TaskCompleted", task.TaskId);
};
agent.OnTaskFailed += (task, error) =>
{
_taskStore.Fail(task.TaskId, error);
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
};
_agents[agentId] = agent;
_agentMonitor[agentId] = new AgentMonitorInfo { AgentId = agentId };
_agentStateTimestamps[agentId] = DateTime.UtcNow;
spawnTasks.Add(Task.Run(async () =>
{
var initialized = await agent.InitializeAsync(cancellationToken);
if (!initialized)
{
OnError?.Invoke($"Failed to initialize agent {agentId}");
}
}, cancellationToken));
}
await Task.WhenAll(spawnTasks);
OnOutput?.Invoke("All agents spawned");
}
public async Task CoordinateAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke("Starting coordination loop...");
SetState(TeamOrchestratorState.Coordinating);
var agentTasks = _agents.Values
.Select(a => Task.Run(() => a.RunLoopAsync(null, cancellationToken), cancellationToken))
.ToList();
while (!cancellationToken.IsCancellationRequested)
{
ProcessLeadMessages();
if (await CheckForStuckAgentsAsync())
{
await HandleStuckAgentsAsync();
}
UpdateAgentMonitoring();
if (AllTasksResolved() && AllAgentsIdleOrStopped())
{
OnOutput?.Invoke("All tasks resolved, all agents idle/stopped");
break;
}
OnQueueUpdate?.Invoke(_taskStore.GetStatistics());
await Task.Delay(1000, cancellationToken);
}
await Task.WhenAll(agentTasks);
}
private void ProcessLeadMessages()
{
if (_leadBus == null) return;
var messages = _leadBus.Poll();
foreach (var msg in messages)
{
switch (msg.Type)
{
case MessageType.StatusUpdate:
if (_agentMonitor.TryGetValue(msg.FromAgentId, out var monitor))
{
monitor.LastStatus = msg.Content;
monitor.LastMessageAt = DateTime.UtcNow;
}
break;
case MessageType.PlanSubmission:
HandlePlanSubmission(msg);
break;
case MessageType.ShutdownResponse:
OnOutput?.Invoke($"Agent {msg.FromAgentId} shutdown response: {msg.Content}");
break;
case MessageType.Text:
_agentFindings.Add($"[{msg.FromAgentId}] {msg.Content}");
break;
}
}
}
private void HandlePlanSubmission(Message msg)
{
var taskId = msg.Metadata?.GetValueOrDefault("taskId", "");
OnOutput?.Invoke($"Plan received from {msg.FromAgentId} for task {taskId}");
var approved = EvaluatePlan(msg.Content, taskId ?? "");
var feedback = approved ? "" : "Plan needs revision: ensure it addresses the task and touches only expected files.";
_leadBus?.Send(Message.PlanApprovalMessage("lead", msg.FromAgentId, approved, feedback));
}
private bool EvaluatePlan(string plan, string taskId)
{
if (string.IsNullOrWhiteSpace(plan)) return false;
if (plan.Length < 50) return false;
var task = _taskStore.GetById(taskId);
if (task == null) return true;
var taskKeywords = task.Description.Split(' ')
.Where(w => w.Length > 4)
.Select(w => w.ToLower())
.ToHashSet();
var planLower = plan.ToLower();
var keywordMatches = taskKeywords.Count(k => planLower.Contains(k));
return keywordMatches >= 2 || plan.Length > 200;
}
private async Task<bool> CheckForStuckAgentsAsync()
{
var avgTaskTime = await GetAverageTaskTimeAsync();
if (avgTaskTime == TimeSpan.Zero) return false;
var stuckThreshold = TimeSpan.FromTicks(avgTaskTime.Ticks * 2);
var now = DateTime.UtcNow;
foreach (var (agentId, agent) in _agents)
{
if (agent.State != AgentState.Working) continue;
if (!_agentStateTimestamps.TryGetValue(agentId, out var stateTime)) continue;
var timeInState = now - stateTime;
if (timeInState <= stuckThreshold) continue;
// Also check if agent has sent messages recently (activity proxy)
if (_agentMonitor.TryGetValue(agentId, out var monitor) &&
(now - monitor.LastMessageAt) > stuckThreshold)
{
return true;
}
}
return false;
}
private async Task HandleStuckAgentsAsync()
{
var avgTaskTime = await GetAverageTaskTimeAsync();
if (avgTaskTime == TimeSpan.Zero) return;
var stuckThreshold = TimeSpan.FromTicks(avgTaskTime.Ticks * 2);
var now = DateTime.UtcNow;
foreach (var (agentId, agent) in _agents)
{
if (agent.State != AgentState.Working || agent.CurrentTask == null) continue;
if (!_agentStateTimestamps.TryGetValue(agentId, out var stateTime)) continue;
var timeInState = now - stateTime;
if (timeInState <= stuckThreshold) continue;
// Check no recent messages from this agent
if (_agentMonitor.TryGetValue(agentId, out var monitor) &&
(now - monitor.LastMessageAt) <= stuckThreshold)
{
continue; // Agent is communicating, not actually stuck
}
var taskId = agent.CurrentTask.TaskId;
OnOutput?.Invoke($"Agent {agentId} appears stuck on task {taskId} ({timeInState.TotalSeconds:F0}s)");
// Send a status check message to the stuck agent
_leadBus?.Send(Message.TextMessage("lead", agentId, "Status check: are you still working on your current task?"));
// Find an idle agent to reassign to
var idleAgent = _agents.Values.FirstOrDefault(a =>
a.AgentId != agentId &&
a.State == AgentState.Idle);
if (idleAgent != null)
{
OnOutput?.Invoke($"Reassigning task {taskId} from stuck agent {agentId} to idle agent {idleAgent.AgentId}");
_taskStore.ReassignTask(taskId, null); // Reset to Pending so idle agent can claim it
_leadBus?.Send(Message.TaskAssignmentMessage("lead", idleAgent.AgentId, taskId,
agent.CurrentTask.Description));
}
else
{
OnOutput?.Invoke($"No idle agents available to reassign task {taskId}");
}
}
}
private Task<TimeSpan> GetAverageTaskTimeAsync()
{
var completedTasks = _taskStore.GetAll()
.Where(t => t.Status == Models.TaskStatus.Completed && t.CompletedAt.HasValue && t.ClaimedAt.HasValue)
.ToList();
if (completedTasks.Count == 0) return Task.FromResult(TimeSpan.Zero);
var avgTicks = (long)completedTasks
.Average(t => (t.CompletedAt!.Value - t.ClaimedAt!.Value).Ticks);
return Task.FromResult(TimeSpan.FromTicks(avgTicks));
}
private void UpdateAgentMonitoring()
{
foreach (var (agentId, agent) in _agents)
{
if (_agentMonitor.TryGetValue(agentId, out var monitor))
{
monitor.CurrentState = agent.State;
monitor.CurrentTask = agent.CurrentTask?.TaskId;
OnAgentUpdate?.Invoke(agent.Statistics);
}
}
}
private bool AllTasksResolved()
{
var stats = _taskStore.GetStatistics();
return stats.Pending == 0 && stats.InProgress == 0;
}
private bool AllAgentsIdleOrStopped()
{
return _agents.Values.All(a =>
a.State == AgentState.Idle ||
a.State == AgentState.Stopped ||
a.State == AgentState.ShuttingDown);
}
public async Task SynthesizeResultsAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke("Synthesizing results...");
SetState(TeamOrchestratorState.Synthesizing);
var results = new StringBuilder();
results.AppendLine("# Teams Execution Results");
results.AppendLine();
var stats = _taskStore.GetStatistics();
results.AppendLine($"## Summary");
results.AppendLine($"- Total tasks: {stats.Total}");
results.AppendLine($"- Completed: {stats.Completed}");
results.AppendLine($"- Failed: {stats.Failed}");
results.AppendLine();
results.AppendLine("## Task Details");
foreach (var task in _taskStore.GetAll())
{
var status = task.Status.ToString();
var agent = task.ClaimedByAgentId ?? "unassigned";
results.AppendLine($"- [{status}] {task.Title ?? task.TaskId} (by {agent})");
}
if (_agentFindings.Count > 0)
{
results.AppendLine();
results.AppendLine("## Agent Findings");
foreach (var finding in _agentFindings)
{
results.AppendLine($"- {finding}");
}
}
OnOutput?.Invoke(results.ToString());
// Mark completed tasks in the implementation plan
OnOutput?.Invoke("Marking completed tasks in implementation plan...");
var verification = PlanUpdater.MarkCompletedTasks(
_config.PlanFilePath,
_taskStore.GetAll().ToList(),
msg => OnOutput?.Invoke(msg));
if (verification.AllTasksComplete)
{
OnOutput?.Invoke($"All {verification.TasksMarked} tasks marked complete in plan");
}
else
{
OnOutput?.Invoke($"Marked {verification.TasksMarked} tasks complete, {verification.IncompleteTasks.Count} incomplete");
}
}
/// <summary>
/// Spawn up to AgentCount audit TaskAgents. Each runs a Code-only phase with an audit prompt.
/// Parses output for ISSUE: lines. Returns discovered findings.
/// </summary>
private async Task<List<AuditFinding>> RunAuditPhaseAsync(int auditRound, CancellationToken ct)
{
var findings = new List<AuditFinding>();
var agentCount = Math.Max(1, _teamConfig.AgentCount);
// Build audit tasks — one per agent
var auditTasks = new List<AgentTask>();
for (int i = 0; i < agentCount; i++)
{
auditTasks.Add(new AgentTask
{
TaskId = $"audit-check-{auditRound}-{i + 1}",
Title = $"Audit agent {i + 1} (round {auditRound})",
Description = BuildAuditPromptDescription(i, agentCount, auditRound)
});
}
// Clean up stale worktrees before audit
if (_teamConfig.UseWorktrees)
{
var worktreeBaseDir = Path.Combine(_config.TargetDirectory, ".ralph-worktrees");
await _gitManager.CleanupStaleWorktreesAsync(worktreeBaseDir, ct);
}
// Launch audit agents in parallel
var agentResults = new ConcurrentBag<(int Index, TaskAgentResult Result)>();
var tasks = new List<Task>();
for (int i = 0; i < auditTasks.Count; i++)
{
var index = i;
var auditTask = auditTasks[i];
var model = _teamConfig.GetAgentModel(index);
tasks.Add(Task.Run(async () =>
{
var taskAgent = new TaskAgent(
_config,
// Override SubAgentPhases to Code-only for audit
_teamConfig with { SubAgentPhases = new List<SubAgentPhase> { SubAgentPhase.Code } },
auditTask,
_gitManager,
model);
taskAgent.OnOutput += output => OnOutput?.Invoke($"[audit-{index + 1}] {output}");
taskAgent.OnError += error => OnError?.Invoke($"[audit-{index + 1}] {error}");
taskAgent.OnUpdate += stats => OnAgentUpdate?.Invoke(stats);
OnTaskAgentCreated?.Invoke(taskAgent);
try
{
var initialized = await taskAgent.InitializeAsync(ct);
if (!initialized)
{
OnError?.Invoke($"Audit agent {index + 1} failed to initialize");
agentResults.Add((index, new TaskAgentResult
{
Success = false,
Summary = "Init failed",
BranchName = taskAgent.BranchName
}));
return;
}
var result = await taskAgent.RunAsync(ct);
agentResults.Add((index, result));
// Cleanup worktree (audit agents are read-only, no merge needed)
await taskAgent.CleanupAsync();
}
finally
{
OnTaskAgentDestroyed?.Invoke(taskAgent);
taskAgent.Dispose();
}
}, ct));
}
await Task.WhenAll(tasks);
// Parse findings from audit agent output
foreach (var (index, result) in agentResults.OrderBy(r => r.Index))
{
if (!result.Success)
{
OnOutput?.Invoke($"Audit agent {index + 1} failed: {result.Summary}");
continue;
}
var output = result.Code?.Output ?? result.Summary ?? "";
// Check for clean audit
if (output.Contains("AUDIT_CLEAN"))
{
OnOutput?.Invoke($"Audit agent {index + 1}: clean");
continue;
}
// Parse ISSUE: lines
var issueMatches = Regex.Matches(output, @"ISSUE:\s*(.+?)(?:\s*\|\s*(.+))?$", RegexOptions.Multiline);
foreach (Match match in issueMatches)
{
var title = match.Groups[1].Value.Trim();
var description = match.Groups[2].Success ? match.Groups[2].Value.Trim() : title;
// Extract severity if present at start of title like [CRITICAL] or [HIGH]
string? severity = null;
var severityMatch = Regex.Match(title, @"^\[(critical|high|medium|low)\]\s*", RegexOptions.IgnoreCase);
if (severityMatch.Success)
{
severity = severityMatch.Groups[1].Value;
title = title[severityMatch.Length..];
}
findings.Add(new AuditFinding(title, description, severity));
}
if (issueMatches.Count == 0)
{
// If agent output doesn't contain ISSUE: or AUDIT_CLEAN, treat as potential issue
OnOutput?.Invoke($"Audit agent {index + 1}: no structured findings, checking for errors...");
}
}
return findings;
}
/// <summary>
/// Build the audit prompt description for an individual audit agent.
/// </summary>
private string BuildAuditPromptDescription(int agentIndex, int totalAgents, int auditRound)
{
var sb = new StringBuilder();
sb.AppendLine("You are an AUDIT agent — your job is to review the project after all implementation is complete.");
sb.AppendLine("DO NOT implement new features. Only review and report issues.");
sb.AppendLine();
sb.AppendLine($"This is audit round {auditRound}. You are agent {agentIndex + 1} of {totalAgents}.");
sb.AppendLine();
sb.AppendLine("INSTRUCTIONS:");
if (!string.IsNullOrEmpty(_teamConfig.VerifyCommand))
{
sb.AppendLine($"1. Run the verification command: {_teamConfig.VerifyCommand}");
}
else
{
sb.AppendLine("1. Build the project and run any available tests");
}
sb.AppendLine("2. Check for compilation errors and test failures");
sb.AppendLine("3. Review recent git changes for correctness (use git log and git diff)");
sb.AppendLine("4. Look for missing implementations, TODOs, or incomplete features");
sb.AppendLine("5. Check for common issues: null references, missing error handling, broken imports");
sb.AppendLine();
sb.AppendLine("OUTPUT FORMAT:");
sb.AppendLine("For each issue found, output a line in this exact format:");
sb.AppendLine(" ISSUE: <title> | <description>");
sb.AppendLine();
sb.AppendLine("You can optionally include severity: ISSUE: [CRITICAL] <title> | <description>");
sb.AppendLine();
sb.AppendLine("If everything looks good and all tests pass, output:");
sb.AppendLine(" AUDIT_CLEAN");
sb.AppendLine();
sb.AppendLine("Be thorough but concise. Only report real issues, not style preferences.");
return sb.ToString();
}
public async Task MergeAndCleanupAsync(CancellationToken cancellationToken)
{
OnOutput?.Invoke("Merging and cleaning up...");
SetState(TeamOrchestratorState.Merging);
foreach (var agent in _agents.Values)
{
try
{
var result = await agent.MergeAsync(cancellationToken);
if (result.Success)
{
OnOutput?.Invoke($"[{agent.AgentId}] Merge successful");
}
else if (result.Conflicts?.Count > 0)
{
OnOutput?.Invoke($"[{agent.AgentId}] Conflicts detected: {result.Conflicts.Count}");
}
await agent.CleanupAsync();
}
catch (Exception ex)
{
OnError?.Invoke($"[{agent.AgentId}] Merge failed: {ex.Message}");
}
}
_taskStore.DeletePersistenceFiles();
}
public void AddTask(AgentTask task) => _taskStore.AddTask(task);
public void ReassignTask(string taskId, string newAgentId)
{
_taskStore.ReassignTask(taskId, newAgentId);
OnOutput?.Invoke($"Task {taskId} reassigned to {newAgentId}");
}
public void CancelTask(string taskId)
{
_taskStore.CancelTask(taskId);
OnOutput?.Invoke($"Task {taskId} cancelled");
}
/// <summary>
/// Send a user message to the lead agent (lead-driven mode).
/// </summary>
public void SendMessageToLead(string message)
{
if (_leadBus == null) return;
_leadBus.Send(Message.TextMessage("user", "lead", message));
_leadAgent?.NotifyMessageAvailable();
}
public void RequestShutdown(string agentId)
{
if (_agents.TryGetValue(agentId, out var agent))
{
agent.RequestShutdown();
OnOutput?.Invoke($"Shutdown requested for {agentId}");
}
}
public async Task ShutdownAll()
{
foreach (var agent in _agents.Values)
{
agent.RequestShutdown();
}
await Task.WhenAll(_agents.Values.Select(a => Task.Run(() => a.Dispose())));
}
private AgentTask? ParseTaskFromLine(string line, string? category, int taskIndex)
{
var isPriority = line.Contains("[!]");
var description = line
.Replace("- [ ]", "")
.Replace("- [!]", "")
.Replace("- [?]", "")
.Replace("[!]", "")
.Trim();
if (string.IsNullOrWhiteSpace(description)) return null;
return new AgentTask
{
TaskId = $"task-{taskIndex}",
Title = description.Length > 60 ? description[..60] + "..." : description,
Description = description,
SourceLine = line,
Priority = isPriority ? TaskPriority.High : TaskPriority.Normal,
Category = category
};
}
/// <summary>
/// Get the delegate mode coordinator instructions for the lead's AI prompt.
/// When delegate mode is on, the lead should not edit files or run build commands.
/// </summary>
public string? GetDelegateModeInstructions()
{
if (!_teamConfig.DelegateMode) return null;
return """
--- DELEGATE MODE ---
You are a COORDINATOR. You must NOT:
- Edit, create, or delete any files
- Run build, test, or shell commands
- Make direct code changes
You CAN:
- Spawn and shut down agents
- Send and receive messages
- Create, assign, reassign, and cancel tasks
- Review and approve agent plans
- Synthesize findings into reports
- Provide guidance and feedback to agents
All implementation work must be delegated to your team agents.