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
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
#[cfg(feature = "test-utils")]
use std::path::{Path, PathBuf};

use crate::agents::AgentRegistry;
#[cfg(feature = "test-utils")]
use crate::app::effect::{AppEffect, AppEffectHandler, AppEffectResult};
#[cfg(feature = "test-utils")]
use crate::app::effect_handler::RealAppEffectHandler;
#[cfg(feature = "test-utils")]
use crate::app::runner::command_handlers::handle_plumbing_commands;
#[cfg(feature = "test-utils")]
use crate::app::runner::{validate_and_setup_agents, AgentSetupParams};

#[cfg(feature = "test-utils")]
fn set_current_dir_with_handler(
    handler: &mut dyn AppEffectHandler,
    path: &Path,
) -> anyhow::Result<()> {
    match handler.execute(AppEffect::SetCurrentDir {
        path: path.to_path_buf(),
    }) {
        AppEffectResult::Ok => Ok(()),
        AppEffectResult::Error(err) => anyhow::bail!("Failed to set working directory: {err}"),
        _ => Ok(()),
    }
}

#[cfg(feature = "test-utils")]
fn discover_repo_root_for_workspace(
    override_dir: Option<&Path>,
    handler: &mut dyn AppEffectHandler,
) -> anyhow::Result<PathBuf> {
    if let Some(dir) = override_dir {
        set_current_dir_with_handler(handler, dir)?;
        return Ok(dir.to_path_buf());
    }

    if let AppEffectResult::Error(err) = handler.execute(AppEffect::GitRequireRepo) {
        anyhow::bail!("Not in a git repository: {err}");
    }

    let root = match handler.execute(AppEffect::GitGetRepoRoot) {
        AppEffectResult::Path(path) => path,
        AppEffectResult::Error(err) => anyhow::bail!("Failed to get repo root: {err}"),
        _ => anyhow::bail!("Unexpected result from GitGetRepoRoot"),
    };
    set_current_dir_with_handler(handler, &root)?;
    Ok(root)
}
/// Test-only entry point that accepts a pre-built Config.
///
/// This function is for integration testing only. It bypasses environment variable
/// loading and uses the provided Config directly, enabling deterministic tests
/// that don't rely on process-global state.
///
/// This function handles ALL commands including early-exit commands (--init, --diagnose,
/// --reset-start-commit, etc.) so that tests can use a single entry point.
///
/// # Arguments
///
/// * `args` - The parsed CLI arguments
/// * `executor` - Process executor for external process execution
/// * `config` - Pre-built configuration (bypasses env var loading)
/// * `registry` - Pre-built agent registry
///
/// # Returns
///
/// Returns `Ok(())` on success or an error if any phase fails.
///
/// # Errors
///
/// Returns an error if:
/// - Agent validation fails
/// - Pipeline initialization fails
/// - Any pipeline phase execution fails
#[cfg(feature = "test-utils")]
pub fn run_with_config(
    args: Args,
    executor: std::sync::Arc<dyn ProcessExecutor>,
    config: crate::config::Config,
    registry: AgentRegistry,
) -> anyhow::Result<()> {
    // Use real path resolver and effect handler by default
    let mut handler = RealAppEffectHandler::new();
    run_with_config_and_resolver(
        args,
        executor,
        config,
        registry,
        &crate::config::RealConfigEnvironment,
        &mut handler,
        None, // Use default WorkspaceFs
    )
}

