ralph-workflow 0.7.18

PROMPT-driven multi-agent orchestrator for git repos
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
//! Agent role-specific invocation tests
//!
//! Tests invocation behavior for each agent role:
//! - Development agent prompt handling and errors
//! - Review agent prompt handling and errors
//! - Fix agent prompt handling and errors
//! - Commit agent prompt handling, errors, and uninitialized chain detection

use super::super::common::TestFixture;
use super::ReadFailingWorkspace;
use crate::agents::AgentRole;
use crate::executor::MockProcessExecutor;
use crate::reducer::boundary::MainEffectHandler;
use crate::reducer::event::{ErrorEvent, WorkspaceIoErrorKind};
use crate::reducer::state::{AgentChainState, CommitState, PipelineState};
use crate::workspace::MemoryWorkspace;
use std::path::PathBuf;
use std::sync::Arc;

#[test]
fn test_invoke_development_agent_returns_error_when_prompt_missing() {
    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx();
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    let err = handler
        .invoke_development_agent(&mut ctx, 0)
        .expect_err("invoke_development_agent should return error when prompt missing");

    assert!(
        err.to_string().contains("development prompt"),
        "Expected error about missing development prompt, got: {err}"
    );
}

#[test]
fn test_invoke_review_agent_returns_error_when_prompt_missing() {
    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx();
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.agent_chain = AgentChainState::initial()
        .with_agents(
            vec!["codex".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        )
        .with_drain(crate::agents::AgentDrain::Development);

    let err = handler
        .invoke_review_agent(&mut ctx, 0)
        .expect_err("invoke_review_agent should return error when prompt missing");

    assert!(
        err.to_string().contains("review prompt"),
        "Expected error about missing review prompt, got: {err}"
    );

    assert_eq!(
        handler.state.agent_chain.current_drain,
        crate::agents::AgentDrain::Development,
        "handler invocation must not repair routing by rewriting the active drain"
    );
}

#[test]
fn test_invoke_review_agent_maps_non_not_found_prompt_read_errors_to_workspace_read_failed() {
    let inner = MemoryWorkspace::new_test();
    let workspace = ReadFailingWorkspace::new(
        inner,
        PathBuf::from(".agent/tmp/review_prompt.txt"),
        std::io::ErrorKind::PermissionDenied,
    );

    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx_with_workspace(&workspace);
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    let err = handler
        .invoke_review_agent(&mut ctx, 0)
        .expect_err("invoke_review_agent should error on non-NotFound prompt read");

    let error_event = err
        .downcast_ref::<ErrorEvent>()
        .expect("error should preserve ErrorEvent for event-loop recovery");
    assert!(
        matches!(
            error_event,
            ErrorEvent::WorkspaceReadFailed {
                path,
                kind: WorkspaceIoErrorKind::PermissionDenied
            } if path == ".agent/tmp/review_prompt.txt"
        ),
        "expected WorkspaceReadFailed, got: {error_event:?}"
    );
}

#[test]
fn test_invoke_fix_agent_returns_error_when_prompt_missing() {
    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx();
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    let err = handler
        .invoke_fix_agent(&mut ctx, 0)
        .expect_err("invoke_fix_agent should return error when prompt missing");

    assert!(
        err.to_string().contains("fix prompt"),
        "Expected error about missing fix prompt, got: {err}"
    );
}

#[test]
fn test_invoke_fix_agent_maps_non_not_found_prompt_read_errors_to_workspace_read_failed() {
    let inner = MemoryWorkspace::new_test();
    let workspace = ReadFailingWorkspace::new(
        inner,
        PathBuf::from(".agent/tmp/fix_prompt.txt"),
        std::io::ErrorKind::PermissionDenied,
    );

    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx_with_workspace(&workspace);
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    let err = handler
        .invoke_fix_agent(&mut ctx, 0)
        .expect_err("invoke_fix_agent should error on non-NotFound prompt read");

    let error_event = err
        .downcast_ref::<ErrorEvent>()
        .expect("error should preserve ErrorEvent for event-loop recovery");
    assert!(
        matches!(
            error_event,
            ErrorEvent::WorkspaceReadFailed {
                path,
                kind: WorkspaceIoErrorKind::PermissionDenied
            } if path == ".agent/tmp/fix_prompt.txt"
        ),
        "expected WorkspaceReadFailed, got: {error_event:?}"
    );
}

#[test]
fn test_invoke_commit_agent_returns_error_when_prompt_missing() {
    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx();
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.commit = CommitState::Generating {
        attempt: 1,
        max_attempts: 2,
    };
    handler.state.agent_chain = AgentChainState::initial().with_agents(
        vec!["claude".to_string()],
        vec![vec![]],
        AgentRole::Commit,
    );

    let err = handler
        .invoke_commit_agent(&mut ctx)
        .expect_err("invoke_commit_agent should return error when prompt missing");

    assert!(
        err.to_string().contains("commit prompt"),
        "Expected error about missing commit prompt, got: {err}"
    );
}

#[test]
fn test_invoke_commit_agent_maps_non_not_found_prompt_read_errors_to_workspace_read_failed() {
    let inner = MemoryWorkspace::new_test();
    let workspace = ReadFailingWorkspace::new(
        inner,
        PathBuf::from(".agent/tmp/commit_prompt.txt"),
        std::io::ErrorKind::PermissionDenied,
    );

    let mut fixture = TestFixture::new();
    let mut ctx = fixture.ctx_with_workspace(&workspace);
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.commit = CommitState::Generating {
        attempt: 1,
        max_attempts: 2,
    };
    handler.state.agent_chain = AgentChainState::initial().with_agents(
        vec!["claude".to_string()],
        vec![vec![]],
        AgentRole::Commit,
    );

    let err = handler
        .invoke_commit_agent(&mut ctx)
        .expect_err("invoke_commit_agent should error on non-NotFound prompt read");

    let error_event = err
        .downcast_ref::<ErrorEvent>()
        .expect("error should preserve ErrorEvent for event-loop recovery");
    assert!(
        matches!(
            error_event,
            ErrorEvent::WorkspaceReadFailed {
                path,
                kind: WorkspaceIoErrorKind::PermissionDenied
            } if path == ".agent/tmp/commit_prompt.txt"
        ),
        "expected WorkspaceReadFailed, got: {error_event:?}"
    );
}

#[test]
fn test_invoke_commit_agent_surfaces_uninitialized_agent_chain_as_error_event() {
    let workspace = MemoryWorkspace::new_test()
        .with_file(".agent/tmp/commit_prompt.txt", "commit prompt content");
    let mut fixture = TestFixture::with_workspace(workspace);
    fixture.executor = Arc::new(MockProcessExecutor::new());
    let mut ctx = fixture.ctx();
    ctx.developer_agent = "claude";
    ctx.reviewer_agent = "codex";

    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.commit = CommitState::Generating {
        attempt: 1,
        max_attempts: 2,
    };
    // Intentionally leave the agent chain uninitialized/empty.
    handler.state.agent_chain = AgentChainState::initial();

    let err = handler
        .invoke_commit_agent(&mut ctx)
        .expect_err("invoke_commit_agent should return typed error when agent chain is empty");

    let error_event = err
        .downcast_ref::<ErrorEvent>()
        .expect("error should preserve ErrorEvent for event-loop recovery");
    assert!(
        matches!(
            error_event,
            ErrorEvent::CommitAgentNotInitialized { attempt: 1 }
        ),
        "expected CommitAgentNotInitialized, got: {error_event:?}"
    );

    // Defensive: ensure the error type is not a string-based anyhow error.
    assert!(
        !matches!(
            error_event,
            ErrorEvent::WorkspaceReadFailed {
                kind: WorkspaceIoErrorKind::Other,
                ..
            }
        ),
        "expected a specific invariant error, not a generic workspace error"
    );
}

#[test]
fn test_invoke_development_agent_uses_parser_type_from_agent_config() {
    use crate::agents::{AgentConfig, AgentDrain, AgentRegistry, JsonParserType};

    // Set up workspace with a development prompt.
    let workspace = MemoryWorkspace::new_test().with_file(
        ".agent/tmp/development_prompt.txt",
        "test development prompt",
    );
    let mut fixture = TestFixture::with_workspace(workspace);

    // Register a "test-codex" agent configured with the Codex parser.
    // Default (buggy) behaviour uses JsonParserType::Claude regardless of this config.
    let codex_config = AgentConfig {
        cmd: String::from("codex"),
        json_parser: JsonParserType::Codex,
        ..AgentConfig::default()
    };
    fixture.registry = AgentRegistry::new()
        .unwrap()
        .register("test-codex", codex_config);

    // Point the agent chain at "test-codex".
    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.agent_chain = AgentChainState::initial()
        .with_agents(
            vec!["test-codex".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        )
        .with_drain(AgentDrain::Development);

    // Clone the executor Arc so we can inspect it after the PhaseContext borrow ends.
    let executor = Arc::clone(&fixture.executor);

    {
        let mut ctx = fixture.ctx();
        ctx.developer_agent = "test-codex";
        // The mock executor returns success by default; ignore the result here.
        let _ = handler.invoke_development_agent(&mut ctx, 0);
    }

    let agent_calls = executor.agent_calls();
    assert_eq!(
        agent_calls.len(),
        1,
        "expected exactly one agent call, got {}",
        agent_calls.len()
    );
    assert_eq!(
        agent_calls[0].parser_type,
        JsonParserType::Codex,
        "expected parser_type to come from agent_config.json_parser (Codex), \
         got {:?} — hardcoded JsonParserType::default() (Claude) was used instead",
        agent_calls[0].parser_type
    );
}

#[test]
fn test_invoke_review_agent_uses_parser_type_from_agent_config() {
    use crate::agents::{AgentConfig, AgentDrain, AgentRegistry, JsonParserType};

    // Set up workspace with a review prompt.
    let workspace =
        MemoryWorkspace::new_test().with_file(".agent/tmp/review_prompt.txt", "test review prompt");
    let mut fixture = TestFixture::with_workspace(workspace);

    // Register a "test-opencode" agent configured with the OpenCode parser.
    // Default (buggy) behaviour uses JsonParserType::Claude regardless of this config.
    let opencode_config = AgentConfig {
        cmd: String::from("opencode"),
        json_parser: JsonParserType::OpenCode,
        ..AgentConfig::default()
    };
    fixture.registry = AgentRegistry::new()
        .unwrap()
        .register("test-opencode", opencode_config);

    // Point the agent chain at "test-opencode" with Review drain.
    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.agent_chain = AgentChainState::initial()
        .with_agents(
            vec!["test-opencode".to_string()],
            vec![vec![]],
            AgentRole::Reviewer,
        )
        .with_drain(AgentDrain::Review);

    // Clone the executor Arc so we can inspect it after the PhaseContext borrow ends.
    let executor = Arc::clone(&fixture.executor);

    {
        let mut ctx = fixture.ctx();
        ctx.reviewer_agent = "test-opencode";
        // The mock executor returns success by default; ignore the result here.
        let _ = handler.invoke_review_agent(&mut ctx, 0);
    }

    let agent_calls = executor.agent_calls();
    assert_eq!(
        agent_calls.len(),
        1,
        "expected exactly one agent call, got {}",
        agent_calls.len()
    );
    assert_eq!(
        agent_calls[0].parser_type,
        JsonParserType::OpenCode,
        "expected parser_type to come from agent_config.json_parser (OpenCode), \
         got {:?} — hardcoded JsonParserType::default() (Claude) was used instead",
        agent_calls[0].parser_type
    );
}

#[test]
fn test_invoke_fix_agent_uses_parser_type_from_agent_config() {
    use crate::agents::{AgentConfig, AgentDrain, AgentRegistry, JsonParserType};

    // Set up workspace with a fix prompt.
    let workspace =
        MemoryWorkspace::new_test().with_file(".agent/tmp/fix_prompt.txt", "test fix prompt");
    let mut fixture = TestFixture::with_workspace(workspace);

    // Register a "test-gemini" agent configured with the Gemini parser.
    // Default (buggy) behaviour uses JsonParserType::Claude regardless of this config.
    let gemini_config = AgentConfig {
        cmd: String::from("gemini"),
        json_parser: JsonParserType::Gemini,
        ..AgentConfig::default()
    };
    fixture.registry = AgentRegistry::new()
        .unwrap()
        .register("test-gemini", gemini_config);

    // Point the agent chain at "test-gemini" with Fix drain.
    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.agent_chain = AgentChainState::initial()
        .with_agents(
            vec!["test-gemini".to_string()],
            vec![vec![]],
            AgentRole::Reviewer,
        )
        .with_drain(AgentDrain::Fix);

    // Clone the executor Arc so we can inspect it after the PhaseContext borrow ends.
    let executor = Arc::clone(&fixture.executor);

    {
        let mut ctx = fixture.ctx();
        ctx.reviewer_agent = "test-gemini";
        // The mock executor returns success by default; ignore the result here.
        let _ = handler.invoke_fix_agent(&mut ctx, 0);
    }

    let agent_calls = executor.agent_calls();
    assert_eq!(
        agent_calls.len(),
        1,
        "expected exactly one agent call, got {}",
        agent_calls.len()
    );
    assert_eq!(
        agent_calls[0].parser_type,
        JsonParserType::Gemini,
        "expected parser_type to come from agent_config.json_parser (Gemini), \
         got {:?} — hardcoded JsonParserType::default() (Claude) was used instead",
        agent_calls[0].parser_type
    );
}

#[test]
fn test_invoke_development_agent_forwards_env_vars_from_agent_config() {
    use crate::agents::{AgentConfig, AgentDrain, AgentRegistry, JsonParserType};
    use std::collections::HashMap;

    // Set up workspace with a development prompt.
    let workspace = MemoryWorkspace::new_test().with_file(
        ".agent/tmp/development_prompt.txt",
        "test development prompt",
    );
    let mut fixture = TestFixture::with_workspace(workspace);

    // Register an agent with non-empty env_vars.
    // The bug (fixed in commit 643c0f60) ignored agent_config.env_vars entirely,
    // passing an empty map to the executor instead.
    let mut agent_env = HashMap::new();
    agent_env.insert("MY_AGENT_KEY".to_string(), "agent_value_42".to_string());
    let agent_config = AgentConfig {
        cmd: String::from("codex"),
        json_parser: JsonParserType::Codex,
        env_vars: agent_env,
        ..AgentConfig::default()
    };
    fixture.registry = AgentRegistry::new()
        .unwrap()
        .register("test-env-agent", agent_config);

    // Point the agent chain at "test-env-agent".
    let mut handler = MainEffectHandler::new(PipelineState::initial(1, 1));
    handler.state.agent_chain = AgentChainState::initial()
        .with_agents(
            vec!["test-env-agent".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        )
        .with_drain(AgentDrain::Development);

    let executor = Arc::clone(&fixture.executor);

    {
        let mut ctx = fixture.ctx();
        ctx.developer_agent = "test-env-agent";
        let _ = handler.invoke_development_agent(&mut ctx, 0);
    }

    let agent_calls = executor.agent_calls();
    assert_eq!(
        agent_calls.len(),
        1,
        "expected exactly one agent call, got {}",
        agent_calls.len()
    );
    assert!(
        agent_calls[0]
            .env
            .get("MY_AGENT_KEY")
            .map(|v| v == "agent_value_42")
            .unwrap_or(false),
        "expected agent_config.env_vars to be forwarded to the executor spawn config; \
         MY_AGENT_KEY not found or has wrong value in env: {:?}",
        agent_calls[0].env.get("MY_AGENT_KEY")
    );
}