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
//! Merge queue for serializing agent merges in MapReduce workflows
//!
//! This module provides a queue-based system for serializing git merge operations
//! from parallel MapReduce agents back to the parent worktree. By processing merges
//! sequentially through a background worker, we eliminate MERGE_HEAD race conditions
//! while preserving parallel agent execution.
use crate::cook::execution::claude::ClaudeExecutor;
use crate::cook::execution::errors::{MapReduceError, MapReduceResult};
use crate::cook::execution::mapreduce::resources::git::GitOperations;
use crate::cook::orchestrator::ExecutionEnvironment;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
/// Request to merge an agent's branch back to the parent worktree
#[derive(Debug)]
struct MergeRequest {
/// Unique identifier for the agent
agent_id: String,
/// Name of the branch to merge
branch_name: String,
/// Item ID being processed
item_id: String,
/// Execution environment with parent worktree context
env: ExecutionEnvironment,
/// Channel to send the merge result back to the waiting agent
response_tx: oneshot::Sender<MapReduceResult<()>>,
}
/// Queue for serializing git merge operations from parallel agents
///
/// The MergeQueue accepts merge requests from multiple concurrent agents
/// and processes them sequentially through a background worker task.
/// This prevents race conditions when multiple agents try to merge to
/// the same parent worktree simultaneously.
///
/// When conflicts occur, the queue automatically invokes Claude to resolve them.
pub struct MergeQueue {
/// Channel for submitting merge requests
tx: mpsc::UnboundedSender<MergeRequest>,
/// Handle to the background worker task
_worker_handle: Arc<JoinHandle<()>>,
}
impl MergeQueue {
/// Create a new merge queue with a background worker
///
/// The worker task will process merge requests sequentially until
/// the queue is dropped and all senders are closed.
pub fn new(git_ops: Arc<GitOperations>) -> Self {
Self::new_with_claude(git_ops, None, 0)
}
/// Create a new merge queue with Claude support for conflict resolution
///
/// When a Claude executor is provided, the queue will automatically attempt
/// to resolve merge conflicts using Claude-assisted merge commands.
///
/// The verbosity parameter controls Claude console output behavior:
/// - verbosity >= 1: Claude streaming JSON output is displayed
/// - verbosity == 0: Clean output with streaming JSON confined to log files
pub fn new_with_claude(
git_ops: Arc<GitOperations>,
claude_executor: Option<Arc<dyn ClaudeExecutor>>,
verbosity: u8,
) -> Self {
let (tx, mut rx) = mpsc::unbounded_channel::<MergeRequest>();
// Spawn background worker to process merges serially
let worker_handle = tokio::spawn(async move {
info!("Merge queue worker started");
let mut merge_count = 0;
while let Some(request) = rx.recv().await {
debug!(
"Processing merge request for agent {} (item {})",
request.agent_id, request.item_id
);
// Try standard git merge first
let result = git_ops
.merge_agent_to_parent(&request.branch_name, &request.env)
.await;
// If merge failed and we have Claude, ALWAYS try Claude-assisted merge as fallback
// This ensures bulletproof merge handling for any type of conflict or edge case
let final_result = match (&result, &claude_executor) {
(Err(_), Some(executor)) => {
info!(
"Git merge failed for agent {} (item {}), attempting Claude-assisted merge fallback",
request.agent_id, request.item_id
);
// Execute Claude merge command in parent worktree
let mut env_vars = HashMap::new();
env_vars.insert("PRODIGY_AUTOMATION".to_string(), "true".to_string());
// Only set PRODIGY_CLAUDE_STREAMING if verbosity >= 1
if verbosity >= 1 {
env_vars
.insert("PRODIGY_CLAUDE_STREAMING".to_string(), "true".to_string());
}
// Respect PRODIGY_CLAUDE_CONSOLE_OUTPUT override
if std::env::var("PRODIGY_CLAUDE_CONSOLE_OUTPUT").unwrap_or_default()
== "true"
{
env_vars.insert(
"PRODIGY_CLAUDE_CONSOLE_OUTPUT".to_string(),
"true".to_string(),
);
}
match executor
.execute_claude_command(
&format!("/prodigy-merge-worktree {}", request.branch_name),
&request.env.working_dir,
env_vars,
)
.await
{
Ok(claude_result) if claude_result.success => {
info!(
"Claude successfully resolved merge for agent {} (item {})",
request.agent_id, request.item_id
);
Ok(())
}
Ok(claude_result) => {
warn!(
"Claude failed to resolve merge for agent {} (item {}): {}",
request.agent_id, request.item_id, claude_result.stderr
);
Err(MapReduceError::ProcessingError(format!(
"Claude-assisted merge failed for agent {}: {}",
request.branch_name, claude_result.stderr
)))
}
Err(e) => {
warn!(
"Failed to execute Claude merge command for agent {} (item {}): {}",
request.agent_id, request.item_id, e
);
Err(MapReduceError::ProcessingError(format!(
"Failed to execute Claude merge command: {}",
e
)))
}
}
}
_ => result,
};
match &final_result {
Ok(()) => {
merge_count += 1;
debug!(
"Completed merge {}: agent {} (item {})",
merge_count, request.agent_id, request.item_id
);
}
Err(e) => {
warn!(
"Merge failed for agent {} (item {}): {}",
request.agent_id, request.item_id, e
);
}
}
// Send result back to waiting agent (ignore send errors - agent may have timed out)
let _ = request.response_tx.send(final_result);
}
info!(
"Merge queue worker shutting down (processed {} merges)",
merge_count
);
});
Self {
tx,
_worker_handle: Arc::new(worker_handle),
}
}
/// Submit a merge request to the queue and wait for completion
///
/// This method submits a merge request to the background worker and
/// waits for the result. Merges are processed in FIFO order.
///
/// # Arguments
///
/// * `agent_id` - Unique identifier for the agent
/// * `branch_name` - Name of the branch to merge
/// * `item_id` - ID of the item being processed
/// * `env` - Execution environment with parent worktree context
///
/// # Returns
///
/// Result of the merge operation
pub async fn submit_merge(
&self,
agent_id: String,
branch_name: String,
item_id: String,
env: ExecutionEnvironment,
) -> MapReduceResult<()> {
let (response_tx, response_rx) = oneshot::channel();
let request = MergeRequest {
agent_id: agent_id.clone(),
branch_name,
item_id: item_id.clone(),
env,
response_tx,
};
// Submit request to queue
self.tx.send(request).map_err(|_| {
MapReduceError::ProcessingError(format!(
"Failed to submit merge request for agent {} (item {}): queue closed",
agent_id, item_id
))
})?;
// Wait for merge to complete
response_rx.await.map_err(|_| {
MapReduceError::ProcessingError(format!(
"Failed to receive merge result for agent {} (item {}): worker dropped response",
agent_id, item_id
))
})?
}
/// Get the number of pending merge requests in the queue
///
/// Note: This is an estimate and may not be exact due to concurrent access
#[allow(dead_code)]
pub fn pending_count(&self) -> usize {
// mpsc doesn't expose queue length, so we can't implement this without
// additional state tracking. For now, return 0 as a placeholder.
// We could add a counter if needed for observability.
0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cook::execution::mapreduce::resources::git::GitOperations;
use std::sync::Arc;
use std::time::Duration;
#[tokio::test]
async fn test_merge_queue_creation() {
let git_ops = Arc::new(GitOperations::new());
let _queue = MergeQueue::new(git_ops);
// Queue should be created without panic
}
#[tokio::test]
async fn test_merge_queue_closes_on_drop() {
let git_ops = Arc::new(GitOperations::new());
let queue = MergeQueue::new(git_ops);
// Drop the queue
drop(queue);
// Worker should shut down gracefully
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[tokio::test]
async fn test_submit_merge_fails_after_drop() {
let git_ops = Arc::new(GitOperations::new());
let queue = MergeQueue::new(git_ops);
// Drop the queue
drop(queue);
// This test can't actually call submit_merge because queue is dropped
// The test validates that dropping works without panic
}
// Note: Full integration tests with actual git operations are in
// the mapreduce integration test suite
}