Class: Ace::Git::Worktree::Organisms::TaskWorktreeOrchestrator

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb

Overview

Task worktree orchestrator

Orchestrates the complete workflow of creating task-aware worktrees, including task status updates, metadata tracking, commits, and mise trust. This is the main high-level interface for task-worktree integration.

Examples:

Create a complete task worktree workflow

orchestrator = TaskWorktreeOrchestrator.new
result = orchestrator.create_for_task("081")
# => { success: true, worktree_path: "/project/.ace-wt/task.081", ... }

Instance Method Summary collapse

Constructor Details

#initialize(config: nil, project_root: Dir.pwd) ⇒ TaskWorktreeOrchestrator

Initialize a new TaskWorktreeOrchestrator

Parameters:

  • config (WorktreeConfig, nil) (defaults to: nil)

    Worktree configuration (loaded if nil)

  • project_root (String) (defaults to: Dir.pwd)

    Project root directory



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb', line 26

def initialize(config: nil, project_root: Dir.pwd)
  @project_root = project_root
  @config = config || load_configuration
  @task_fetcher = Molecules::TaskFetcher.new
  @task_status_updater = Molecules::TaskStatusUpdater.new
  @task_committer = Molecules::TaskCommitter.new
  @task_pusher = Molecules::TaskPusher.new
  @worktree_creator = Molecules::WorktreeCreator.new
  @pr_creator = Molecules::PrCreator.new
  @parent_task_resolver = Molecules::ParentTaskResolver.new(project_root: project_root)
end

Instance Method Details

#create_for_task(task_ref, options = {}) ⇒ Hash

Create a worktree for a task with complete workflow

Examples:

orchestrator = TaskWorktreeOrchestrator.new
result = orchestrator.create_for_task("081")
# => {
#   success: true,
#   worktree_path: "/project/.ace-wt/task.081",
#   branch: "081-fix-authentication-bug",
#   task_id: "081",
#   steps_completed: ["task_fetched", "status_updated", "worktree_created", "mise_trusted"],
#   error: nil
# }

With explicit source

result = orchestrator.create_for_task("081", source: "main")
# => Creates branch based on 'main' instead of current branch

Parameters:

  • task_ref (String)

    Task reference (081, task.081, v.0.9.0+081)

  • options (Hash) (defaults to: {})

    Options for worktree creation

Options Hash (options):

  • :source (String)

    Git ref to use as branch start-point (default: current branch)

Returns:

  • (Hash)

    Result with workflow details



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
# File 'lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb', line 60

