worktrunk 0.36.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
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
use std::path::{Path, PathBuf};

use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::CommandConfig;
use worktrunk::git::WorktrunkError;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
    eprintln, error_message, format_bash_with_gutter, progress_message, warning_message,
};

use super::command_executor::{
    CommandContext, PreparedCommand, PreparedStep, prepare_commands, prepare_steps,
};
use crate::commands::process::{HookLog, spawn_detached_exec};
use crate::output::execute_command_in_worktree;

/// A prepared command with its source information.
pub struct SourcedCommand {
    pub prepared: PreparedCommand,
    pub source: HookSource,
    pub hook_type: HookType,
    /// Path to display in announcement, if different from user's current directory.
    /// When `Some`, shows "@ path" suffix to clarify where the command runs.
    pub display_path: Option<PathBuf>,
}

impl SourcedCommand {
    /// Short name for summary display: "user:name" or just "user" if unnamed.
    fn summary_name(&self) -> String {
        match &self.prepared.name {
            Some(n) => format!("{}:{}", self.source, n),
            None => self.source.to_string(),
        }
    }

    /// Announce this command before execution.
    ///
    /// Format: "Running pre-merge user:foo" for named, "Running pre-start user hook" for unnamed
    /// When display_path is set, appends "@ path" to show where the command runs.
    fn announce(&self) -> anyhow::Result<()> {
        // Named: "Running post-switch user:foo" with "user:foo" bold
        // Unnamed: "Running post-switch user hook" with no bold
        let full_label = match &self.prepared.name {
            Some(n) => {
                let display_name = format!("{}:{}", self.source, n);
                crate::commands::format_command_label(
                    &self.hook_type.to_string(),
                    Some(&display_name),
                )
            }
            None => format!("Running {} {} hook", self.hook_type, self.source),
        };
        let message = match &self.display_path {
            Some(path) => {
                let path_display = format_path_for_display(path);
                cformat!("{full_label} @ <bold>{path_display}</>")
            }
            None => full_label,
        };
        eprintln!("{}", progress_message(message));
        eprintln!("{}", format_bash_with_gutter(&self.prepared.expanded));
        Ok(())
    }
}

/// Controls how hook execution should respond to failures.
#[derive(Clone, Copy)]
pub enum HookFailureStrategy {
    /// Stop on first failure and surface a `HookCommandFailed` error.
    FailFast,
    /// Log warnings and continue executing remaining commands.
    Warn,
}

// Re-export for backward compatibility with existing imports
pub use super::hook_filter::{HookSource, ParsedFilter};

/// Shared hook selection and rendering inputs for preparation/execution.
#[derive(Clone, Copy)]
pub struct HookCommandSpec<'cfg, 'vars, 'name, 'path> {
    pub user_config: Option<&'cfg CommandConfig>,
    pub project_config: Option<&'cfg CommandConfig>,
    pub hook_type: HookType,
    pub extra_vars: &'vars [(&'vars str, &'vars str)],
    pub name_filters: &'name [String],
    pub display_path: Option<&'path Path>,
}