/// Test-only entry point that accepts a pre-built Config and a custom path resolver.
///
/// This function is for integration testing only. It bypasses environment variable
/// loading and uses the provided Config and path resolver directly, enabling
/// deterministic tests that don't rely on process-global state or env vars.
///
/// This function handles ALL commands including early-exit commands (--init, --diagnose,
/// --reset-start-commit, etc.) so that tests can use a single entry point.
///
/// # Arguments
///
/// * `args` - The parsed CLI arguments
/// * `executor` - Process executor for external process execution
/// * `config` - Pre-built configuration (bypasses env var loading)
/// * `registry` - Pre-built agent registry
/// * `path_resolver` - Custom path resolver for init commands
/// * `handler` - Effect handler for git/filesystem operations
/// * `workspace` - Optional workspace for file operations (if `None`, uses `WorkspaceFs`)
///
/// # Returns
///
/// Returns `Ok(())` on success or an error if any phase fails.
///
/// # Errors
///
/// Returns an error if:
/// - Agent validation fails
/// - Pipeline initialization fails
/// - Any pipeline phase execution fails
#[cfg(feature = "test-utils")]
pub fn run_with_config_and_resolver<P: crate::config::ConfigEnvironment, H: AppEffectHandler>(
    args: Args,
    executor: std::sync::Arc<dyn ProcessExecutor>,
    config: crate::config::Config,
    registry: AgentRegistry,
    path_resolver: &P,
    handler: &mut H,
    workspace: Option<std::sync::Arc<dyn crate::workspace::Workspace>>,
) -> anyhow::Result<()> {
    use crate::cli::{
        handle_extended_help, handle_init_global_with, handle_init_local_config_with,
        handle_list_work_guides, handle_smart_init_with,
    };

    let colors = Colors::new();
    let logger = Logger::new(colors);

    // Set working directory first if override is provided
    if let Some(ref override_dir) = args.working_dir_override {
        std::env::set_current_dir(override_dir)?;
    }

    // CRITICAL: Validate config files before any operations (fail-fast)
    // This ensures tests match production behavior where invalid config prevents startup
    // Per requirements: Ralph refuses to start pipeline if ANY config file has errors
    if let Err(e) =
        crate::config::loader::load_config_from_path_with_env(args.config.as_deref(), path_resolver)
    {
        eprintln!("{}", e.format_errors());
        return Err(anyhow::anyhow!("Configuration validation failed"));
    }

    // Handle --extended-help / --man flag: display extended help and exit.
    if args.recovery.extended_help {
        handle_extended_help();
        if args.work_guide_list.list_work_guides {
            println!();
            let _ = handle_list_work_guides(colors);
        }
        return Ok(());
    }

    // Handle --list-work-guides / --list-templates flag
    if args.work_guide_list.list_work_guides && handle_list_work_guides(colors) {
        return Ok(());
    }

    // Handle smart --init flag: intelligently determine what to initialize
    if args.unified_init.init.is_some()
        && handle_smart_init_with(
            args.unified_init.init.as_deref(),
            args.unified_init.force_init,
            colors,
            path_resolver,
        )?
    {
        return Ok(());
    }

    // Handle --init-config flag: explicit config creation and exit
    if args.unified_init.init_config && handle_init_global_with(colors, path_resolver)? {
        return Ok(());
    }

    // Handle --init-global flag: create unified config if it doesn't exist and exit
    if args.unified_init.init_global && handle_init_global_with(colors, path_resolver)? {
        return Ok(());
    }

    // Handle --init-local-config flag: create local project config and exit
    if args.unified_init.init_local_config
        && handle_init_local_config_with(colors, path_resolver, args.unified_init.force_init)?
    {
        return Ok(());
    }

    // Use provided config directly (no env var loading)
    let config_path = std::path::PathBuf::from("test-config");

    // Resolve required agent names
    let validated = resolve_required_agents(
        &config,
        &crate::app::config_init::AgentResolutionSources {
            local_config_path: None,
            global_config_path: Some(config_path.clone()),
            built_in_defaults: true,
        },
    )?;
    let developer_agent = validated.developer_agent;
    let reviewer_agent = validated.reviewer_agent;

    // Handle listing commands (these can run without git repo)
    if handle_listing_commands(&args, &registry, colors) {
        return Ok(());
    }

    // Handle --diagnose
    if args.recovery.diagnose {
        let diagnose_workspace = workspace
            .as_ref()
            .map(std::convert::AsRef::as_ref)
            .ok_or_else(|| anyhow::anyhow!("--diagnose requires workspace context"))?;
        handle_diagnose(
            &mut std::io::stdout(),
            colors,
            &config,
            &registry,
            crate::cli::ConfigInfo {
                path: &config_path,
                sources: &[],
            },
            &*executor,
            diagnose_workspace,
        );
        return Ok(());
    }

    let repo_root = workspace
        .as_ref()
        .map(|ws| ws.root().to_path_buf())
        .map_or_else(
            || discover_repo_root_for_workspace(args.working_dir_override.as_deref(), handler),
            Ok,
        )?;

    let workspace = workspace.unwrap_or_else(|| {
        std::sync::Arc::new(crate::workspace::WorkspaceFs::new(repo_root.clone()))
    });

    // Handle plumbing commands (--reset-start-commit, --show-commit-msg, etc.)
    // Pass workspace reference for testability with MemoryWorkspace
    if handle_plumbing_commands(&args, &logger, colors, handler, Some(workspace.as_ref()))? {
        return Ok(());
    }

    if !command_requires_prompt_setup(&args)
        && handle_repo_commands_without_prompt_setup(RepoCommandParams {
            args: &args,
            config: &config,
            registry: &registry,
            developer_agent: &developer_agent,
            reviewer_agent: &reviewer_agent,
            logger: &logger,
            colors,
            executor: &executor,
            app_handler: handler,
            repo_root: &repo_root,
            workspace: &workspace,
        })?
    {
        return Ok(());
    }

    if args.recovery.inspect_checkpoint {
        crate::app::resume::inspect_checkpoint(workspace.as_ref(), &logger)?;
        return Ok(());
    }

    // Validate agents and set up git repo and PROMPT.md
    let Some(repo_root) = validate_and_setup_agents(
        &AgentSetupParams {
            config: &config,
            registry: &registry,
            developer_agent: &developer_agent,
            reviewer_agent: &reviewer_agent,
            config_path: &config_path,
            colors,
            logger: &logger,
            working_dir_override: args.working_dir_override.as_deref(),
        },
        handler,
    )?
    else {
        return Ok(());
    };

    // Prepare pipeline context or exit early
    (prepare_pipeline_or_exit(PipelinePreparationParams {
        args,
        config,
        registry,
        developer_agent,
        reviewer_agent,
        repo_root,
        logger,
        colors,
        executor,
        handler,
        workspace,
    })?)
    .map_or_else(|| Ok(()), |ctx| run_pipeline(&ctx))
}