def create_for_task(task_ref, options = {})
  workflow_result = initialize_workflow_result

  begin
    # Step 1: Fetch task data
    task_data = fetch_task_data(task_ref)
    return error_workflow_result("Task not found: #{task_ref}", workflow_result) unless task_data

    task_id = extract_task_id(task_data)
    workflow_result[:task_id] = task_id
    workflow_result[:task_title] = task_data[:title]
    workflow_result[:steps_completed] << "task_fetched"

    # Step 2: Check if worktree already exists
    existing_worktree = check_existing_worktree(task_data)
    if existing_worktree
      return success_workflow_result("Worktree already exists", workflow_result.merge(
        worktree_path: existing_worktree.path,
        branch: existing_worktree.branch,
        existing: true
      ))
    end

    # Step 3: Update task status if configured (and not overridden)
    should_update_status = options[:no_status_update] ? false : @config.auto_mark_in_progress?
    if should_update_status && task_data[:status] != "in-progress"
      status_result = update_task_status(task_id, "in-progress")
      if status_result[:success]
        workflow_result[:steps_completed] << "status_updated"
      else
        error_message = status_result[:message] || "Failed to update task status"
        hint = "\n\nHint: Use --no-status-update to create worktree without changing task status"
        return error_workflow_result(error_message + hint, workflow_result)
      end
    end

    # Step 4: Create worktree metadata
    # Determine target branch for PR (parent's branch for subtasks, or main)
    target_branch = resolve_target_branch(task_data, options)
    workflow_result[:target_branch] = target_branch
     = (task_data, target_branch: target_branch)
    workflow_result[:steps_completed] << "metadata_prepared"

    # Step 5: Add worktree metadata to task file (BEFORE commit so it's included)
    if @config.add_worktree_metadata?
      if (task_data, )
        workflow_result[:steps_completed] << "metadata_added"
      else
        workflow_result[:warnings] << "Failed to add worktree metadata to task"
      end
    end

    # Step 6: Commit task changes if configured (includes status + metadata)
    # Commit when either status was updated or metadata was added
    should_commit = options[:no_commit] ? false : @config.auto_commit_task?
     = workflow_result[:steps_completed].include?("metadata_added")
    has_changes_to_commit = should_update_status || 
    if should_commit && has_changes_to_commit
      commit_message = options[:commit_message] || "in-progress"
      if commit_task_changes(task_data, commit_message)
        workflow_result[:steps_completed] << "task_committed"
      else
        # Continue even if commit fails, but note it
        workflow_result[:warnings] << "Failed to commit task changes"
      end
    end

    # Step 7: Push task changes if configured (so PR shows updates)
    should_push = options[:no_push] ? false : @config.auto_push_task?
    if should_push && should_commit && workflow_result[:steps_completed].include?("task_committed")
      push_remote = options[:push_remote] || @config.push_remote
      if push_task_changes(push_remote)
        workflow_result[:steps_completed] << "task_pushed"
        workflow_result[:pushed_to] = push_remote
      else
        # Continue even if push fails, but note it
        workflow_result[:warnings] << "Failed to push task changes"
      end
    end

    # Step 8: Create the worktree
    worktree_result = create_worktree_for_task(task_data, , source: options[:source])
    return error_workflow_result(worktree_result[:error], workflow_result) unless worktree_result[:success]

    workflow_result[:worktree_path] = worktree_result[:worktree_path]
    workflow_result[:branch] = worktree_result[:branch]
    workflow_result[:directory_name] = worktree_result[:directory_name]
    workflow_result[:start_point] = worktree_result[:start_point]
    workflow_result[:steps_completed] << "worktree_created"

    # Step 8.5: Create _current symlink in worktree if configured
    if @config.create_current_symlink?
      current_linker = Molecules::CurrentTaskLinker.new(
        project_root: worktree_result[:worktree_path],
        symlink_name: @config.current_symlink_name
      )
      # Task directory relative to worktree (same structure as main repo)
      # task_data[:path] is the task file path, we need the parent directory
      worktree_task_dir = File.dirname(File.join(worktree_result[:worktree_path], relative_task_path(task_data[:path])))
      link_result = current_linker.link(worktree_task_dir)
      if link_result[:success]
        workflow_result[:steps_completed] << "current_symlink_created"
        workflow_result[:current_symlink] = link_result[:symlink_path]
      else
        # Symlink creation is non-blocking - failure becomes warning
        workflow_result[:warnings] ||= []
        workflow_result[:warnings] << "Failed to create _current symlink: #{link_result[:error]}"
      end
    end

    # Step 9: Setup upstream for worktree branch if configured
    should_setup_upstream = @config.auto_setup_upstream? && !options[:no_upstream]
    if should_setup_upstream
      upstream_result = setup_upstream_for_worktree(worktree_result, options)
      if upstream_result[:success]
        workflow_result[:steps_completed] << "upstream_setup"
        workflow_result[:pushed_branch] = upstream_result[:branch]
      else
        # Upstream setup is non-blocking - failure becomes warning
        workflow_result[:warnings] ||= []
        workflow_result[:warnings] << "Failed to setup upstream: #{upstream_result[:error]}"
      end
    end

    # Step 9.5: Add started_at timestamp to task IN WORKTREE (creates initial commit for PR)
    # Only do this if we're going to create a PR and upstream succeeded
    upstream_succeeded = workflow_result[:steps_completed].include?("upstream_setup")
    should_create_pr = @config.auto_create_pr? && !options[:no_pr]
    if should_create_pr && upstream_succeeded
      started_result = add_started_timestamp_in_worktree(task_data, worktree_result, options)
      if started_result[:success]
        workflow_result[:steps_completed] << "started_at_added"
      else
        # Non-blocking - PR creation may still work if branch already has commits
        workflow_result[:warnings] ||= []
        workflow_result[:warnings] << "Failed to add started_at: #{started_result[:error]}"
      end
    end

    # Step 10: Create draft PR if configured
    if should_create_pr && upstream_succeeded
      pr_result = create_pr_for_task(task_data, worktree_result, options)
      if pr_result[:success]
        workflow_result[:steps_completed] << "pr_created"
        workflow_result[:pr_number] = pr_result[:pr_number]
        workflow_result[:pr_url] = pr_result[:pr_url]
        workflow_result[:pr_existing] = pr_result[:existing]

        # Step 11: Save PR metadata to task
        save_pr_result = save_pr_to_task(task_data, pr_result)
        if save_pr_result
          workflow_result[:steps_completed] << "pr_saved_to_task"
        else
          workflow_result[:warnings] ||= []
          workflow_result[:warnings] << "Failed to save PR metadata to task"
        end
      else
        # PR creation is non-blocking - failure becomes warning
        workflow_result[:warnings] ||= []
        workflow_result[:warnings] << "Failed to create PR: #{pr_result[:error]}"
      end
    elsif should_create_pr && !upstream_succeeded
      # Skip PR creation if upstream setup failed
      workflow_result[:warnings] ||= []
      workflow_result[:warnings] << "Skipped PR creation: branch not pushed to remote"
    end

    # Step 12: Run after-create hooks if configured
    hooks = @config.after_create_hooks
    if hooks && hooks.any?
      require_relative "../molecules/hook_executor"
      hook_executor = Molecules::HookExecutor.new
      hook_result = hook_executor.execute_hooks(
        hooks,
        worktree_path: worktree_result[:worktree_path],
        project_root: @project_root,
        task_data: task_data
      )

      if hook_result[:success]
        workflow_result[:steps_completed] << "hooks_executed"
        workflow_result[:hooks_results] = hook_result[:results]
      else
        # Hooks are non-blocking - failures become warnings
        workflow_result[:warnings] ||= []
        workflow_result[:warnings] += hook_result[:errors]
        workflow_result[:hooks_results] = hook_result[:results]
      end
    end

    # Success!
    success_workflow_result("Task worktree created successfully", workflow_result)
  rescue => e
    error_workflow_result("Unexpected error: #{e.message}", workflow_result)
  end