/// Prepare hook commands from both user and project configs.
///
/// Collects commands from user config first, then project config, applying the name filter.
/// The filter supports source prefixes: `user:foo` or `project:foo` to run only from one source.
/// Returns a flat list of commands with source information for execution.
///
/// `display_path`: When `Some`, the path is shown in hook announcements (e.g., "@ ~/repo").
/// Use this when commands run in a different directory than where the user invoked the command.
pub fn prepare_hook_commands(
    ctx: &CommandContext,
    spec: HookCommandSpec<'_, '_, '_, '_>,
) -> anyhow::Result<Vec<SourcedCommand>> {
    let HookCommandSpec {
        user_config,
        project_config,
        hook_type,
        extra_vars,
        name_filters,
        display_path,
    } = spec;

    let parsed_filters: Vec<ParsedFilter<'_>> = name_filters
        .iter()
        .map(|f| ParsedFilter::parse(f))
        .collect();
    let mut commands = Vec::new();

    let display_path = display_path.map(|p| p.to_path_buf());

    // Process user config first, then project config (execution order)
    let sources = [
        (HookSource::User, user_config),
        (HookSource::Project, project_config),
    ];

    for (source, config) in sources {
        let Some(config) = config else { continue };

        // Skip if all filters specify a different source
        if !parsed_filters.is_empty() && !parsed_filters.iter().any(|f| f.matches_source(source)) {
            continue;
        }

        let prepared = prepare_commands(config, ctx, extra_vars, hook_type, source)?;
        let filtered = filter_by_name(prepared, &parsed_filters);
        commands.extend(filtered.into_iter().map(|p| SourcedCommand {
            prepared: p,
            source,
            hook_type,
            display_path: display_path.clone(),
        }));
    }

    Ok(commands)
}