/// Parameters for `run_with_config_and_handlers`.
///
/// Groups related parameters to reduce function argument count.
#[cfg(feature = "test-utils")]
pub struct RunWithHandlersParams<'a, 'ctx, P, A, E>
where
    P: crate::config::ConfigEnvironment,
    A: AppEffectHandler,
    E: crate::reducer::EffectHandler<'ctx> + crate::app::StatefulHandler,
{
    pub args: Args,
    pub executor: std::sync::Arc<dyn ProcessExecutor>,
    pub config: crate::config::Config,
    pub registry: AgentRegistry,
    pub path_resolver: &'a P,
    pub app_handler: &'a mut A,
    pub effect_handler: &'a mut E,
    pub workspace: Option<std::sync::Arc<dyn crate::workspace::Workspace>>,
    /// Phantom data to bind the `'ctx` lifetime from `EffectHandler<'ctx>`.
    pub _marker: std::marker::PhantomData<&'ctx ()>,
}

/// Run with both `AppEffectHandler` AND `EffectHandler` for full isolation.
///
/// This function is the ultimate test entry point that allows injecting BOTH:
/// - `AppEffectHandler` for CLI-layer operations (git require repo, set cwd, etc.)
/// - `EffectHandler` for reducer-layer operations (create commit, run rebase, etc.)
///
/// Using both handlers ensures tests make ZERO real git calls at any layer.
///
/// # Example
///
/// ```ignore
/// use ralph_workflow::app::mock_effect_handler::MockAppEffectHandler;
/// use ralph_workflow::reducer::mock_effect_handler::MockEffectHandler;
///
/// let mut app_handler = MockAppEffectHandler::new().with_head_oid("abc123");
/// let mut effect_handler = MockEffectHandler::new(PipelineState::initial(1, 0));
///
/// run_with_config_and_handlers(RunWithHandlersParams {
///     args, executor, config, registry, path_resolver: &env,
///     app_handler: &mut app_handler, effect_handler: &mut effect_handler,
///     workspace: None,
/// })?;
///
/// // Verify no real git operations at either layer
/// assert!(app_handler.captured().iter().any(|e| matches!(e, AppEffect::GitRequireRepo)));
/// assert!(effect_handler.captured_effects().iter().any(|e| matches!(e, Effect::CreateCommit { .. })));
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - Agent validation fails
/// - Pipeline initialization fails
/// - Any pipeline phase execution fails
#[cfg(feature = "test-utils")]
pub fn run_with_config_and_handlers<'a, 'ctx, P, A, E>(
    params: RunWithHandlersParams<'a, 'ctx, P, A, E>,
) -> anyhow::Result<()>
where
    P: crate::config::ConfigEnvironment,
    A: AppEffectHandler,
    E: crate::reducer::EffectHandler<'ctx> + crate::app::StatefulHandler,
{
    use crate::cli::{
        handle_extended_help, handle_init_global_with, handle_init_local_config_with,
        handle_list_work_guides, handle_smart_init_with,
    };

    let RunWithHandlersParams {
        args,
        executor,
        config,
        registry,
        path_resolver,
        app_handler,
        effect_handler,
        workspace,
        ..
    } = params;

    let colors = Colors::new();
    let logger = Logger::new(colors);

    // Set working directory first if override is provided
    if let Some(ref override_dir) = args.working_dir_override {
        std::env::set_current_dir(override_dir)?;
    }

    // CRITICAL: Validate config files before any operations (fail-fast)
    // This ensures tests match production behavior where invalid config prevents startup
    // Per requirements: Ralph refuses to start pipeline if ANY config file has errors
    if let Err(e) =
        crate::config::loader::load_config_from_path_with_env(args.config.as_deref(), path_resolver)
    {
        eprintln!("{}", e.format_errors());
        return Err(anyhow::anyhow!("Configuration validation failed"));
    }

    // Handle --extended-help / --man flag
    if args.recovery.extended_help {
        handle_extended_help();
        if args.work_guide_list.list_work_guides {
            println!();
            let _ = handle_list_work_guides(colors);
        }
        return Ok(());
    }

    // Handle --list-work-guides / --list-templates flag
    if args.work_guide_list.list_work_guides && handle_list_work_guides(colors) {
        return Ok(());
    }

    // Handle smart --init flag
    if args.unified_init.init.is_some()
        && handle_smart_init_with(
            args.unified_init.init.as_deref(),
            args.unified_init.force_init,
            colors,
            path_resolver,
        )?
    {
        return Ok(());
    }

    // Handle --init-config flag
    if args.unified_init.init_config && handle_init_global_with(colors, path_resolver)? {
        return Ok(());
    }

    // Handle --init-global flag
    if args.unified_init.init_global && handle_init_global_with(colors, path_resolver)? {
        return Ok(());
    }

    // Handle --init-local-config flag: create local project config and exit
    if args.unified_init.init_local_config
        && handle_init_local_config_with(colors, path_resolver, args.unified_init.force_init)?
    {
        return Ok(());
    }

    // Use provided config directly
    let config_path = std::path::PathBuf::from("test-config");

    // Resolve required agent names
    let validated = resolve_required_agents(
        &config,
        &crate::app::config_init::AgentResolutionSources {
            local_config_path: None,
            global_config_path: Some(config_path.clone()),
            built_in_defaults: true,
        },
    )?;
    let developer_agent = validated.developer_agent;
    let reviewer_agent = validated.reviewer_agent;

    // Handle listing commands
    if handle_listing_commands(&args, &registry, colors) {
        return Ok(());
    }

    // Handle --diagnose
    if args.recovery.diagnose {
        let diagnose_workspace = workspace
            .as_ref()
            .map(std::convert::AsRef::as_ref)
            .ok_or_else(|| anyhow::anyhow!("--diagnose requires workspace context"))?;
        handle_diagnose(
            &mut std::io::stdout(),
            colors,
            &config,
            &registry,
            crate::cli::ConfigInfo {
                path: &config_path,
                sources: &[],
            },
            &*executor,
            diagnose_workspace,
        );
        return Ok(());
    }

    let repo_root = workspace
        .as_ref()
        .map(|ws| ws.root().to_path_buf())
        .map_or_else(
            || discover_repo_root_for_workspace(args.working_dir_override.as_deref(), app_handler),
            Ok,
        )?;

    let workspace = workspace.unwrap_or_else(|| {
        std::sync::Arc::new(crate::workspace::WorkspaceFs::new(repo_root.clone()))
    });

    // Handle plumbing commands with app_handler
    // Pass workspace reference for testability with MemoryWorkspace
    if handle_plumbing_commands(
        &args,
        &logger,
        colors,
        app_handler,
        Some(workspace.as_ref()),
    )? {
        return Ok(());
    }

    if !command_requires_prompt_setup(&args)
        && handle_repo_commands_without_prompt_setup(RepoCommandParams {
            args: &args,
            config: &config,
            registry: &registry,
            developer_agent: &developer_agent,
            reviewer_agent: &reviewer_agent,
            logger: &logger,
            colors,
            executor: &executor,
            app_handler,
            repo_root: &repo_root,
            workspace: &workspace,
        })?
    {
        return Ok(());
    }

    if args.recovery.inspect_checkpoint {
        crate::app::resume::inspect_checkpoint(workspace.as_ref(), &logger)?;
        return Ok(());
    }

    // Validate agents and set up git repo with app_handler
    let Some(repo_root) = validate_and_setup_agents(
        &AgentSetupParams {
            config: &config,
            registry: &registry,
            developer_agent: &developer_agent,
            reviewer_agent: &reviewer_agent,
            config_path: &config_path,
            colors,
            logger: &logger,
            working_dir_override: args.working_dir_override.as_deref(),
        },
        app_handler,
    )?
    else {
        return Ok(());
    };

    // Prepare pipeline context or exit early
    let ctx = prepare_pipeline_or_exit(PipelinePreparationParams {
        args,
        config,
        registry,
        developer_agent,
        reviewer_agent,
        repo_root,
        logger,
        colors,
        executor,
        handler: app_handler,
        workspace,
    })?;

    // Run pipeline with the injected effect_handler
    ctx.map_or_else(
        || Ok(()),
        |ctx| run_pipeline_with_effect_handler(&ctx, effect_handler),
    )
}