end

#dry_run_create(task_ref, options = {}) ⇒ Hash

Create a worktree with dry run (no actual changes)

Examples:

result = orchestrator.dry_run_create("081")
# => { success: true, would_create: {...}, steps: [...] }

Parameters:

  • task_ref (String)

    Task reference

  • options (Hash) (defaults to: {})

    Options for dry run

Returns:

  • (Hash)

    Dry run result showing what would be done



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
# File 'lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb', line 266

def dry_run_create(task_ref, options = {})
  workflow_result = initialize_workflow_result

  begin
    # Step 1: Fetch task data
    task_data = fetch_task_data(task_ref)
    return error_workflow_result("Task not found: #{task_ref}", workflow_result) unless task_data

    task_id = extract_task_id(task_data)
    workflow_result[:task_id] = task_id
    workflow_result[:task_title] = task_data[:title]
    workflow_result[:steps_completed] << "task_fetched"

    # Step 2: Check what would be created
    directory_name = @config.format_directory(task_data)
    branch_name = @config.format_branch(task_data)
    worktree_path = File.join(@config.absolute_root_path, directory_name)
    options[:source] || "main"

    # Determine target branch for PR (parent's branch for subtasks, or main)
    target_branch = resolve_target_branch(task_data, options)

    # Determine upstream/PR settings (considering options)
    should_setup_upstream = @config.auto_setup_upstream? && !options[:no_upstream]
    should_create_pr = @config.auto_create_pr? && !options[:no_pr] && should_setup_upstream

    # Determine if there will be changes to commit
    # Commit when either status would be updated or metadata would be added
    would_update_status = @config.auto_mark_in_progress? && task_data[:status] != "in-progress"
     = @config.add_worktree_metadata?
    has_changes_to_commit = would_update_status || 
    would_commit = @config.auto_commit_task? && has_changes_to_commit

    # Determine if current symlink would be created (in worktree)
    would_create_current_symlink = @config.create_current_symlink?
    current_symlink_path = would_create_current_symlink ? File.join(worktree_path, @config.current_symlink_name) : nil
    # Task directory relative to worktree (same structure as main repo)
    # task_data[:path] is the task file path, we need the parent directory
    relative_task = would_create_current_symlink ? relative_task_path(task_data[:path]) : nil
    worktree_task_dir = would_create_current_symlink ? File.dirname(File.join(worktree_path, relative_task)) : nil

    workflow_result[:would_create] = {
      worktree_path: worktree_path,
      branch: branch_name,
      directory_name: directory_name,
      target_branch: target_branch,
      task_status_update: would_update_status,
      metadata_addition: ,
      task_commit: would_commit,
      task_push: @config.auto_push_task? && would_commit,
      push_remote: @config.push_remote,
      current_symlink: would_create_current_symlink,
      current_symlink_path: current_symlink_path,
      current_symlink_target: worktree_task_dir,
      upstream_push: should_setup_upstream,
      add_started_at: should_create_pr && should_setup_upstream,
      create_pr: should_create_pr,
      pr_title: should_create_pr ? @config.format_pr_title(task_data) : nil,
      pr_base: should_create_pr ? target_branch : nil,
      hooks_count: @config.after_create_hooks.length
    }

    workflow_result[:steps_planned] = [
      "fetch_task_data",
      ("update_task_status" if workflow_result[:would_create][:task_status_update]),
      ("add_worktree_metadata" if workflow_result[:would_create][:metadata_addition]),
      ("commit_task_changes" if workflow_result[:would_create][:task_commit]),
      ("push_to_#{workflow_result[:would_create][:push_remote]}" if workflow_result[:would_create][:task_push]),
      "create_worktree",
      ("create_current_symlink" if workflow_result[:would_create][:current_symlink]),
      ("setup_upstream_tracking" if should_setup_upstream),
      ("add_started_at_in_worktree" if workflow_result[:would_create][:add_started_at]),
      ("create_draft_pr" if should_create_pr),
      ("save_pr_metadata" if should_create_pr),
      ("execute_#{workflow_result[:would_create][:hooks_count]}_hooks" if workflow_result[:would_create][:hooks_count] > 0)
    ].compact

    success_workflow_result("Dry run completed", workflow_result)
  rescue => e
    error_workflow_result("Dry run error: #{e.message}", workflow_result)
  end