/// Filter commands by name (returns empty vec if no names match).
/// Empty slice matches all commands. Each filter's name component is checked
/// independently — empty names (from `user:` or `project:`) match all commands
/// from that source (source filtering is handled by the caller).
fn filter_by_name(
    commands: Vec<PreparedCommand>,
    parsed_filters: &[ParsedFilter<'_>],
) -> Vec<PreparedCommand> {
    if parsed_filters.is_empty() {
        return commands; // No filters = match all
    }

    // Collect the non-empty name parts from filters
    let filter_names: Vec<&str> = parsed_filters
        .iter()
        .map(|f| f.name)
        .filter(|n| !n.is_empty())
        .collect();

    // If all filters have empty names (e.g., just "user:" or "project:"),
    // match all commands (source filtering already handled by caller)
    if filter_names.is_empty() {
        return commands;
    }

    commands
        .into_iter()
        .filter(|cmd| {
            cmd.name
                .as_deref()
                .is_some_and(|n| filter_names.contains(&n))
        })
        .collect()
}

/// A pipeline step with source information, for pipeline-aware execution.
pub struct SourcedStep {
    pub step: PreparedStep,
    pub source: HookSource,
    pub hook_type: HookType,
    pub display_path: Option<PathBuf>,
}

/// Format a summary description of a pipeline for display.
///
/// Named steps show as `source:name`; unnamed steps are collapsed into a single
/// `source ×N` count. Serial steps are separated by `;`, concurrent steps by `,`.
/// Example: "user:install; user:build, user:lint"
///
/// TODO: The `source:` prefix on named steps may be too verbose when only one
/// source is present (e.g., `user:bg` vs just `bg`). Consider prefixing only
/// when both user and project hooks exist for the same hook type.
fn format_pipeline_summary(steps: &[SourcedStep]) -> String {
    // All steps in a group share the same source.
    let source_label = steps[0].source.to_string();

    // Collect named labels per step (None = unnamed).
    let mut parts: Vec<String> = Vec::new();
    let mut unnamed_count: usize = 0;

    for step in steps {
        let step_names: Vec<Option<&str>> = match &step.step {
            PreparedStep::Single(cmd) => vec![cmd.name.as_deref()],
            PreparedStep::Concurrent(cmds) => cmds.iter().map(|c| c.name.as_deref()).collect(),
        };

        let named: Vec<_> = step_names
            .iter()
            .filter_map(|n| n.map(|name| cformat!("<bold>{source_label}:{name}</>")))
            .collect();
        unnamed_count += step_names.iter().filter(|n| n.is_none()).count();

        if !named.is_empty() {
            // Flush any pending unnamed count before named labels.
            if unnamed_count > 0 {
                parts.push(format_unnamed(&source_label, unnamed_count));
                unnamed_count = 0;
            }
            parts.push(named.join(", "));
        }
    }

    // Flush trailing unnamed count.
    if unnamed_count > 0 {
        parts.push(format_unnamed(&source_label, unnamed_count));
    }

    parts.join("; ")
}

fn format_unnamed(source_label: &str, count: usize) -> String {
    if count == 1 {
        cformat!("<bold>{source_label}</>")
    } else {
        cformat!("<bold>{source_label}</> ×{count}")
    }
}

/// Announce and spawn background hooks for one or more hook types.
///
/// Displays a single combined summary line covering all hook types, then
/// spawns each source group as an independent pipeline. Use this instead
/// of calling `spawn_hook_pipeline` directly when multiple hook types
/// fire together (e.g., post-switch + post-start on create).
///
/// Each pipeline carries its own `CommandContext` so that different hook types
/// can use different contexts (e.g., post-remove uses the removed branch while
/// post-switch uses the destination branch).
///
/// When `show_branch` is true, includes the branch name for disambiguation in batch
/// contexts (e.g., prune removing multiple worktrees):
/// `Running post-remove for feature: docs; post-switch for feature: zellij-tab`
///
/// Without `show_branch`: `Running post-switch: zellij-tab; post-start: deps, assets, docs`
pub fn announce_and_spawn_background_hooks(
    pipelines: Vec<(CommandContext<'_>, Vec<SourcedStep>)>,
    show_branch: bool,
) -> anyhow::Result<()> {
    let non_empty: Vec<_> = pipelines
        .into_iter()
        .filter(|(_, steps)| !steps.is_empty())
        .collect();
    if non_empty.is_empty() {
        return Ok(());
    }

    // Build combined summary, merging groups with the same hook type:
    // "post-switch: zellij-tab; post-start: deps, assets, docs"
    let display_path = non_empty
        .iter()
        .flat_map(|(_, g)| g.iter())
        .find_map(|s| s.display_path.as_ref());

    // Merge summaries by hook type so user+project for the same type
    // shows "post-start: user_bg, project" not "post-start: user_bg; post-start: project".
    let mut type_summaries: Vec<(HookType, Vec<String>)> = Vec::new();
    for (_, group) in &non_empty {
        let hook_type = group[0].hook_type;
        let summary = format_pipeline_summary(group);
        if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| *ht == hook_type) {
            entry.1.push(summary);
        } else {
            type_summaries.push((hook_type, vec![summary]));
        }
    }

    // In batch contexts (prune), use the first pipeline's branch for disambiguation.
    // This is the removed branch — it identifies the triggering event even for
    // post-switch hooks that fire as a consequence of the removal.
    let branch_suffix = if show_branch {
        non_empty
            .first()
            .and_then(|(ctx, _)| ctx.branch)
            .map(|b| cformat!(" for <bold>{b}</>"))
    } else {
        None
    };

    let combined: String = type_summaries
        .iter()
        .map(|(ht, summaries)| {
            let suffix = branch_suffix.as_deref().unwrap_or("");
            format!("{ht}{suffix}: {}", summaries.join(", "))
        })
        .collect::<Vec<_>>()
        .join("; ");
    let message = match display_path {
        Some(path) => {
            let path_display = format_path_for_display(path);
            cformat!("Running {combined} @ <bold>{path_display}</>")
        }
        None => format!("Running {combined}"),
    };
    eprintln!("{}", progress_message(message));

    for (ctx, group) in non_empty {
        spawn_hook_pipeline_quiet(&ctx, group)?;
    }

    Ok(())
}

/// Spawn a hook pipeline as a background `wt hook run-pipeline` process.
///
/// Displays a summary line and spawns the pipeline. For multiple hook types
/// that should share a single display line, use `announce_and_spawn_background_hooks`.
pub fn spawn_hook_pipeline(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {
    if steps.is_empty() {
        return Ok(());
    }

    let hook_type = steps[0].hook_type;
    let display_path = steps[0].display_path.as_ref();
    let summary = format_pipeline_summary(&steps);
    let message = match display_path {
        Some(path) => {
            let path_display = format_path_for_display(path);
            cformat!("Running {hook_type}: {summary} @ <bold>{path_display}</>")
        }
        None => format!("Running {hook_type}: {summary}"),
    };
    eprintln!("{}", progress_message(message));

    spawn_hook_pipeline_quiet(ctx, steps)
}

/// Spawn a hook pipeline without displaying a summary line.
///
/// Used by `announce_and_spawn_background_hooks` which handles display separately.
fn spawn_hook_pipeline_quiet(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {
    use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};

    let hook_type = steps[0].hook_type;
    let source = steps[0].source;

    // Extract base context from the first command. All steps share the same base context,
    // but per-step metadata (hook_name) is stripped — it gets injected per-step by the
    // background runner.
    let mut context: std::collections::HashMap<String, String> = steps
        .iter()
        .find_map(|s| match &s.step {
            PreparedStep::Single(cmd) => Some(&cmd.context_json),
            PreparedStep::Concurrent(cmds) => cmds.first().map(|c| &c.context_json),
        })
        .map(|json| serde_json::from_str(json).context("failed to deserialize context_json"))
        .transpose()?
        .unwrap_or_default();
    context.remove("hook_name");

    // Build pipeline spec from prepared steps. Use the raw template for lazy
    // steps (vars-referencing) and the expanded command for eager steps.
    let spec_steps: Vec<PipelineStepSpec> = steps
        .iter()
        .map(|s| match &s.step {
            PreparedStep::Single(cmd) => PipelineStepSpec::Single {
                name: cmd.name.clone(),
                template: cmd.lazy_template.as_ref().unwrap_or(&cmd.expanded).clone(),
            },
            PreparedStep::Concurrent(cmds) => PipelineStepSpec::Concurrent {
                commands: cmds
                    .iter()
                    .map(|c| PipelineCommandSpec {
                        name: c.name.clone(),
                        template: c.lazy_template.as_ref().unwrap_or(&c.expanded).clone(),
                    })
                    .collect(),
            },
        })
        .collect();

    let spec = PipelineSpec {
        worktree_path: ctx.worktree_path.to_path_buf(),
        branch: ctx.branch_or_head().to_string(),
        hook_type,
        source,
        context,
        steps: spec_steps,
        log_dir: ctx.repo.wt_logs_dir(),
    };

    let spec_json = serde_json::to_vec(&spec).context("failed to serialize pipeline spec")?;

    let wt_bin = std::env::current_exe().context("failed to resolve wt binary path")?;

    let hook_log = HookLog::hook(source, hook_type, "runner");
    let log_label = format!("{hook_type} {source} runner");

    if let Err(err) = spawn_detached_exec(
        ctx.repo,
        ctx.worktree_path,
        &wt_bin,
        &["hook", "run-pipeline"],
        ctx.branch_or_head(),
        &hook_log,
        &spec_json,
    ) {
        eprintln!(
            "{}",
            warning_message(format!("Failed to spawn pipeline: {err}"))
        );
    } else {
        let cmd_display = format!("{} hook run-pipeline", wt_bin.display());
        worktrunk::command_log::log_command(&log_label, &cmd_display, None, None);
    }

    Ok(())
}

/// Check if name filters were provided but no commands matched.
/// Returns an error listing available command names if so.
pub(crate) fn check_name_filter_matched(
    name_filters: &[String],
    total_commands_run: usize,
    user_config: Option<&CommandConfig>,
    project_config: Option<&CommandConfig>,
) -> anyhow::Result<()> {
    if !name_filters.is_empty() && total_commands_run == 0 {
        // Show the combined filter string in the error
        let filter_display = name_filters.join(", ");

        // Use the first filter to determine source scope for available commands,
        // but collect across all filters' source scopes
        let parsed_filters: Vec<ParsedFilter<'_>> = name_filters
            .iter()
            .map(|f| ParsedFilter::parse(f))
            .collect();
        let mut available = Vec::new();

        let sources = [
            (HookSource::User, user_config),
            (HookSource::Project, project_config),
        ];
        for (source, config) in sources {
            let Some(config) = config else { continue };
            // Include this source if any filter matches it
            if !parsed_filters.iter().any(|f| f.matches_source(source)) {
                continue;
            }
            available.extend(
                config
                    .commands()
                    .filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),
            );
        }

        return Err(worktrunk::git::GitError::HookCommandNotFound {
            name: filter_display,
            available,
        }
        .into());
    }
    Ok(())
}

/// Run user and project hooks for a given hook type.
///
/// This is the canonical implementation for running hooks from both sources.
/// Runs user hooks first, then project hooks sequentially. Handles name filtering
/// and returns an error if a name filter was provided but no matching command found.
///
/// `display_path`: Pass `ctx.hooks_display_path()` for automatic detection, or
/// explicit `Some(path)` when hooks run somewhere the user won't be cd'd to.
pub fn run_hook_with_filter(
    ctx: &CommandContext,
    spec: HookCommandSpec<'_, '_, '_, '_>,
    failure_strategy: HookFailureStrategy,
) -> anyhow::Result<()> {
    let commands = prepare_hook_commands(ctx, spec)?;
    let HookCommandSpec {
        user_config,
        project_config,
        hook_type,
        name_filters,
        ..
    } = spec;

    check_name_filter_matched(name_filters, commands.len(), user_config, project_config)?;

    if commands.is_empty() {
        return Ok(());
    }

    // Track first failure's exit code for Warn strategy (to propagate after all commands run)
    for cmd in commands {
        cmd.announce()?;

        // Lazy commands (referencing vars.) are expanded just before execution
        // so that vars set by earlier commands in the pipeline are available.
        let expanded = if let Some(ref template) = cmd.prepared.lazy_template {
            let name = cmd.summary_name();
            expand_lazy_template(template, &cmd.prepared.context_json, ctx.repo, &name)?
        } else {
            cmd.prepared.expanded.clone()
        };

        let log_label = format!("{} {}", cmd.hook_type, cmd.summary_name());
        if let Err(err) = execute_command_in_worktree(
            ctx.worktree_path,
            &expanded,
            Some(&cmd.prepared.context_json),
            Some(&log_label),
        ) {
            // Extract raw message and exit code from error
            let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
                match wt_err {
                    WorktrunkError::ChildProcessExited { message, code } => {
                        (message.clone(), Some(*code))
                    }
                    _ => (err.to_string(), None),
                }
            } else {
                (err.to_string(), None)
            };

            match &failure_strategy {
                HookFailureStrategy::FailFast => {
                    return Err(WorktrunkError::HookCommandFailed {
                        hook_type,
                        command_name: cmd.prepared.name.clone(),
                        error: err_msg,
                        exit_code,
                    }
                    .into());
                }
                HookFailureStrategy::Warn => {
                    let message = match &cmd.prepared.name {
                        Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),
                        None => format!("Command failed: {err_msg}"),
                    };
                    eprintln!("{}", error_message(message));
                }
            }
        }
    }

    Ok(())
}

