Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Simplify hook and list task execution (#3964)
Maximilian Roos964533f89fae
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 012ca7888..4945cc53a 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -3,6 +3,7 @@ use std::path::{Path, PathBuf};use anyhow::Result;use color_print::cformat;+use serde::{Deserialize, Serialize};use worktrunk::HookType;use worktrunk::config::{Command, CommandConfig, HookStep, TemplateContext, UserConfig, VarScope, VarsMode,@@ -22,7 +23,7 @@ use super::hook_filter::HookSource;use crate::output::concurrent::{ConcurrentCommand, run_concurrent_commands};use crate::output::{DirectivePassthrough, execute_shell_command};-#[derive(Debug)]+#[derive(Debug, Serialize, Deserialize)]pub struct PreparedCommand {pub name: Option<String>,/// Raw template, rendered against `context` when the command runs.@@ -50,7 +51,7 @@ impl PreparedCommand {}/// A step in a prepared pipeline, mirroring `HookStep`.-#[derive(Debug)]+#[derive(Debug, Serialize, Deserialize)]pub enum PreparedStep {Single(PreparedCommand),Concurrent(Vec<PreparedCommand>),diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 3fc905a4b..6723869ba 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -425,7 +425,7 @@ fn run_hooks_background(};eprintln!("{}", progress_message(message));- for pipeline in &pipelines {+ for pipeline in pipelines {spawn_hook_pipeline_quiet(repo, pipeline)?;}@@ -477,54 +477,22 @@ fn print_background_variable_table(pipelines: &[PendingPipeline], hook_type: Hoo/// Spawn a hook pipeline without displaying a summary line.////// Used by `run_hooks_background` after the combined announcement is printed.-fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> anyhow::Result<()> {- use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};-- // Extract base context from the first command. Registration never adds an- // empty step group (asserted in `add_groups`), so `steps[0]` is safe;- // every step's first command carries the same base context (only- // `hook_name` differs per step — strip it so the runner re-injects per- // step).- let steps = &pipeline.steps;- let source = steps[0].source;- let first_cmd = &steps[0].step.commands()[0];- let mut context = first_cmd.context.clone();- context.remove("hook_name");-- // Build pipeline spec from prepared steps. The runner renders each raw- // template when its step runs (see `run_pipeline`'s "Template freshness").- let spec_steps: Vec<PipelineStepSpec> = steps- .iter()- .map(|s| match &s.step {- PreparedStep::Single(cmd) => PipelineStepSpec::Single {- name: cmd.name.clone(),- template_name: cmd.template_name.clone(),- template: cmd.template.clone(),- },- PreparedStep::Concurrent(cmds) => PipelineStepSpec::Concurrent {- commands: cmds- .iter()- .map(|c| PipelineCommandSpec {- name: c.name.clone(),- template_name: c.template_name.clone(),- template: c.template.clone(),- })- .collect(),- },- })- .collect();+fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: PendingPipeline) -> anyhow::Result<()> {+ use super::run_pipeline::PipelineSpec;++ // Registration never adds an empty step group (asserted in `add_groups`),+ // so `steps[0]` is safe.+ let source = pipeline.steps[0].source;// "HEAD" fallback matches `CommandContext::branch_or_head` for detached HEAD.- let branch = pipeline.branch.as_deref().unwrap_or("HEAD");+ let branch = pipeline.branch.unwrap_or_else(|| "HEAD".to_string());let hook_type = pipeline.hook_type;let spec = PipelineSpec {- worktree_path: pipeline.worktree_path.clone(),- branch: branch.to_string(),+ worktree_path: pipeline.worktree_path,+ branch,hook_type,source,- context,- steps: spec_steps,- log_dir: repo.wt_logs_dir(),+ steps: pipeline.steps.into_iter().map(|step| step.step).collect(),};let spec_json = serde_json::to_vec(&spec).context("failed to serialize pipeline spec")?;@@ -536,10 +504,10 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: &PendingPipeline) -> aif let Err(err) = spawn_detached_exec(repo,- &pipeline.worktree_path,+ &spec.worktree_path,&wt_bin,&["hook", "run-pipeline"],- branch,+ &spec.branch,&hook_log,&spec_json,) {diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex 8720ea12b..ed42fc4fd 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -2,7 +2,7 @@//!//! Contains the flat parallelism infrastructure://! - `WorkItem` - unit of work for the thread pool-//! - `dispatch_task()` - route TaskKind to the correct Task implementation+//! - `TaskKind::compute()` - route each task to its computation//! - `work_items_for_worktree()` / `work_items_for_branch()` - generate work items//! - `ExpectedResults` - track expected results for timeout diagnostics//! - `seed_skipped_task_defaults()` - conservative sentinels for skipped tasks@@ -26,12 +26,7 @@ use worktrunk::git::Repository;use super::super::model::{ListItem, UpstreamStatus, WorkingTreeStatus};use super::CollectOptions;-use super::tasks::{- AheadBehindTask, BranchDiffTask, CiStatusTask, CommittedTreesMatchTask, GitOperationTask,- HasFileChangesTask, IsAncestorTask, MergeTreeConflictsTask, SummaryGenerateTask, Task,- TaskContext, UpstreamTask, UrlStatusTask, UserMarkerTask, WorkingTreeConflictsTask,- WorkingTreeDiffTask, WouldMergeAddTask,-};+use super::tasks::TaskContext;use super::types::{TaskError, TaskKind, TaskResult};/// Tasks that require a valid commit SHA. Skipped for unborn branches (no commits yet).@@ -75,7 +70,7 @@ pub struct WorkItem {impl WorkItem {/// Execute this work item, returning the task result.pub fn execute(self) -> Result<TaskResult, TaskError> {- let result = dispatch_task(self.kind, self.ctx);+ let result = self.kind.compute(self.ctx);if let Ok(ref task_result) = result {debug_assert_eq!(TaskKind::from(task_result), self.kind);}@@ -83,27 +78,6 @@ impl WorkItem {}}-/// Dispatch a task by kind, calling the appropriate Task::compute().-fn dispatch_task(kind: TaskKind, ctx: TaskContext) -> Result<TaskResult, TaskError> {- match kind {- TaskKind::AheadBehind => AheadBehindTask::compute(ctx),- TaskKind::CommittedTreesMatch => CommittedTreesMatchTask::compute(ctx),- TaskKind::HasFileChanges => HasFileChangesTask::compute(ctx),- TaskKind::WouldMergeAdd => WouldMergeAddTask::compute(ctx),- TaskKind::IsAncestor => IsAncestorTask::compute(ctx),- TaskKind::BranchDiff => BranchDiffTask::compute(ctx),- TaskKind::WorkingTreeDiff => WorkingTreeDiffTask::compute(ctx),- TaskKind::MergeTreeConflicts => MergeTreeConflictsTask::compute(ctx),- TaskKind::WorkingTreeConflicts => WorkingTreeConflictsTask::compute(ctx),- TaskKind::GitOperation => GitOperationTask::compute(ctx),- TaskKind::UserMarker => UserMarkerTask::compute(ctx),- TaskKind::Upstream => UpstreamTask::compute(ctx),- TaskKind::CiStatus => CiStatusTask::compute(ctx),- TaskKind::UrlStatus => UrlStatusTask::compute(ctx),- TaskKind::SummaryGenerate => SummaryGenerateTask::compute(ctx),- }-}-// ============================================================================// Expected Results Tracking// ============================================================================@@ -363,7 +337,7 @@ pub fn work_items_for_worktree(// Send the URL through the drain channel so the row redraws as soon as// the result is processed. Without this round trip, the URL would only// appear when *some other* task happens to complete and trigger a- // refresh — often the slow `UrlStatusTask` itself.+ // refresh — often the slow URL-status task itself.if include_url && let Some(ref url) = item_url {expected_results.expect(item_idx, TaskKind::UrlStatus);let _ = tx.send(Ok(TaskResult::UrlStatus {@@ -399,8 +373,8 @@ pub fn work_items_for_worktree(TaskKind::UserMarker,TaskKind::WorkingTreeConflicts,TaskKind::BranchDiff,- // MergeTreeConflictsTask peeks the shared porcelain cache and- // skips its own merge-tree call when WorkingTreeConflictsTask+ // The merge-tree conflict task peeks the shared porcelain cache and+ // skips its own merge-tree call when the working-tree conflict task// will produce an authoritative dirty-tree result.TaskKind::MergeTreeConflicts,TaskKind::CiStatus,@@ -653,6 +627,6 @@ mod tests {// single authority, and `test_required_tasks_for_render` pins that the gate// drops SummaryGenerate when no LLM is configured. The spawn loop's "skip// what isn't planned" rule is covered by the UrlStatus test above. If a- // caller plans Summary without a command anyway, `SummaryGenerateTask`+ // caller plans Summary without a command anyway, the summary-generation task// returns a clean error rather than misbehaving (tasks.rs).}diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 626f75183..a6752d0b3 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -1510,7 +1510,7 @@ pub fn collect(// here on a cold cache is serial — it blocks this scope, and the// big task pool can't open until it returns. Nothing downstream of// work-item generation actually needs the ahead/behind *counts*- // (only the per-row `AheadBehindTask` reads them, and it has a+ // (only the per-row ahead/behind task reads them, and it has a// per-SHA fallback) — only the cheap `for-each-ref refs/heads/// refs/remotes/` ref scan gates work-item generation. So the walk// could become a single work item in the pool, overlapping the@@ -1542,7 +1542,7 @@ pub fn collect(// just gates on its data dependency.//// Scope to branches that will actually render an- // `UpstreamTask` row: with `--branches` that's every local;+ // Upstream-task row: with `--branches` that's every local;// without it that's just the worktree-attached subset.// Otherwise plain `wt list` on a repo with many stale// tracking branches would block the worker pool on a serialdiff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex c8fed77e6..fa1d3c716 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -1,7 +1,7 @@-//! Task trait and implementations.+//! Task computations and their shared context.//!-//! Contains the `Task` trait interface and all task implementations that-//! compute various git operations for worktrees and branches.+//! Each [`TaskKind`] dispatches here to one private computation over a shared+//! [`TaskContext`].use std::net::{SocketAddr, TcpStream};use std::time::Duration;@@ -60,7 +60,7 @@ pub struct TaskContext {pub branch_ref: worktrunk::git::BranchRef,pub item_idx: usize,/// Expanded URL for this item (from project config template).- /// UrlStatusTask uses this to check if the port is listening.+ /// The URL-status task uses this to check if the port is listening.pub item_url: Option<String>,/// LLM command for summary generation (from commit.generation config).pub llm_command: Option<String>,@@ -88,7 +88,7 @@ pub struct TaskContext {}impl TaskContext {- pub(super) fn error(&self, kind: TaskKind, err: &anyhow::Error) -> TaskError {+ fn error(&self, kind: TaskKind, err: &anyhow::Error) -> TaskError {// Check if any error in the chain is a timeoutlet is_timeout = err.chain().any(|e| {e.downcast_ref::<std::io::Error>()@@ -118,7 +118,7 @@ impl TaskContext {/// the type-level "Comparison bases" note). Returns `None` if the default/// branch cannot be determined, or if the persisted value is stale (see/// the `default_branch` field docs).- pub(super) fn default_branch(&self) -> Option<String> {+ fn default_branch(&self) -> Option<String> {self.default_branch.clone()}@@ -142,7 +142,7 @@ impl TaskContext {/// drift onto different bases. Falls back to the raw default branch name/// when integration targets could not be resolved (snapshot capture failed)/// so the columns still render in that degraded mode.- pub(super) fn comparison_base(&self) -> Option<&str> {+ fn comparison_base(&self) -> Option<&str> {select_comparison_base(self.integration_targets.as_ref(),self.default_branch.as_deref(),@@ -153,20 +153,20 @@ impl TaskContext {////// Used for integration checks (status symbols, safe deletion)./// Returns `None` if default branch cannot be determined or is stale.- pub(super) fn integration_targets(&self) -> Option<&IntegrationTargets> {+ fn integration_targets(&self) -> Option<&IntegrationTargets> {self.integration_targets.as_ref()}/// Captured ref state for this list invocation. Returns `None` when/// snapshot capture failed during pre-skeleton.- pub(super) fn snapshot(&self) -> Option<&RefSnapshot> {+ fn snapshot(&self) -> Option<&RefSnapshot> {self.snapshot.as_deref()}/// Resolve a ref name to its commit SHA via the snapshot, falling back/// to an uncached `git rev-parse` when the snapshot doesn't carry the/// ref (e.g., HEAD, raw SHAs, tags) or when no snapshot was captured.- pub(super) fn resolve_sha(&self, name: &str) -> anyhow::Result<String> {+ fn resolve_sha(&self, name: &str) -> anyhow::Result<String> {if let Some(snap) = self.snapshot()&& let Some(sha) = snap.resolve(name){@@ -183,7 +183,7 @@ impl TaskContext {/// the branch's full ref points at (so a rebase-in-progress doesn't/// compare against the transient HEAD); falls back to/// `branch_ref.commit_sha` for detached-HEAD items.- pub(super) fn branch_check_sha(&self) -> anyhow::Result<String> {+ fn branch_check_sha(&self) -> anyhow::Result<String> {if let Some(full_ref) = self.branch_ref.full_ref() {self.resolve_sha(full_ref)} else {@@ -193,143 +193,116 @@ impl TaskContext {}// ============================================================================-// Task Trait+// Task Computations// ============================================================================-/// A task that computes a single `TaskResult`.-///-/// Each task type has a compile-time `KIND` that determines which `TaskResult`-/// variant it produces. The `compute()` function receives a cloned context and-/// returns a Result - either the successful result or an error.-///-/// Tasks should propagate errors via `?` rather than swallowing them.-/// The drain layer handles defaults and collects errors for display.-pub trait Task: Send + Sync + 'static {- /// The kind of result this task produces (compile-time constant).- const KIND: TaskKind;-- /// Compute the task result. Called in a spawned thread.- /// Returns Ok(result) on success, Err(TaskError) on failure.- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError>;+impl TaskKind {+ /// Compute this task for one list item.+ pub(super) fn compute(self, ctx: TaskContext) -> Result<TaskResult, TaskError> {+ let result = match self {+ Self::AheadBehind => compute_ahead_behind(&ctx),+ Self::CommittedTreesMatch => compute_committed_trees_match(&ctx),+ Self::HasFileChanges => compute_has_file_changes(&ctx),+ Self::WouldMergeAdd => compute_would_merge_add(&ctx),+ Self::IsAncestor => compute_is_ancestor(&ctx),+ Self::BranchDiff => compute_branch_diff(&ctx),+ Self::WorkingTreeDiff => compute_working_tree_diff(&ctx),+ Self::MergeTreeConflicts => compute_merge_tree_conflicts(&ctx),+ Self::WorkingTreeConflicts => compute_working_tree_conflicts(&ctx),+ Self::GitOperation => compute_git_operation(&ctx),+ Self::UserMarker => compute_user_marker(&ctx),+ Self::Upstream => compute_upstream(&ctx),+ Self::CiStatus => compute_ci_status(&ctx),+ Self::UrlStatus => compute_url_status(&ctx),+ Self::SummaryGenerate => compute_summary_generate(&ctx),+ };+ result.map_err(|error| ctx.error(self, &error))+ }}-// ============================================================================-// Task Implementations-// ============================================================================--/// Task: Ahead/behind counts vs the mainline tip (informational stats).+/// Ahead/behind counts vs the mainline tip (informational stats).////// Measures against [`TaskContext::comparison_base`] — the upstream-aware/// default-branch tip — so a stale local default doesn't inflate the counts.-pub struct AheadBehindTask;+fn compute_ahead_behind(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When no comparison base resolves, return zero counts (cells show empty)+ let Some(base) = ctx.comparison_base() else {+ return Ok(TaskResult::AheadBehind {+ item_idx: ctx.item_idx,+ counts: AheadBehind::default(),+ is_orphan: false,+ });+ };+ let repo = &ctx.repo;-impl Task for AheadBehindTask {- const KIND: TaskKind = TaskKind::AheadBehind;+ let base_sha = ctx.resolve_sha(base)?;+ // Compare against the branch tip via its full ref when present —+ // see `branch_check_sha` for the rebase-in-progress rationale.+ let head_sha = ctx.branch_check_sha()?;- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When no comparison base resolves, return zero counts (cells show empty)- let Some(base) = ctx.comparison_base() else {- return Ok(TaskResult::AheadBehind {- item_idx: ctx.item_idx,- counts: AheadBehind::default(),- is_orphan: false,- });- };- let repo = &ctx.repo;-- let base_sha = ctx- .resolve_sha(base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- // Compare against the branch tip via its full ref when present —- // see `branch_check_sha` for the rebase-in-progress rationale.- let head_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;-- // Check for orphan branch (no common ancestor with default branch).- let is_orphan = repo- .merge_base_by_sha(&base_sha, &head_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?- .is_none();-- if is_orphan {- return Ok(TaskResult::AheadBehind {- item_idx: ctx.item_idx,- counts: AheadBehind::default(),- is_orphan: true,- });- }+ // Check for orphan branch (no common ancestor with default branch).+ let is_orphan = repo.merge_base_by_sha(&base_sha, &head_sha)?.is_none();- // Snapshot's ahead/behind batch is keyed by ref names — try the- // batched answer first, fall back to a per-pair query keyed by SHA.- let head_ref = ctx- .branch_ref- .full_ref()- .unwrap_or(&ctx.branch_ref.commit_sha);- let counts = ctx- .snapshot()- .and_then(|s| s.ahead_behind(base, head_ref))- .map(Ok)- .unwrap_or_else(|| repo.ahead_behind_by_sha(&base_sha, &head_sha))- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::AheadBehind {+ if is_orphan {+ return Ok(TaskResult::AheadBehind {item_idx: ctx.item_idx,- counts: AheadBehind {- ahead: counts.0,- behind: counts.1,- },- is_orphan: false,- })+ counts: AheadBehind::default(),+ is_orphan: true,+ });}++ // Snapshot's ahead/behind batch is keyed by ref names — try the+ // batched answer first, fall back to a per-pair query keyed by SHA.+ let head_ref = ctx+ .branch_ref+ .full_ref()+ .unwrap_or(&ctx.branch_ref.commit_sha);+ let counts = ctx+ .snapshot()+ .and_then(|s| s.ahead_behind(base, head_ref))+ .map(Ok)+ .unwrap_or_else(|| repo.ahead_behind_by_sha(&base_sha, &head_sha))?;++ Ok(TaskResult::AheadBehind {+ item_idx: ctx.item_idx,+ counts: AheadBehind {+ ahead: counts.0,+ behind: counts.1,+ },+ is_orphan: false,+ })}-/// Task 3: Tree identity check (does the item's commit tree match integration target's tree?)+/// Tree identity check (does the item's commit tree match the integration target's tree?).////// Uses target for integration detection (squash merge, rebase). When local/// and upstream have diverged, ORs across both — a tree match against either/// counts as integrated, matching `Repository::integration_reason`.-pub struct CommittedTreesMatchTask;--impl Task for CommittedTreesMatchTask {- const KIND: TaskKind = TaskKind::CommittedTreesMatch;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When integration_targets is None, return false (conservative: don't mark as integrated)- let Some(targets) = ctx.integration_targets() else {- return Ok(TaskResult::CommittedTreesMatch {- item_idx: ctx.item_idx,- committed_trees_match: false,- });- };- let repo = &ctx.repo;- // Resolve via snapshot — see `branch_check_sha` for the- // rebase-in-progress rationale.- let branch_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let primary_sha = ctx- .resolve_sha(&targets.primary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let mut committed_trees_match = repo- .trees_match_by_sha(&branch_sha, &primary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- if !committed_trees_match && let Some(secondary) = targets.secondary.as_deref() {- let secondary_sha = ctx- .resolve_sha(secondary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- committed_trees_match = repo- .trees_match_by_sha(&branch_sha, &secondary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- }- Ok(TaskResult::CommittedTreesMatch {+fn compute_committed_trees_match(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When integration_targets is None, return false (conservative: don't mark as integrated)+ let Some(targets) = ctx.integration_targets() else {+ return Ok(TaskResult::CommittedTreesMatch {item_idx: ctx.item_idx,- committed_trees_match,- })- }+ committed_trees_match: false,+ });+ };+ let repo = &ctx.repo;+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let branch_sha = ctx.branch_check_sha()?;+ let primary_sha = ctx.resolve_sha(&targets.primary)?;+ let mut committed_trees_match = repo.trees_match_by_sha(&branch_sha, &primary_sha)?;+ if !committed_trees_match && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx.resolve_sha(secondary)?;+ committed_trees_match = repo.trees_match_by_sha(&branch_sha, &secondary_sha)?;+ }+ Ok(TaskResult::CommittedTreesMatch {+ item_idx: ctx.item_idx,+ committed_trees_match,+ })}-/// Task 3b: File changes check (does branch have file changes beyond merge-base?)+/// File changes check (does the branch have file changes beyond merge-base?).////// Uses three-dot diff (`target...branch`) to detect if the branch has any file/// changes relative to the merge-base with target. Returns false when the diff@@ -340,57 +313,41 @@ impl Task for CommittedTreesMatchTask {/// that pulled in main, or commits whose changes were reverted.////// Uses target for integration detection.-pub struct HasFileChangesTask;--impl Task for HasFileChangesTask {- const KIND: TaskKind = TaskKind::HasFileChanges;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // No branch name (detached HEAD) - return conservative default (assume has changes)- if ctx.branch_ref.full_ref().is_none() {- return Ok(TaskResult::HasFileChanges {- item_idx: ctx.item_idx,- has_file_changes: true,- });- }- // When integration_targets is None, return true (conservative: assume has changes)- let Some(targets) = ctx.integration_targets() else {- return Ok(TaskResult::HasFileChanges {- item_idx: ctx.item_idx,- has_file_changes: true,- });- };- let repo = &ctx.repo;- // Resolve via snapshot. The branch is integrated (no added changes)- // if it has none against EITHER target — AND the per-target- // booleans so the combined value is false as soon as one side has- // nothing to add.- let branch_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let primary_sha = ctx- .resolve_sha(&targets.primary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let mut has_file_changes = repo- .has_added_changes_by_sha(&branch_sha, &primary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- if has_file_changes && let Some(secondary) = targets.secondary.as_deref() {- let secondary_sha = ctx- .resolve_sha(secondary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- has_file_changes = repo- .has_added_changes_by_sha(&branch_sha, &secondary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- }-- Ok(TaskResult::HasFileChanges {+fn compute_has_file_changes(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // No branch name (detached HEAD) - return conservative default (assume has changes)+ if ctx.branch_ref.full_ref().is_none() {+ return Ok(TaskResult::HasFileChanges {item_idx: ctx.item_idx,- has_file_changes,- })+ has_file_changes: true,+ });}+ // When integration_targets is None, return true (conservative: assume has changes)+ let Some(targets) = ctx.integration_targets() else {+ return Ok(TaskResult::HasFileChanges {+ item_idx: ctx.item_idx,+ has_file_changes: true,+ });+ };+ let repo = &ctx.repo;+ // Resolve via snapshot. The branch is integrated (no added changes)+ // if it has none against EITHER target — AND the per-target+ // booleans so the combined value is false as soon as one side has+ // nothing to add.+ let branch_sha = ctx.branch_check_sha()?;+ let primary_sha = ctx.resolve_sha(&targets.primary)?;+ let mut has_file_changes = repo.has_added_changes_by_sha(&branch_sha, &primary_sha)?;+ if has_file_changes && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx.resolve_sha(secondary)?;+ has_file_changes = repo.has_added_changes_by_sha(&branch_sha, &secondary_sha)?;+ }++ Ok(TaskResult::HasFileChanges {+ item_idx: ctx.item_idx,+ has_file_changes,+ })}-/// Task 3c: Merge simulation + patch-id fallback+/// Merge simulation + patch-id fallback.////// Delegates to [`Repository::merge_integration_probe_by_sha()`], which runs:///@@ -405,67 +362,53 @@ impl Task for HasFileChangesTask {/// conflicts — it needs the merge-tree result first. Splitting them into separate/// parallel tasks would either waste work (running patch-id unconditionally) or/// require two-phase scheduling.-pub struct WouldMergeAddTask;--impl Task for WouldMergeAddTask {- const KIND: TaskKind = TaskKind::WouldMergeAdd;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // No branch name (detached HEAD) - return conservative default (assume would add)- if ctx.branch_ref.full_ref().is_none() {- return Ok(TaskResult::WouldMergeAdd {- item_idx: ctx.item_idx,- would_merge_add: true,- is_patch_id_match: false,- });- }- // When integration_targets is None, return true (conservative: assume would add)- let Some(targets) = ctx.integration_targets() else {- return Ok(TaskResult::WouldMergeAdd {- item_idx: ctx.item_idx,- would_merge_add: true,- is_patch_id_match: false,- });- };- // Combine probes the same way `compute_integration_reason_uncached`- // ORs the two `check_integration` calls: a branch is integrated if- // merging would add nothing OR a patch-id matches against EITHER- // side. So `would_merge_add` ANDs (false on either ⇒ integrated)- // and `is_patch_id_match` ORs.- let branch_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let primary_sha = ctx- .resolve_sha(&targets.primary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let probe = ctx- .repo- .merge_integration_probe_by_sha(&branch_sha, &primary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let mut would_merge_add = probe.would_merge_add;- let mut is_patch_id_match = probe.is_patch_id_match;- if let Some(secondary) = targets.secondary.as_deref()- && (would_merge_add && !is_patch_id_match)- {- let secondary_sha = ctx- .resolve_sha(secondary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let alt = ctx- .repo- .merge_integration_probe_by_sha(&branch_sha, &secondary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- would_merge_add = would_merge_add && alt.would_merge_add;- is_patch_id_match = is_patch_id_match || alt.is_patch_id_match;- }- Ok(TaskResult::WouldMergeAdd {+fn compute_would_merge_add(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // No branch name (detached HEAD) - return conservative default (assume would add)+ if ctx.branch_ref.full_ref().is_none() {+ return Ok(TaskResult::WouldMergeAdd {item_idx: ctx.item_idx,- would_merge_add,- is_patch_id_match,- })+ would_merge_add: true,+ is_patch_id_match: false,+ });}+ // When integration_targets is None, return true (conservative: assume would add)+ let Some(targets) = ctx.integration_targets() else {+ return Ok(TaskResult::WouldMergeAdd {+ item_idx: ctx.item_idx,+ would_merge_add: true,+ is_patch_id_match: false,+ });+ };+ // Combine probes the same way `compute_integration_reason_uncached`+ // ORs the two `check_integration` calls: a branch is integrated if+ // merging would add nothing OR a patch-id matches against EITHER+ // side. So `would_merge_add` ANDs (false on either ⇒ integrated)+ // and `is_patch_id_match` ORs.+ let branch_sha = ctx.branch_check_sha()?;+ let primary_sha = ctx.resolve_sha(&targets.primary)?;+ let probe = ctx+ .repo+ .merge_integration_probe_by_sha(&branch_sha, &primary_sha)?;+ let mut would_merge_add = probe.would_merge_add;+ let mut is_patch_id_match = probe.is_patch_id_match;+ if let Some(secondary) = targets.secondary.as_deref()+ && (would_merge_add && !is_patch_id_match)+ {+ let secondary_sha = ctx.resolve_sha(secondary)?;+ let alt = ctx+ .repo+ .merge_integration_probe_by_sha(&branch_sha, &secondary_sha)?;+ would_merge_add = would_merge_add && alt.would_merge_add;+ is_patch_id_match = is_patch_id_match || alt.is_patch_id_match;+ }+ Ok(TaskResult::WouldMergeAdd {+ item_idx: ctx.item_idx,+ would_merge_add,+ is_patch_id_match,+ })}-/// Task 3d: Ancestor check (is branch HEAD an ancestor of integration target?)+/// Ancestor check (is branch HEAD an ancestor of the integration target?).////// Checks if branch is an ancestor of target - runs `git merge-base --is-ancestor`./// Returns true when the branch HEAD is in target's history (merged via fast-forward@@ -473,138 +416,99 @@ impl Task for WouldMergeAddTask {////// Uses target (target) for the Ancestor integration reason in `⊂`./// The `_` symbol uses ahead/behind counts (vs default_branch) instead.-pub struct IsAncestorTask;--impl Task for IsAncestorTask {- const KIND: TaskKind = TaskKind::IsAncestor;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When integration_targets is None, return false (conservative: don't mark as ancestor)- let Some(targets) = ctx.integration_targets() else {- return Ok(TaskResult::IsAncestor {- item_idx: ctx.item_idx,- is_ancestor: false,- });- };- let repo = &ctx.repo;- // Resolve via snapshot — see `branch_check_sha` for the- // rebase-in-progress rationale.- let branch_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let primary_sha = ctx- .resolve_sha(&targets.primary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let mut is_ancestor = repo- .is_ancestor_by_sha(&branch_sha, &primary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- if !is_ancestor && let Some(secondary) = targets.secondary.as_deref() {- let secondary_sha = ctx- .resolve_sha(secondary)- .map_err(|e| ctx.error(Self::KIND, &e))?;- is_ancestor = repo- .is_ancestor_by_sha(&branch_sha, &secondary_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- }-- Ok(TaskResult::IsAncestor {+fn compute_is_ancestor(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When integration_targets is None, return false (conservative: don't mark as ancestor)+ let Some(targets) = ctx.integration_targets() else {+ return Ok(TaskResult::IsAncestor {item_idx: ctx.item_idx,- is_ancestor,- })- }+ is_ancestor: false,+ });+ };+ let repo = &ctx.repo;+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let branch_sha = ctx.branch_check_sha()?;+ let primary_sha = ctx.resolve_sha(&targets.primary)?;+ let mut is_ancestor = repo.is_ancestor_by_sha(&branch_sha, &primary_sha)?;+ if !is_ancestor && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx.resolve_sha(secondary)?;+ is_ancestor = repo.is_ancestor_by_sha(&branch_sha, &secondary_sha)?;+ }++ Ok(TaskResult::IsAncestor {+ item_idx: ctx.item_idx,+ is_ancestor,+ })}-/// Task 4: Branch diff stats vs the mainline tip (informational stats).+/// Branch diff stats vs the mainline tip (informational stats).////// Measures against [`TaskContext::comparison_base`] — the upstream-aware/// default-branch tip — so a stale local default doesn't inflate the diff.-pub struct BranchDiffTask;--impl Task for BranchDiffTask {- const KIND: TaskKind = TaskKind::BranchDiff;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When no comparison base resolves, return empty diff (cells show empty)- let Some(base) = ctx.comparison_base() else {- return Ok(TaskResult::BranchDiff {- item_idx: ctx.item_idx,- branch_diff: BranchDiffTotals::default(),- });- };- let repo = &ctx.repo;- // Resolve via snapshot — see `branch_check_sha` for the- // rebase-in-progress rationale.- let base_sha = ctx- .resolve_sha(base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let head_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let diff = repo- .branch_diff_stats_by_sha(&base_sha, &head_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::BranchDiff {+fn compute_branch_diff(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When no comparison base resolves, return empty diff (cells show empty)+ let Some(base) = ctx.comparison_base() else {+ return Ok(TaskResult::BranchDiff {item_idx: ctx.item_idx,- branch_diff: BranchDiffTotals { diff },- })- }+ branch_diff: BranchDiffTotals::default(),+ });+ };+ let repo = &ctx.repo;+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let base_sha = ctx.resolve_sha(base)?;+ let head_sha = ctx.branch_check_sha()?;+ let diff = repo.branch_diff_stats_by_sha(&base_sha, &head_sha)?;++ Ok(TaskResult::BranchDiff {+ item_idx: ctx.item_idx,+ branch_diff: BranchDiffTotals { diff },+ })}-/// Task 5 (worktree only): Working tree diff + status flags+/// Working tree diff + status flags (worktree only).////// Runs `git status --porcelain` to get working tree status and computes diff stats.-pub struct WorkingTreeDiffTask;--impl Task for WorkingTreeDiffTask {- const KIND: TaskKind = TaskKind::WorkingTreeDiff;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .ok_or_else(|| ctx.error(Self::KIND, &anyhow::anyhow!("requires a worktree")))?;-- // Shared cache: WorkingTreeConflictsTask also needs porcelain. First- // accessor spawns the subprocess; second hits the cache. Uses- // --no-optional-locks to avoid index lock contention with `git write-tree`.- let status_output = wt- .status_porcelain_cached()- .map_err(|e| ctx.error(Self::KIND, &e))?;-- let (working_tree_status, is_dirty, has_conflicts) =- parse_working_tree_status(&status_output);-- // Only untracked entries need the temporary index. Tracked-only- // changes keep the ordinary tracked diff fast path.- let working_tree_diff = if !is_dirty {- LineDiff::default()- } else if working_tree_status.untracked {- wt.working_tree_diff_stats_with_untracked()- .map_err(|e| ctx.error(Self::KIND, &e))?- } else {- wt.working_tree_diff_stats()- .map_err(|e| ctx.error(Self::KIND, &e))?- };-- Ok(TaskResult::WorkingTreeDiff {- item_idx: ctx.item_idx,- working_tree_diff,- working_tree_status,- has_conflicts,- })- }+fn compute_working_tree_diff(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .ok_or_else(|| anyhow::anyhow!("requires a worktree"))?;++ // Shared cache: the working-tree conflict task also needs porcelain. First+ // accessor spawns the subprocess; second hits the cache. Uses+ // --no-optional-locks to avoid index lock contention with `git write-tree`.+ let status_output = wt.status_porcelain_cached()?;++ let (working_tree_status, is_dirty, has_conflicts) = parse_working_tree_status(&status_output);++ // Only untracked entries need the temporary index. Tracked-only+ // changes keep the ordinary tracked diff fast path.+ let working_tree_diff = if !is_dirty {+ LineDiff::default()+ } else if working_tree_status.untracked {+ wt.working_tree_diff_stats_with_untracked()?+ } else {+ wt.working_tree_diff_stats()?+ };++ Ok(TaskResult::WorkingTreeDiff {+ item_idx: ctx.item_idx,+ working_tree_diff,+ working_tree_status,+ has_conflicts,+ })}-/// Task 6: Potential merge conflicts check (merge-tree vs local main)+/// Potential merge conflicts check (merge-tree vs the local default branch).////// Uses default_branch (local main) for consistency with other Main subcolumn symbols./// Shows whether merging to your local main would conflict.////// **Skip-when-tracked-dirty optimization:** for worktree items, peek at the/// shared porcelain cache. When the worktree has tracked changes (and has no-/// unmerged entries), `WorkingTreeConflictsTask` will produce a+/// unmerged entries), the working-tree conflict task will produce a/// `Some(Some(_))` tracked-tree result that is authoritative for the WouldConflict tier/// (`tier_would_conflict` short-circuits on `Some(Some(_))` and ignores the/// HEAD probe). Returning@@ -615,54 +519,40 @@ impl Task for WorkingTreeDiffTask {////// Branch-only items have no working tree, so they fall through to the/// normal HEAD-vs-base merge-tree call.-pub struct MergeTreeConflictsTask;--impl Task for MergeTreeConflictsTask {- const KIND: TaskKind = TaskKind::MergeTreeConflicts;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return false (no conflicts can be detected)- let Some(base) = ctx.default_branch() else {+fn compute_merge_tree_conflicts(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When default_branch is None, return false (no conflicts can be detected)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::MergeTreeConflicts {+ item_idx: ctx.item_idx,+ has_merge_tree_conflicts: false,+ });+ };+ // Skip when tracked changes let the working-tree conflict task provide the+ // authoritative result. The unmerged path+ // returns `Some(None)` from that task, which falls+ // back to this HEAD probe.+ if let Some(wt) = ctx.branch_ref.working_tree(&ctx.repo) {+ let porcelain = wt.status_porcelain_cached()?;+ if has_tracked_changes(&porcelain) && !has_unmerged_entries(&porcelain) {return Ok(TaskResult::MergeTreeConflicts {item_idx: ctx.item_idx,has_merge_tree_conflicts: false,});- };- // Skip when tracked changes let WorkingTreeConflictsTask provide the- // authoritative result. The unmerged path- // returns `Some(None)` from WorkingTreeConflictsTask, which falls- // back to this HEAD probe.- if let Some(wt) = ctx.branch_ref.working_tree(&ctx.repo) {- let porcelain = wt- .status_porcelain_cached()- .map_err(|e| ctx.error(Self::KIND, &e))?;- if has_tracked_changes(&porcelain) && !has_unmerged_entries(&porcelain) {- return Ok(TaskResult::MergeTreeConflicts {- item_idx: ctx.item_idx,- has_merge_tree_conflicts: false,- });- }}- let repo = &ctx.repo;- // Resolve via snapshot — see `branch_check_sha` for the- // rebase-in-progress rationale.- let base_sha = ctx- .resolve_sha(&base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let head_sha = ctx- .branch_check_sha()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let has_merge_tree_conflicts = repo- .has_merge_conflicts_by_sha(&base_sha, &head_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::MergeTreeConflicts {- item_idx: ctx.item_idx,- has_merge_tree_conflicts,- })}+ let repo = &ctx.repo;+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let base_sha = ctx.resolve_sha(&base)?;+ let head_sha = ctx.branch_check_sha()?;+ let has_merge_tree_conflicts = repo.has_merge_conflicts_by_sha(&base_sha, &head_sha)?;+ Ok(TaskResult::MergeTreeConflicts {+ item_idx: ctx.item_idx,+ has_merge_tree_conflicts,+ })}-/// Task 6b (worktree only): Working tree conflict check+/// Working tree conflict check (worktree only).////// For worktrees with tracked changes, builds a tree SHA from the index plus/// unstaged tracked changes, then checks for merge conflicts against the@@ -671,187 +561,145 @@ impl Task for MergeTreeConflictsTask {////// Returns None if the working tree has no usable tracked snapshot (caller/// falls back to MergeTreeConflicts).-pub struct WorkingTreeConflictsTask;--impl Task for WorkingTreeConflictsTask {- const KIND: TaskKind = TaskKind::WorkingTreeConflicts;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return None (skip conflict check)- let Some(base) = ctx.default_branch() else {- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- };- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .ok_or_else(|| ctx.error(Self::KIND, &anyhow::anyhow!("requires a worktree")))?;-- // Shared cache with WorkingTreeDiffTask — single subprocess per worktree.- let status_output = wt- .status_porcelain_cached()- .map_err(|e| ctx.error(Self::KIND, &e))?;-- if !has_tracked_changes(&status_output) {- // A clean or untracked-only worktree uses the commit-based check.- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }-- // Unmerged entries (UU, AU, UA, DU, UD, DD, AA) mean a merge/rebase- // conflict is in progress. Fall back to the commit-based check to- // preserve prior behavior — write-tree on unmerged entries would- // produce a tree with conflict markers as content.- let has_unmerged = has_unmerged_entries(&status_output);- if has_unmerged {- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }-- // A staged-only snapshot needs only `write-tree` against a copy of the- // index. Unstaged tracked changes also run `add -u` against that copy so- // the user's staging state stays untouched. Untracked entries are- // ignored.- let has_unstaged_tracked_changes = status_output- .lines()- .any(|line| !line.starts_with("??") && line.as_bytes().get(1) != Some(&b' '));- let tree_sha = if has_unstaged_tracked_changes {- wt.write_tracked_worktree_tree()- .map_err(|e| ctx.error(Self::KIND, &e))?- } else {- wt.write_index_tree()- .map_err(|e| ctx.error(Self::KIND, &e))?- };-- let base_sha = ctx- .resolve_sha(&base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let has_conflicts = ctx- .repo- .has_merge_conflicts_by_tree_with_base_sha(- &base_sha,- &ctx.branch_ref.commit_sha,- &tree_sha,- )- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::WorkingTreeConflicts {+fn compute_working_tree_conflicts(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // When default_branch is None, return None (skip conflict check)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::WorkingTreeConflicts {item_idx: ctx.item_idx,- has_working_tree_conflicts: Some(has_conflicts),- })- }-}--/// Task 7 (worktree only): Git operation state detection (rebase, merge, …)-pub struct GitOperationTask;--impl Task for GitOperationTask {- const KIND: TaskKind = TaskKind::GitOperation;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .ok_or_else(|| ctx.error(Self::KIND, &anyhow::anyhow!("requires a worktree")))?;- let git_operation = wt- .operation_in_progress()- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::GitOperation {+ has_working_tree_conflicts: None,+ });+ };+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .ok_or_else(|| anyhow::anyhow!("requires a worktree"))?;++ // Shared cache with the working-tree diff task — single subprocess per worktree.+ let status_output = wt.status_porcelain_cached()?;++ if !has_tracked_changes(&status_output) {+ // A clean or untracked-only worktree uses the commit-based check.+ return Ok(TaskResult::WorkingTreeConflicts {item_idx: ctx.item_idx,- git_operation,- })+ has_working_tree_conflicts: None,+ });}-}--/// Task 8 (worktree only): User-defined status from git config-pub struct UserMarkerTask;--impl Task for UserMarkerTask {- const KIND: TaskKind = TaskKind::UserMarker;- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;- let user_marker = repo.user_marker(ctx.branch_ref.short_name());- Ok(TaskResult::UserMarker {+ // Unmerged entries (UU, AU, UA, DU, UD, DD, AA) mean a merge/rebase+ // conflict is in progress. Fall back to the commit-based check to+ // preserve prior behavior — write-tree on unmerged entries would+ // produce a tree with conflict markers as content.+ let has_unmerged = has_unmerged_entries(&status_output);+ if has_unmerged {+ return Ok(TaskResult::WorkingTreeConflicts {item_idx: ctx.item_idx,- user_marker,- })+ has_working_tree_conflicts: None,+ });}-}-/// Task 9: Upstream tracking status-pub struct UpstreamTask;+ // A staged-only snapshot needs only `write-tree` against a copy of the+ // index. Unstaged tracked changes also run `add -u` against that copy so+ // the user's staging state stays untouched. Untracked entries are+ // ignored.+ let has_unstaged_tracked_changes = status_output+ .lines()+ .any(|line| !line.starts_with("??") && line.as_bytes().get(1) != Some(&b' '));+ let tree_sha = if has_unstaged_tracked_changes {+ wt.write_tracked_worktree_tree()?+ } else {+ wt.write_index_tree()?+ };++ let base_sha = ctx.resolve_sha(&base)?;+ let has_conflicts = ctx.repo.has_merge_conflicts_by_tree_with_base_sha(+ &base_sha,+ &ctx.branch_ref.commit_sha,+ &tree_sha,+ )?;++ Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: Some(has_conflicts),+ })+}-impl Task for UpstreamTask {- const KIND: TaskKind = TaskKind::Upstream;+/// Git operation state detection (rebase, merge, …; worktree only).+fn compute_git_operation(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .ok_or_else(|| anyhow::anyhow!("requires a worktree"))?;+ let git_operation = wt.operation_in_progress()?;+ Ok(TaskResult::GitOperation {+ item_idx: ctx.item_idx,+ git_operation,+ })+}- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;+/// User-defined status from git config (worktree only).+fn compute_user_marker(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ let repo = &ctx.repo;+ let user_marker = repo.user_marker(ctx.branch_ref.short_name());+ Ok(TaskResult::UserMarker {+ item_idx: ctx.item_idx,+ user_marker,+ })+}- // No branch means no upstream- let Some(branch) = ctx.branch_ref.short_name() else {- return Ok(TaskResult::Upstream {- item_idx: ctx.item_idx,- upstream: UpstreamStatus::default(),- });- };+/// Upstream tracking status.+fn compute_upstream(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ let repo = &ctx.repo;- // Get upstream branch (None is valid - just means no upstream configured)- let upstream_branch = repo- .branch(branch)- .upstream()- .map_err(|e| ctx.error(Self::KIND, &e))?;- let Some(upstream_branch) = upstream_branch else {- return Ok(TaskResult::Upstream {- item_idx: ctx.item_idx,- upstream: UpstreamStatus::default(),- });- };+ // No branch means no upstream+ let Some(branch) = ctx.branch_ref.short_name() else {+ return Ok(TaskResult::Upstream {+ item_idx: ctx.item_idx,+ upstream: UpstreamStatus::default(),+ });+ };- let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());- // Resolve upstream ref to a SHA via the snapshot, then compute- // ahead/behind by SHA. Branch SHA is taken from `branch_ref.commit_sha`- // — for the upstream comparison we want the branch's actual tip,- // which `branch_ref.commit_sha` carries (snapshot tracks the same- // value for branch items via the for-each-ref scan).- //- // `ahead_behind_by_sha` is persistently cached (`ahead-behind/`- // SHA-keyed), so warm runs are pure reads. Cold runs are also- // primed up front: `Repository::prime_upstream_ahead_behind_cache`- // runs in the same post-skeleton `rayon::scope` as the snapshot- // capture and pre-fills the cache via one `for-each-ref- // %(ahead-behind:UPSTREAM_SHA)` walk per unique upstream — same- // shared-graph-traversal win that `capture_ahead_behind` uses for- // the `main↕` column. This per-row call then falls through to a- // cache read.- let upstream_sha = ctx- .resolve_sha(&upstream_branch)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let (ahead, behind) = repo- .ahead_behind_by_sha(&upstream_sha, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::Upstream {+ // Get upstream branch (None is valid - just means no upstream configured)+ let upstream_branch = repo.branch(branch).upstream()?;+ let Some(upstream_branch) = upstream_branch else {+ return Ok(TaskResult::Upstream {item_idx: ctx.item_idx,- upstream: UpstreamStatus {- remote,- upstream_short: Some(upstream_branch),- ahead,- behind,- },- })- }+ upstream: UpstreamStatus::default(),+ });+ };++ let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());+ // Resolve upstream ref to a SHA via the snapshot, then compute+ // ahead/behind by SHA. Branch SHA is taken from `branch_ref.commit_sha`+ // — for the upstream comparison we want the branch's actual tip,+ // which `branch_ref.commit_sha` carries (snapshot tracks the same+ // value for branch items via the for-each-ref scan).+ //+ // `ahead_behind_by_sha` is persistently cached (`ahead-behind/`+ // SHA-keyed), so warm runs are pure reads. Cold runs are also+ // primed up front: `Repository::prime_upstream_ahead_behind_cache`+ // runs in the same post-skeleton `rayon::scope` as the snapshot+ // capture and pre-fills the cache via one `for-each-ref+ // %(ahead-behind:UPSTREAM_SHA)` walk per unique upstream — same+ // shared-graph-traversal win that `capture_ahead_behind` uses for+ // the `main↕` column. This per-row call then falls through to a+ // cache read.+ let upstream_sha = ctx.resolve_sha(&upstream_branch)?;+ let (ahead, behind) = repo.ahead_behind_by_sha(&upstream_sha, &ctx.branch_ref.commit_sha)?;++ Ok(TaskResult::Upstream {+ item_idx: ctx.item_idx,+ upstream: UpstreamStatus {+ remote,+ upstream_short: Some(upstream_branch),+ ahead,+ behind,+ },+ })}-/// Task 10: CI/PR status+/// CI/PR status.////// Always checks for open PRs/MRs regardless of upstream tracking./// For branch workflow/pipeline fallback (no PR), requires upstream tracking@@ -860,98 +708,76 @@ impl Task for UpstreamTask {/// Remote branches (e.g., "origin/feature") are treated as having upstream/// by definition - they ARE the upstream. This enables workflow/pipeline/// fallback for remote-only branches shown via `wt list --remotes`.-pub struct CiStatusTask;--impl Task for CiStatusTask {- const KIND: TaskKind = TaskKind::CiStatus;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;- let pr_status = CiBranchName::from_branch_ref(&ctx.branch_ref)- .and_then(|ci_branch| PrStatus::detect(repo, &ci_branch, &ctx.branch_ref.commit_sha));-- Ok(TaskResult::CiStatus {- item_idx: ctx.item_idx,- pr_status,- })- }+fn compute_ci_status(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ let repo = &ctx.repo;+ let pr_status = CiBranchName::from_branch_ref(&ctx.branch_ref)+ .and_then(|ci_branch| PrStatus::detect(repo, &ci_branch, &ctx.branch_ref.commit_sha));++ Ok(TaskResult::CiStatus {+ item_idx: ctx.item_idx,+ pr_status,+ })}-/// Task 13: URL health check (port availability).+/// URL health check (port availability).////// The URL itself is sent immediately after template expansion (in spawning code)/// so it appears in normal styling right away. This task only checks if the port/// is listening, and if not, the URL dims.-pub struct UrlStatusTask;--impl Task for UrlStatusTask {- const KIND: TaskKind = TaskKind::UrlStatus;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // URL already sent in spawning code; this task only checks port availability- let Some(ref url) = ctx.item_url else {- return Ok(TaskResult::UrlStatus {- item_idx: ctx.item_idx,- url: None,- active: None,- });- };-- // Parse port from URL and check if it's listening- // Skip health check in tests to avoid flaky results from random local processes- let active = if std::env::var("WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK").is_ok() {- Some(false)- } else {- parse_port_from_url(url).map(|port| {- // Quick TCP connect check with 50ms timeout- let addr = SocketAddr::from(([127, 0, 0, 1], port));- TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()- })- };-- // Return only active status (url=None to avoid overwriting the already-sent URL)- Ok(TaskResult::UrlStatus {+fn compute_url_status(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ // URL already sent in spawning code; this task only checks port availability+ let Some(ref url) = ctx.item_url else {+ return Ok(TaskResult::UrlStatus {item_idx: ctx.item_idx,url: None,- active,+ active: None,+ });+ };++ // Parse port from URL and check if it's listening+ // Skip health check in tests to avoid flaky results from random local processes+ let active = if std::env::var("WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK").is_ok() {+ Some(false)+ } else {+ parse_port_from_url(url).map(|port| {+ // Quick TCP connect check with 50ms timeout+ let addr = SocketAddr::from(([127, 0, 0, 1], port));+ TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()})- }-}--/// Task 14: LLM-generated branch summary (`--full` + `[list] summary = true` + LLM command)-pub struct SummaryGenerateTask;--impl Task for SummaryGenerateTask {- const KIND: TaskKind = TaskKind::SummaryGenerate;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let Some(ref llm_command) = ctx.llm_command else {- return Err(ctx.error(- Self::KIND,- &anyhow::anyhow!("SummaryGenerateTask requires llm_command"),- ));- };+ };- let branch = ctx.branch_ref.short_name().unwrap_or("(detached)");- let worktree_path = ctx.branch_ref.worktree_path();-- let summary = crate::summary::generate_summary_core(- branch,- &ctx.branch_ref.commit_sha,- worktree_path,- llm_command,- &ctx.repo,- )- .map_err(|e| ctx.error(Self::KIND, &e))?;-- // Extract subject line (first line) for the table column- let subject = summary.as_deref().map(first_line);+ // Return only active status (url=None to avoid overwriting the already-sent URL)+ Ok(TaskResult::UrlStatus {+ item_idx: ctx.item_idx,+ url: None,+ active,+ })+}- Ok(TaskResult::SummaryGenerate {- item_idx: ctx.item_idx,- summary: subject,- })- }+/// LLM-generated branch summary (`--full` + `[list] summary = true` + LLM command).+fn compute_summary_generate(ctx: &TaskContext) -> anyhow::Result<TaskResult> {+ let Some(ref llm_command) = ctx.llm_command else {+ anyhow::bail!("summary generation requires an LLM command");+ };++ let branch = ctx.branch_ref.short_name().unwrap_or("(detached)");+ let worktree_path = ctx.branch_ref.worktree_path();++ let summary = crate::summary::generate_summary_core(+ branch,+ &ctx.branch_ref.commit_sha,+ worktree_path,+ llm_command,+ &ctx.repo,+ )?;++ // Extract subject line (first line) for the table column+ let subject = summary.as_deref().map(first_line);++ Ok(TaskResult::SummaryGenerate {+ item_idx: ctx.item_idx,+ summary: subject,+ })}// ============================================================================@@ -1065,6 +891,50 @@ fn has_tracked_changes(status_output: &str) -> bool {#[cfg(test)]mod tests {use super::*;+ use worktrunk::git::BranchRef;+ use worktrunk::testing::TestRepo;++ fn task_context(test: &TestRepo) -> TaskContext {+ TaskContext {+ repo: test.repo.clone(),+ branch_ref: BranchRef::local_branch("feature", "deadbeef"),+ item_idx: 3,+ item_url: None,+ llm_command: None,+ default_branch: None,+ integration_targets: None,+ snapshot: None,+ }+ }++ #[test]+ fn url_status_without_url_is_inert() {+ let test = TestRepo::new();++ let result = TaskKind::UrlStatus.compute(task_context(&test)).unwrap();++ assert!(matches!(+ result,+ TaskResult::UrlStatus {+ item_idx: 3,+ url: None,+ active: None,+ }+ ));+ }++ #[test]+ fn summary_without_command_keeps_task_identity() {+ let test = TestRepo::new();++ let error = TaskKind::SummaryGenerate+ .compute(task_context(&test))+ .unwrap_err();++ assert_eq!(error.item_idx, 3);+ assert_eq!(error.kind, TaskKind::SummaryGenerate);+ assert_eq!(error.message, "summary generation requires an LLM command");+ }#[test]fn test_first_line_simple() {diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rsindex 396e164d4..1c06e1179 100644--- a/src/commands/list/json_v2.rs+++ b/src/commands/list/json_v2.rs@@ -764,7 +764,7 @@ fn json_default_branch(item: &ListItem, worktree_data: Option<&WorktreeData>) ->// integrated: the probes run on the committed HEAD regardless)// - no match with every signal loaded → absent (determined not-integrated)// - any signal unloaded, or seeded on skip → null (undetermined)- // Orphans get sentinel counts `{0, 0}` from `AheadBehindTask` (there is+ // Orphans get sentinel counts `{0, 0}` from the ahead/behind task (there is// no merge-base to count against — the table short-circuits them at its// orphan tier for the same reason). Guard both readings of the counts:// the sentinel is not a same-commit match, and 0/0 is not a real@@ -1134,7 +1134,7 @@ mod tests {#[test]fn test_orphan_sentinel_counts_do_not_fabricate_integration() {- // AheadBehindTask reports orphans with sentinel counts {0, 0}; the+ // The ahead/behind task reports orphans with sentinel counts {0, 0}; the// sentinel must not read as a same-commit match nor as real counts.let mut item = item_with("orphan");item.is_orphan = Some(true);diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rsindex 22d42efe3..14cffabbb 100644--- a/src/commands/list/model/state.rs+++ b/src/commands/list/model/state.rs@@ -327,7 +327,7 @@ pub fn tier_orphan(is_orphan: Option<bool>) -> Tier<MainState> {/// result reflects the tracked working state better than the HEAD-only probe./// When `has_working_tree_conflicts` is/// `Some(Some(b))`, fire/rule out on `b` and ignore the HEAD probe.-/// `MergeTreeConflictsTask` skips its merge-tree call in that case to+/// The merge-tree conflict task skips its merge-tree call in that case to/// avoid a redundant subprocess (returning a sentinel `false` that this/// gate ignores).///@@ -802,7 +802,7 @@ mod tests {Tier::RuledOut);// WT probe is authoritative: rule out even when HEAD probe was- // skipped (None) because MergeTreeConflictsTask deferred to it.+ // skipped (None) because the merge-tree conflict task deferred to it.assert_eq!(tier_would_conflict(None, Some(Some(false)), true),Tier::RuledOut@@ -816,7 +816,7 @@ mod tests {// WT probe is authoritative: rule out even when HEAD probe says// "would conflict" (uncommitted changes resolve it). This// combination shouldn't arise in production — the- // `MergeTreeConflictsTask` skip-when-dirty path keeps HEAD as a+ // The merge-tree conflict task's skip-when-dirty path keeps HEAD as a// sentinel `false` whenever WT is `Some(Some(_))` — but pin the// contract so a future refactor that reorders the matches// doesn't silently regress.diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex c75d8ba1c..2a4fb8784 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -18,7 +18,6 @@ pub(crate) mod init;pub(crate) mod list;pub(crate) mod merge;pub(crate) mod picker;-pub(crate) mod pipeline_spec;pub(crate) mod process;pub(crate) mod project_config;mod relocate;diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 6b5e3871f..24398da87 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -737,7 +737,7 @@ pub(super) struct LocalContent {summary_working_tree: Option<bool>,/// `branch_diff`: the branch has commits ahead of the mainline tip/// (`counts.ahead > 0`), or it is an orphan (no merge base — see- /// [`Self::from_item`]). `counts` is `AheadBehindTask`'s answer, measured+ /// [`Self::from_item`]). `counts` is the ahead/behind task's answer, measured/// against the **upstream-aware** comparison base/// (`TaskContext::comparison_base` — the upstream ref when the local default/// lags it), so a stale fork default doesn't inflate it. The branch-diff anddiff --git a/src/commands/pipeline_spec.rs b/src/commands/pipeline_spec.rsdeleted file mode 100644index 2f4d6fa31..000000000--- a/src/commands/pipeline_spec.rs+++ /dev/null@@ -1,125 +0,0 @@-use serde::{Deserialize, Serialize};-use std::path::PathBuf;--use worktrunk::HookType;-use worktrunk::config::TemplateContext;--use super::hook_filter::HookSource;--/// Serialized specification for a background pipeline.-///-/// Serialized to JSON and piped to stdin of `wt hook run-pipeline`.-/// Contains raw templates — expansion happens at execution time in-/// the background process.-#[derive(Serialize, Deserialize)]-pub struct PipelineSpec {- pub worktree_path: PathBuf,- pub branch: String,- pub hook_type: HookType,- pub source: HookSource,- /// Base context variables for template expansion.- pub context: TemplateContext,- pub steps: Vec<PipelineStepSpec>,- /// Directory for per-command log files.- ///- /// The pipeline runner creates one log file per command here,- /// named via `HookLog::hook(source, hook_type, name)`.- pub log_dir: PathBuf,-}--#[derive(Serialize, Deserialize)]-pub enum PipelineStepSpec {- Single {- name: Option<String>,- /// Label for template-expansion errors, copied from- /// `PreparedCommand::template_name` so runner-log errors read the- /// same as foreground ones (`"Failed to expand user:foo: …"`).- /// Command-failure messages instead use `name`, mirroring the- /// foreground's `HookCommandFailed { command_name }`.- template_name: String,- template: String,- },- Concurrent {- commands: Vec<PipelineCommandSpec>,- },-}--#[derive(Serialize, Deserialize)]-pub struct PipelineCommandSpec {- pub name: Option<String>,- /// See `PipelineStepSpec::Single::template_name`.- pub template_name: String,- pub template: String,-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_pipeline_spec_roundtrip() {- let mut context = TemplateContext::default();- context.insert("branch", "feature/auth");- let spec = PipelineSpec {- worktree_path: "/tmp/test-worktree".into(),- branch: "feature/auth".into(),- hook_type: HookType::PostCreate,- source: HookSource::User,- context,- log_dir: "/tmp/test-worktree/.git/wt/logs".into(),- steps: vec![- PipelineStepSpec::Single {- name: Some("install".into()),- template_name: "user:install".into(),- template: "npm install".into(),- },- PipelineStepSpec::Concurrent {- commands: vec![- PipelineCommandSpec {- name: Some("build".into()),- template_name: "user:build".into(),- template: "npm run build".into(),- },- PipelineCommandSpec {- name: None,- template_name: "user post-create hook".into(),- template: "echo {{ vars.tag }}".into(),- },- ],- },- ],- };-- let json = serde_json::to_string(&spec).unwrap();- let roundtripped: PipelineSpec = serde_json::from_str(&json).unwrap();-- assert_eq!(roundtripped.worktree_path, spec.worktree_path);- assert_eq!(roundtripped.branch, spec.branch);- assert_eq!(roundtripped.hook_type, spec.hook_type);- assert_eq!(roundtripped.source, spec.source);- assert_eq!(roundtripped.context, spec.context);- assert_eq!(roundtripped.steps.len(), 2);-- // Verify step structure survives roundtrip- match &roundtripped.steps[0] {- PipelineStepSpec::Single {- name,- template_name,- template,- } => {- assert_eq!(name.as_deref(), Some("install"));- assert_eq!(template_name, "user:install");- assert_eq!(template, "npm install");- }- _ => panic!("expected Single step"),- }- match &roundtripped.steps[1] {- PipelineStepSpec::Concurrent { commands } => {- assert_eq!(commands.len(), 2);- assert_eq!(commands[0].name.as_deref(), Some("build"));- assert!(commands[1].template.contains("vars.tag"));- }- _ => panic!("expected Concurrent step"),- }- }-}diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rsindex f9b02efb1..79f8e9814 100644--- a/src/commands/run_pipeline.rs+++ b/src/commands/run_pipeline.rs@@ -31,13 +31,13 @@//! git config, so order matters for `vars.*`), so a later command's expansion//! can run after an earlier command's child has already started.//!-//! **Stdin**: every child receives the spec's context as JSON on stdin,+//! **Stdin**: every child receives its prepared context as JSON on stdin,//! matching the foreground hook convention. Commands that don't read stdin//! ignore it.//!//! ## Template freshness//!-//! The spec carries two kinds of template input:+//! Each prepared command carries two kinds of template input://!//! - **Base context** (`branch`, `commit`, `worktree_path`, …) — snapshotted//! once when the parent builds the spec. A step that creates a new commit@@ -54,30 +54,47 @@//! Template values are shell-escaped at expansion time (`shell_escape=true`)//! since the expanded string is passed to a shell for interpretation.-use std::borrow::Cow;use std::fs;use std::io::Read as _;-use std::path::Path;+use std::path::{Path, PathBuf};use std::process::{Child, ExitStatus, Stdio};use anyhow::Context;+use serde::{Deserialize, Serialize};-use worktrunk::config::TemplateContext;+use worktrunk::HookType;use worktrunk::git::{Repository, WorktrunkError};use worktrunk::shell_exec::{ShellConfig, scrub_git_discovery_env_vars};use worktrunk::trace::CommandTrace;-use super::command_executor::{expand_shell_template, wait_first_error};-use super::pipeline_spec::{PipelineSpec, PipelineStepSpec};+use super::command_executor::{+ PreparedCommand, PreparedStep, expand_shell_template, wait_first_error,+};+use super::hook_filter::HookSource;use super::process::HookLog;+/// Serialized specification for a background hook pipeline.+///+/// The envelope carries pipeline-wide execution metadata. Its steps use the+/// same prepared command model as foreground execution, so selection and+/// context preparation have one representation on both sides of the process+/// boundary.+#[derive(Serialize, Deserialize)]+pub(super) struct PipelineSpec {+ pub worktree_path: PathBuf,+ pub branch: String,+ pub hook_type: HookType,+ pub source: HookSource,+ pub steps: Vec<PreparedStep>,+}+/// Run a serialized pipeline from stdin.////// This is the entry point for `wt hook run-pipeline`./// The orchestrator is a long-lived background process spawned by/// `spawn_detached_exec`; stdout/stderr are already redirected to a log file.///-/// Each command's output is written to its own log file in `spec.log_dir`,+/// Each command's output is written to its own repository log file,/// named `{branch}-{source}-{hook_type}-{name}.log`. The runner process's/// own stdout/stderr captures only runner-level errors.pub fn run_pipeline() -> anyhow::Result<()> {@@ -92,33 +109,33 @@ pub fn run_pipeline() -> anyhow::Result<()> {let repo =Repository::at(&spec.worktree_path).context("failed to open repository for pipeline")?;- fs::create_dir_all(&spec.log_dir)- .with_context(|| format!("failed to create log directory: {}", spec.log_dir.display()))?;+ let log_dir = repo.wt_logs_dir();+ fs::create_dir_all(&log_dir)+ .with_context(|| format!("failed to create log directory: {}", log_dir.display()))?;let mut cmd_index = 0usize;for step in &spec.steps {match step {- PipelineStepSpec::Single {- template,- template_name,- name,- } => {- let log_name = command_log_name(name.as_deref(), cmd_index);- let log_file = create_command_log(&spec, &log_name)?;- let step_ctx = step_context(&spec.context, name.as_deref());- let expanded = expand_shell_template(template, &step_ctx, &repo, template_name)?;- let step_json = step_ctx.to_json();+ PreparedStep::Single(cmd) => {+ let log_name = command_log_name(cmd.name.as_deref(), cmd_index);+ let log_file = create_command_log(&spec, &log_dir, &log_name)?;+ let expanded =+ expand_shell_template(&cmd.template, &cmd.context, &repo, &cmd.template_name)?;+ let step_json = cmd.context_json();let (mut child, mut trace) =spawn_shell_command(&expanded, &spec.worktree_path, &step_json, log_file)?;let status = wait_resolving(&mut child, &mut trace, &expanded)?;if !status.success() {- return Err(failure_error(&status, name.as_deref().unwrap_or(&expanded)));+ return Err(failure_error(+ &status,+ cmd.name.as_deref().unwrap_or(&expanded),+ ));}cmd_index += 1;}- PipelineStepSpec::Concurrent { commands } => {- run_concurrent_group(commands, &spec, &repo, &mut cmd_index)?;+ PreparedStep::Concurrent(commands) => {+ run_concurrent_group(commands, &spec, &repo, &log_dir, &mut cmd_index)?;}}}@@ -126,21 +143,6 @@ pub fn run_pipeline() -> anyhow::Result<()> {Ok(())}-/// Build a per-step context, injecting `hook_name` when the step has a name.-///-/// The shared pipeline context has `hook_name` stripped (it varies per step).-/// Returns a `Cow` so unnamed steps borrow the base context without cloning.-fn step_context<'a>(base: &'a TemplateContext, name: Option<&str>) -> Cow<'a, TemplateContext> {- match name {- Some(n) => {- let mut ctx = base.clone();- ctx.insert("hook_name", n);- Cow::Owned(ctx)- }- None => Cow::Borrowed(base),- }-}-/// Spawn a shell command with context JSON piped to stdin.////// Uses `ShellConfig` for portable shell detection (Git Bash on Windows,@@ -222,9 +224,10 @@ fn wait_resolving(/// running every child to completion (the test hatch is for ordering, not/// error semantics).fn run_concurrent_group(- commands: &[super::pipeline_spec::PipelineCommandSpec],+ commands: &[PreparedCommand],spec: &PipelineSpec,repo: &Repository,+ log_dir: &Path,cmd_index: &mut usize,) -> anyhow::Result<()> {let serial = super::force_serial_concurrent();@@ -238,11 +241,10 @@ fn run_concurrent_group(let spawn_result = (|| -> anyhow::Result<()> {for cmd in commands {let log_name = command_log_name(cmd.name.as_deref(), *cmd_index);- let log_file = create_command_log(spec, &log_name)?;- let cmd_ctx = step_context(&spec.context, cmd.name.as_deref());+ let log_file = create_command_log(spec, log_dir, &log_name)?;let expanded =- expand_shell_template(&cmd.template, &cmd_ctx, repo, &cmd.template_name)?;- let cmd_json = cmd_ctx.to_json();+ expand_shell_template(&cmd.template, &cmd.context, repo, &cmd.template_name)?;+ let cmd_json = cmd.context_json();let (mut child, mut trace) =spawn_shell_command(&expanded, &spec.worktree_path, &cmd_json, log_file)?;*cmd_index += 1;@@ -292,12 +294,12 @@ fn command_log_name(name: Option<&str>, index: usize) -> String {}}-/// Create a per-command log file in the spec's log directory.+/// Create a per-command log file in the repository's log directory.///-/// Caller must ensure `spec.log_dir` exists (created once at pipeline startup).-fn create_command_log(spec: &PipelineSpec, name: &str) -> anyhow::Result<fs::File> {+/// Caller must ensure `log_dir` exists (created once at pipeline startup).+fn create_command_log(spec: &PipelineSpec, log_dir: &Path, name: &str) -> anyhow::Result<fs::File> {let hook_log = HookLog::hook(spec.source, spec.hook_type, name);- let path = hook_log.path(&spec.log_dir, &spec.branch);+ let path = hook_log.path(log_dir, &spec.branch);fs::File::create(&path).with_context(|| format!("failed to create log file: {}", path.display()))}diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex ef28d21a1..1e1ce6ee4 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -398,7 +398,7 @@ impl Repository {/// In-memory front over a persistent disk back/// (`merge-base/{min}-{max}.json`): the `DashMap` dedups within one/// process, the disk cache serves re-runs without re-forking. The- /// `wt list` orphan check (`AheadBehindTask`) calls this once per row+ /// The `wt list` orphan check calls this once per row/// even when the ahead/behind counts are themselves cache-warm, so on a/// repo with many branches the disk back turns that per-row/// `git merge-base` fork into a file read. Content-addressed, neverdiff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rsindex 8fd2f3814..07ee3996c 100644--- a/src/git/repository/ref_snapshot.rs+++ b/src/git/repository/ref_snapshot.rs@@ -19,7 +19,7 @@//! %(ahead-behind:BASE)` batch walk (git ≥ 2.36) when the cache is cold//! for this base, seeding the cache from the batch so later runs are pure//! reads. Branches that moved since the last run are left out of the-//! snapshot map — the per-branch `AheadBehindTask` recomputes (and+//! snapshot map — the per-branch ahead/behind task recomputes (and//! caches) those by SHA in the parallel pool.//!//! # Lifetime@@ -137,7 +137,7 @@ impl Repository {/// cached (a fresh repo, after `wt config state clear`, or branches/// that moved since their last write) the misses are filled by:/// - a few misses → left out of the map; the per-branch- /// `AheadBehindTask` recomputes (and caches) them by SHA in the+ /// ahead/behind task recomputes (and caches) them by SHA in the/// parallel pool;/// - everything cold → one unscoped `for-each-ref %(ahead-behind)/// refs/heads/` walk, results written to the cache;@@ -304,7 +304,7 @@ impl Repository {/// `parse_local_branch_line`), are skipped: nothing to cache. Each/// per-upstream group below the same threshold/// `capture_ahead_behind` uses for the cold-subset batch is also- /// skipped — the per-row `UpstreamTask` will recompute those by SHA+ /// skipped — the per-row upstream task will recompute those by SHA/// in the parallel pool, which beats blocking the pool on a small/// serial batch. Unlike [`Self::capture_refs_with_ahead_behind`]/// there is no "all cold → unscoped walk" shortcut: each upstream@@ -360,7 +360,7 @@ impl Repository {}// Partition cold vs warm by probing the SHA cache. Warm pairs- // need no work — the per-row `UpstreamTask` reads them in+ // need no work — the per-row upstream task reads them in// parallel via `ahead_behind_by_sha`.let mut cold_by_upstream: HashMap<String, Vec<String>> = HashMap::new();for (branch_ref, branch_sha, upstream_sha) in &candidates {diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 669513785..2f224734c 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -476,7 +476,7 @@ impl<'a> WorkingTree<'a> {/// each want porcelain (e.g., working-tree diff + conflict detection during/// `wt list`) share a single subprocess. Uses `--no-optional-locks` to avoid/// index-lock contention with the `git write-tree` run by- /// `WorkingTreeConflictsTask` in parallel. Explicitly requests normal+ /// the working-tree conflict task in parallel. Explicitly requests normal/// untracked-file reporting so `status.showUntrackedFiles=no` cannot make/// an untracked-only worktree look clean to callers.pub fn status_porcelain_cached(&self) -> anyhow::Result<String> {@@ -1066,7 +1066,7 @@ impl<'a> WorkingTree<'a> {/// operations there. Today the callers are/// [`WorkingTree::working_tree_diff_stats_with_untracked`] (HEAD± with/// untracked, used by list and statusline),-/// `WorkingTreeConflictsTask` (write-tree of tracked changes, for+/// the working-tree conflict task (write-tree of tracked changes, for/// merge-conflict probing), `wt step diff` (diff vs target merge-base with/// untracked), `wt step commit --dry-run` (mirror its `--stage` mode without/// changing the user's index), and the `wt switch` unified/working preview tabs.@@ -1692,7 +1692,7 @@ mod tests {fn temp_index_tolerates_missing_real_index() {// A worktree whose `<gitdir>/index` file is absent must not error// when callers ask for a temp index — git itself treats a missing- // index as empty, and the WorkingTreeConflictsTask used to surface+ // index as empty, and the working-tree conflict task used to surface// this as a misleading `working-tree conflict check (Failed to copy// index file)` footer.let test = TestRepo::with_initial_commit();diff --git a/src/summary.rs b/src/summary.rsindex cfa4f0448..045b698aa 100644--- a/src/summary.rs+++ b/src/summary.rs@@ -294,7 +294,7 @@ pub(crate) fn render_prompt(diff: &str, stat: &str) -> anyhow::Result<String> {/// with clean worktree). Returns `Ok(Some(full_summary))` on success. Errors/// propagate from template rendering or LLM execution.///-/// Both `generate_summary` (TUI) and `SummaryGenerateTask` (list column) delegate+/// Both `generate_summary` (TUI) and the list summary task delegate/// to this function, wrapping its result with their own error formatting.pub(crate) fn generate_summary_core(branch: &str,diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex cd1a884c8..f43b2401d 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -3991,7 +3991,7 @@ fn test_list_unborn_worktree_no_task_failures(repo: TestRepo) {String::from_utf8_lossy(&out.stdout),String::from_utf8_lossy(&out.stderr));- // Untracked content forces WorkingTreeDiffTask to inspect the unborn tree.+ // Untracked content forces the working-tree diff task to inspect the unborn tree.std::fs::write(orphan_path.join("untracked.txt"), "content\n").unwrap();let output = repo@@ -4207,7 +4207,7 @@ fn test_list_tolerates_missing_index(mut repo: TestRepo) {let feature = repo.add_worktree("feature");- // Dirty the worktree so WorkingTreeConflictsTask exercises the temp-index path.+ // Dirty the worktree so the working-tree conflict task exercises the temp-index path.std::fs::write(feature.join("shared.txt"), "feature changes").unwrap();std::fs::write(feature.join("untracked.txt"), "extra\n").unwrap();