end

#get_task_worktree_status(task_refs = nil) ⇒ Hash

Get status of task worktrees

Examples:

status = orchestrator.get_task_worktree_status(["081", "082"])

Parameters:

  • task_refs (Array<String>, nil) (defaults to: nil)

    Task references to check (all if nil)

Returns:

  • (Hash)

    Status information



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
# File 'lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb', line 420

def get_task_worktree_status(task_refs = nil)
  if task_refs.nil?
    # Get all task-associated worktrees
    worktree_lister = Molecules::WorktreeLister.new
    worktrees = worktree_lister.list_all.select(&:task_associated?)
    task_ids = worktrees.map(&:task_id).compact.uniq
  else
    task_ids = Array(task_refs).map { |ref| Atoms::TaskIDExtractor.normalize(ref) }.compact
  end

  status_info = {
    total_tasks: task_ids.length,
    worktrees: []
  }

  task_ids.each do |task_id|
    worktree_info = @worktree_creator.find_by_task_id(task_id)
     = @task_fetcher.fetch(task_id)

    worktree_status = {
      task_id: task_id,
      task_title: &.title,
      task_status: &.status,
      has_worktree: !worktree_info.nil?,
      worktree_path: worktree_info&.path,
      worktree_branch: worktree_info&.branch,
      worktree_exists: worktree_info&.exists?,
      worktree_usable: worktree_info&.usable?
    }

    status_info[:worktrees] << worktree_status
  end

  status_info[:worktrees_with_worktrees] = status_info[:worktrees].count { |w| w[:has_worktree] }
  status_info[:active_worktrees] = status_info[:worktrees].count { |w| w[:worktree_exists] && w[:worktree_usable] }

  {success: true, status: status_info}