/// Look up user and project configs for a given hook type.
pub(crate) fn lookup_hook_configs<'a>(
    user_hooks: &'a worktrunk::config::HooksConfig,
    project_config: Option<&'a worktrunk::config::ProjectConfig>,
    hook_type: HookType,
) -> (Option<&'a CommandConfig>, Option<&'a CommandConfig>) {
    (
        user_hooks.get(hook_type),
        project_config.and_then(|c| c.hooks.get(hook_type)),
    )
}

/// Run a hook type with automatic config lookup.
///
/// This is a convenience wrapper that:
/// 1. Loads project config from the repository
/// 2. Looks up user hooks from the config
/// 3. Calls `run_hook_with_filter` with the appropriate hook configs
/// 4. Adds the hook skip hint to errors
///
/// Use this instead of manually looking up configs and calling `run_hook_with_filter`.
pub fn execute_hook(
    ctx: &CommandContext,
    hook_type: HookType,
    extra_vars: &[(&str, &str)],
    failure_strategy: HookFailureStrategy,
    name_filters: &[String],
    display_path: Option<&Path>,
) -> anyhow::Result<()> {
    let project_config = ctx.repo.load_project_config()?;
    let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
    let (user_config, proj_config) =
        lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);

    run_hook_with_filter(
        ctx,
        HookCommandSpec {
            user_config,
            project_config: proj_config,
            hook_type,
            extra_vars,
            name_filters,
            display_path,
        },
        failure_strategy,
    )
    .map_err(worktrunk::git::add_hook_skip_hint)
}

/// Prepare background hooks with automatic config lookup.
///
/// Returns pipeline steps grouped by source — one group per source that has
/// hooks configured. Each group should be spawned as an independent pipeline
/// so that user and project hooks remain independent (a user hook failure
/// doesn't abort project hooks).
pub(crate) fn prepare_background_hooks(
    ctx: &CommandContext,
    hook_type: HookType,
    extra_vars: &[(&str, &str)],
    display_path: Option<&Path>,
) -> anyhow::Result<Vec<Vec<SourcedStep>>> {
    let project_config = ctx.repo.load_project_config()?;
    let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
    let (user_config, proj_config) =
        lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);

    let display_path = display_path.map(|p| p.to_path_buf());
    let mut groups = Vec::new();

    let sources = [
        (HookSource::User, user_config),
        (HookSource::Project, proj_config),
    ];

    for (source, config) in sources {
        let Some(config) = config else { continue };
        let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?;
        if steps.is_empty() {
            continue;
        }
        groups.push(
            steps
                .into_iter()
                .map(|step| SourcedStep {
                    step,
                    source,
                    hook_type,
                    display_path: display_path.clone(),
                })
                .collect(),
        );
    }

    Ok(groups)
}

/// Expand a lazy template using its command's context JSON.
///
/// Used by `run_hook_with_filter` (foreground) to expand templates that
/// reference `vars.*` at execution time. Background hooks handle lazy
/// expansion inside the pipeline runner process instead.
fn expand_lazy_template(
    template: &str,
    context_json: &str,
    repo: &worktrunk::git::Repository,
    label: &str,
) -> anyhow::Result<String> {
    let context_map: std::collections::HashMap<String, String> =
        serde_json::from_str(context_json).context("failed to deserialize context_json")?;
    let vars: std::collections::HashMap<&str, &str> = context_map
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    Ok(worktrunk::config::expand_template(
        template, &vars, true, repo, label,
    )?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ansi_str::AnsiStr;
    use insta::assert_snapshot;

    #[test]
    fn test_hook_source_display() {
        assert_eq!(HookSource::User.to_string(), "user");
        assert_eq!(HookSource::Project.to_string(), "project");
    }

    #[test]
    fn test_hook_failure_strategy_copy() {
        let strategy = HookFailureStrategy::FailFast;
        let copied = strategy; // Copy trait
        assert!(matches!(copied, HookFailureStrategy::FailFast));

        let warn = HookFailureStrategy::Warn;
        let copied_warn = warn;
        assert!(matches!(copied_warn, HookFailureStrategy::Warn));
    }

    #[test]
    fn test_parsed_filter() {
        // No prefix — matches all sources
        let f = ParsedFilter::parse("foo");
        assert!(f.source.is_none());
        assert_eq!(f.name, "foo");
        assert!(f.matches_source(HookSource::User));
        assert!(f.matches_source(HookSource::Project));

        // user: prefix
        let f = ParsedFilter::parse("user:foo");
        assert_eq!(f.source, Some(HookSource::User));
        assert_eq!(f.name, "foo");
        assert!(f.matches_source(HookSource::User));
        assert!(!f.matches_source(HookSource::Project));

        // project: prefix
        let f = ParsedFilter::parse("project:bar");
        assert_eq!(f.source, Some(HookSource::Project));
        assert_eq!(f.name, "bar");
        assert!(!f.matches_source(HookSource::User));
        assert!(f.matches_source(HookSource::Project));

        // Unknown prefix treated as name (colon in name)
        let f = ParsedFilter::parse("my:hook");
        assert!(f.source.is_none());
        assert_eq!(f.name, "my:hook");

        // Source-only (empty name matches all hooks from source)
        let f = ParsedFilter::parse("user:");
        assert_eq!(f.source, Some(HookSource::User));
        assert_eq!(f.name, "");
        let f = ParsedFilter::parse("project:");
        assert_eq!(f.source, Some(HookSource::Project));
        assert_eq!(f.name, "");
    }

    fn make_sourced_step(step: PreparedStep) -> SourcedStep {
        SourcedStep {
            step,
            source: HookSource::User,
            hook_type: worktrunk::HookType::PostStart,
            display_path: None,
        }
    }

    fn make_cmd(name: Option<&str>, expanded: &str) -> PreparedCommand {
        PreparedCommand {
            name: name.map(String::from),
            expanded: expanded.to_string(),
            context_json: "{}".to_string(),
            lazy_template: None,
        }
    }

    #[test]
    fn test_format_pipeline_summary_named() {
        let steps = vec![
            make_sourced_step(PreparedStep::Single(make_cmd(
                Some("install"),
                "npm install",
            ))),
            make_sourced_step(PreparedStep::Concurrent(vec![
                make_cmd(Some("build"), "npm run build"),
                make_cmd(Some("lint"), "npm run lint"),
            ])),
        ];
        let summary = format_pipeline_summary(&steps);
        assert_snapshot!(summary.ansi_strip(), @"user:install; user:build, user:lint");
    }

    #[test]
    fn test_format_pipeline_summary_unnamed() {
        let steps = vec![
            make_sourced_step(PreparedStep::Single(make_cmd(None, "npm install"))),
            make_sourced_step(PreparedStep::Single(make_cmd(None, "npm run build"))),
        ];
        let summary = format_pipeline_summary(&steps);
        assert_snapshot!(summary.ansi_strip(), @"user ×2");
    }

    #[test]
    fn test_format_pipeline_summary_mixed_named_unnamed() {
        let steps = vec![
            make_sourced_step(PreparedStep::Single(make_cmd(None, "npm install"))),
            make_sourced_step(PreparedStep::Single(make_cmd(Some("bg"), "npm run dev"))),
        ];
        let summary = format_pipeline_summary(&steps);
        assert_snapshot!(summary.ansi_strip(), @"user; user:bg");
    }

    #[test]
    fn test_format_pipeline_summary_single_unnamed() {
        let steps = vec![make_sourced_step(PreparedStep::Single(make_cmd(
            None,
            "npm install",
        )))];
        let summary = format_pipeline_summary(&steps);
        assert_snapshot!(summary.ansi_strip(), @"user");
    }

    #[test]
    fn test_format_pipeline_summary_concurrent_then_concurrent() {
        // The canonical pipeline: two concurrent groups in sequence.
        // post-start = [
        //     { install = "npm install", setup = "setup-db" },
        //     { build = "npm run build", lint = "npm run lint" },
        // ]
        let steps = vec![
            make_sourced_step(PreparedStep::Concurrent(vec![
                make_cmd(Some("install"), "npm install"),
                make_cmd(Some("setup"), "setup-db"),
            ])),
            make_sourced_step(PreparedStep::Concurrent(vec![
                make_cmd(Some("build"), "npm run build"),
                make_cmd(Some("lint"), "npm run lint"),
            ])),
        ];
        let summary = format_pipeline_summary(&steps);
        assert_snapshot!(summary.ansi_strip(), @"user:install, user:setup; user:build, user:lint");
    }

    #[test]
    fn test_is_pipeline() {
        use worktrunk::config::CommandConfig;

        let single = CommandConfig::single("npm install");
        assert!(!single.is_pipeline());
    }
}