rescue => e
  error_result("Failed to get task worktree status: #{e.message}")
end

#remove_task_worktree(task_ref, options = {}) ⇒ Hash

Remove a task worktree with cleanup

Examples:

result = orchestrator.remove_task_worktree("081", force: true)

Parameters:

  • task_ref (String)

    Task reference

  • options (Hash) (defaults to: {})

    Options for removal

Returns:

  • (Hash)

    Result of removal workflow



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
# File 'lib/ace/git/worktree/organisms/task_worktree_orchestrator.rb', line 357

def remove_task_worktree(task_ref, options = {})
  workflow_result = initialize_workflow_result

  begin
    # Step 1: Fetch task data
    task_data = fetch_task_data(task_ref)

    # Step 2: Find existing worktree (with fallback for missing task)
    if task_data
      task_id = extract_task_id(task_data)
      workflow_result[:task_id] = task_id
      workflow_result[:steps_completed] << "task_fetched"
      worktree_info = find_worktree_for_task_data(task_data)
    else
      # Fallback: Try to find worktree by task reference even if task data not found
      worktree_info = find_worktree_by_task_reference(task_ref)
      if worktree_info
        puts "Task not found, but worktree found. Removing worktree without updating task data."
        workflow_result[:task_id] = task_ref
        workflow_result[:task_not_found] = true
      else
        return error_workflow_result("Task not found: #{task_ref}", workflow_result)
      end
    end

    return error_workflow_result("No worktree found for task", workflow_result) unless worktree_info

    workflow_result[:worktree_path] = worktree_info.path
    workflow_result[:branch] = worktree_info.branch

    # Step 3: Check removal safety
    worktree_remover = Molecules::WorktreeRemover.new
    safety_check = worktree_remover.check_removal_safety(worktree_info.path)
    unless options[:force] || safety_check[:safe]
      return error_workflow_result("Cannot remove worktree: #{safety_check[:errors].join(", ")}", workflow_result)
    end

    # Step 4: Remove worktree metadata from task (only if task was found)
    if task_data && (task_data)
      workflow_result[:steps_completed] << "metadata_removed"
    elsif workflow_result[:task_not_found]
      workflow_result[:steps_completed] << "skipped_metadata_cleanup"
    end

    # Step 5: Remove the worktree
    remove_result = worktree_remover.remove(worktree_info.path, force: options[:force])
    return error_workflow_result("Failed to remove worktree: #{remove_result[:error]}", workflow_result) unless remove_result[:success]

    workflow_result[:steps_completed] << "worktree_removed"

    success_workflow_result("Task worktree removed successfully", workflow_result)
  rescue => e
    error_workflow_result("Unexpected error: #{e.message}", workflow_result)
  end
end