Module: Brainiac::Plugins::Github::Handler

Defined in:
lib/brainiac/plugins/github/handler.rb

Class Method Summary collapse

Class Method Details

.handle_issue_comment(payload) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/brainiac/plugins/github/handler.rb', line 247

def handle_issue_comment(payload)
  comment = payload["comment"]
  issue = payload["issue"]
  comment_body = comment["body"] || ""
  comment_id = comment["id"]
  comment_user = comment.dig("user", "login")
  comment_user_type = comment.dig("user", "type")
  repo_name = payload.dig("repository", "full_name")

  unless issue["pull_request"]
    LOG.info "Issue comment on non-PR issue ##{issue["number"]}, ignoring"
    return [200, { status: "ignored", reason: "not a PR comment" }.to_json]
  end

  # If the PR was opened by a remote agent bot (not local to this machine),
  # skip dispatch — the other machine that owns the agent will handle it.
  pr_author = issue.dig("user", "login")
  pr_author_type = issue.dig("user", "type")
  unless pr_author_owned_locally?(pr_author, pr_author_type)
    pr_number = issue["number"]
    LOG.info "[GitHub] PR ##{pr_number} owned by remote agent (#{pr_author}) — skipping dispatch"
    return [200, { status: "ignored", reason: "PR owned by remote agent" }.to_json]
  end

  project_result = identify_project_by_repo(repo_name)
  unless project_result
    LOG.info "No project found for GitHub repo #{repo_name}"
    return [200, { status: "ignored", reason: "no matching project" }.to_json]
  end

  project_key, project_config = project_result
  pr_number = issue["number"]
  agent_name = agent_name_for(project_config)

  # Mention detection: if the comment mentions a specific agent, dispatch
  # that agent instead of the project's default. This enables cross-agent
  # reviews on PRs.
  #
  # Supported syntax (to avoid tagging real GitHub users with @):
  #   "Threepio, review this"   — name + comma at the start
  #   "/ask Threepio review"    — /ask Name
  #   "/Threepio review this"   — /Name
  #   "@Threepio review this"   — @Name (legacy, works but tags real users)
  mentioned = detect_github_mention(comment_body)
  if mentioned && mentioned.downcase != agent_name.downcase && local_agent_names.include?(mentioned)
    LOG.info "[GitHub] Mention detected: #{mentioned} in PR comment (default agent: #{agent_name})"
    agent_name = mentioned
  end

  # Ignore comments from agent bots that shouldn't trigger dispatch on this machine:
  # 1. Self-triggered: bot matches the dispatching agent (prevents loops)
  # 2. Remote agent: bot matches a known agent that isn't local (other machine handles it)
  # Cross-agent LOCAL bot comments (e.g. GLaDOS commenting on Galen's PR) are still processed.
  bot_ignore_reason = bot_comment_ignore_reason(comment_user, comment_user_type, agent_name, pr_number)
  return bot_ignore_reason if bot_ignore_reason

  branch = fetch_pr_branch(repo_name, pr_number, agent_name, project_config)
  result = find_work_item_by_branch(branch)

  # If a work item exists and has an assigned agent, use that agent
  # instead of the project default. This ensures comments on a PR
  # route to whoever is actually working it (e.g. GLaDOS opened the PR,
  # so GLaDOS should handle follow-up comments — not the project's default agent).
  # Explicit mentions still take priority (already resolved above).
  #
  # If the work item's assigned agent is NOT local to this machine,
  # skip dispatch entirely — the other machine owns this PR's agent.
  if result && !mentioned
    override_result = resolve_comment_agent_override(result, agent_name, pr_number)
    return override_result if override_result.is_a?(Array)

    agent_name = override_result if override_result
  end

  # Fallback for human-opened PRs with no assigned agent: if there's no work item,
  # or the work item has no agent field, both machines would dispatch because each
  # has its own local project default agent. Use branch_exists_locally? as a
  # tiebreaker — only the machine that has the branch as a local worktree/branch
  # should handle the comment. Explicit mentions bypass this check.
  unless mentioned || work_item_has_agent?(result)
    repo_path = project_config["repo_path"]
    unless branch_exists_locally?(repo_path, branch)
      LOG.info "[GitHub] PR ##{pr_number} branch '#{branch}' not found locally — skipping comment dispatch"
      return [200, { status: "ignored", reason: "branch not on this machine" }.to_json]
    end
  end

  card_number, worktree = resolve_comment_worktree(result, mentioned, agent_name, pr_number, project_config)
  return worktree if worktree.is_a?(Array)

  card_key = "pr-comment-#{repo_name.tr("/", "-")}-#{pr_number}-#{agent_name.downcase}"

  if session_active?(card_key)
    LOG.info "Skipping PR comment on #{card_key} — agent session already active"
    return [200, { status: "ignored", reason: "session already active" }.to_json]
  end

  card_context = card_number ? " for card ##{card_number}" : ""
  LOG.info "PR comment from #{comment_user} on PR ##{pr_number}#{card_context} (project: #{project_key})"
  dispatch_pr_comment(card_number, card_key, pr_number, comment_id, comment_user, comment_body,
                      repo_name, worktree, project_key, project_config, agent_name: agent_name)

  [200, { status: "processed", card: card_number, pr: pr_number, comment_id: comment_id, project: project_key }.to_json]
rescue StandardError => e
  LOG.error "Error handling PR comment: #{e.message}"
  [500, { error: e.message }.to_json]
end

.handle_issue_opened(payload) ⇒ Object



355
356
357
358
359
360
361
362
363
364
# File 'lib/brainiac/plugins/github/handler.rb', line 355

def handle_issue_opened(payload)
  issue = payload["issue"]
  issue_url = issue["html_url"]
  issue_title = issue["title"]
  issue_number = issue["number"]
  repo_name = payload.dig("repository", "full_name")

  LOG.info "New GitHub issue ##{issue_number} on #{repo_name}: #{issue_title} (#{issue_url})"
  [200, { status: "logged", issue: issue_number, title: issue_title, url: issue_url }.to_json]
end

.handle_pr_merged(payload) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/brainiac/plugins/github/handler.rb', line 8

def handle_pr_merged(payload)
  pr = payload["pull_request"]
  branch = pr.dig("head", "ref")
  base = pr.dig("base", "ref")
  pr_url = pr["html_url"]
  pr_title = pr["title"]
  repo_full_name = payload.dig("repository", "full_name")

  default_branch = payload.dig("repository", "default_branch") || "main"

  # Extract card number from branch name (e.g., "fizzy-1182-add-goodbye-method" → 1182)
  card_number_from_branch = branch&.match(/^fizzy-(\d+)-/)
  card_number_from_branch = card_number_from_branch[1].to_i if card_number_from_branch

  # Emit a hook for ALL merges (including epic branches) so consumers can decide
  if card_number_from_branch
    Brainiac.emit(:pr_merged_to_branch,
                  card_number: card_number_from_branch,
                  branch: branch,
                  base_branch: base,
                  pr_url: pr_url,
                  pr_title: pr_title,
                  repo_full_name: repo_full_name)
  end

  unless base == default_branch
    LOG.info "PR merged into #{base}, not #{default_branch} — ignoring"

    # Trigger #2: a child PR merging *into* an epic branch redeploys the
    # epic's ephemeral env (if one is tracked for that branch).
    epic_redeployed = maybe_redeploy_epic_ephemeral_env(base_branch: base)
    return [200, { status: "processed", action: "epic_redeploy", base: base }.to_json] if epic_redeployed

    return [200, { status: "ignored", reason: "not merged into #{default_branch}" }.to_json]
  end

  project_result = identify_project_by_repo(repo_full_name)
  unless project_result
    LOG.info "No project found for GitHub repo #{repo_full_name}"
    return [200, { status: "ignored", reason: "no matching project" }.to_json]
  end

  project_key, project_config = project_result
  repo_path = project_config["repo_path"]

  result = find_work_item_by_branch(branch)
  unless result
    LOG.info "No card found for branch #{branch}"
    return [200, { status: "ignored", reason: "no matching card" }.to_json]
  end

  _internal_id, card_info = result
  card_number = extract_card_number(card_info)
  unless card_number
    LOG.warn "Card has no number — can't comment or move"
    return [200, { status: "ignored", reason: "card has no number" }.to_json]
  end

  LOG.info "PR merged into main for card ##{card_number} (project: #{project_key}): #{pr_url}"
  process_merged_pr(card_info, card_number, branch, pr, pr_url, pr_title, project_key, project_config, repo_path)

  [200, { status: "processed", card: card_number, pr: pr_url, action: "merged_to_uat", project: project_key }.to_json]
rescue StandardError => e
  LOG.error "Error handling merged PR: #{e.message}"
  [500, { error: e.message }.to_json]
end

.handle_pr_opened(payload) ⇒ Object



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
# File 'lib/brainiac/plugins/github/handler.rb', line 75

def handle_pr_opened(payload)
  track_pr_in_work_items(payload)

  # Emit :pr_opened hook so plugins (e.g., brainiac-basecamp) can trigger review gates.
  pr = payload["pull_request"]
  branch = pr.dig("head", "ref")

  result = find_work_item_by_branch(branch)
  if result
    _internal_id, card_info = result
    card_number = extract_card_number(card_info)
    pr_number = pr["number"]
    repo_name = payload.dig("repository", "full_name")
    repo_path = card_info["worktree"] || find_repo_path_for(payload)
    base_branch = pr.dig("base", "ref")

    Brainiac.emit(:pr_opened,
                  card_number: card_number, card_info: card_info,
                  pr_number: pr_number, repo_name: repo_name,
                  repo_path: repo_path, branch: branch,
                  base_branch: base_branch, pull_request: pr)
  end

  [200, { status: "processed", action: "pr_tracked" }.to_json]
end

.handle_pr_review_submitted(payload) ⇒ Object



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
# File 'lib/brainiac/plugins/github/handler.rb', line 148

def (payload)
  pr = payload["pull_request"]
  review = payload["review"]
  branch = pr.dig("head", "ref")
  pr_number = pr["number"]
  repo_name = payload.dig("repository", "full_name")
  review_state = review["state"]
  reviewer = review.dig("user", "login")
  reviewer_type = review.dig("user", "type")

  # If the review was submitted by a remote agent bot, ignore — the other machine handles it.
  if reviewer_type == "Bot"
    reviewing_agent = (reviewer)
    if reviewing_agent && !local_agent_names.include?(reviewing_agent)
      LOG.info "[GitHub] Ignoring review from remote agent bot #{reviewer} (agent: #{reviewing_agent}) on PR ##{pr_number}"
      return [200, { status: "ignored", reason: "remote agent bot review" }.to_json]
    end
  end

  # If the PR was opened by a remote agent bot (not local to this machine),
  # skip dispatch — the other machine that owns the agent will handle it.
  unless pr_owned_locally?(pr)
    pr_author = pr.dig("user", "login")
    LOG.info "[GitHub] PR ##{pr_number} owned by remote agent (#{pr_author}) — skipping dispatch"
    return [200, { status: "ignored", reason: "PR owned by remote agent" }.to_json]
  end

  project_result = identify_project_by_repo(repo_name)
  return [200, { status: "ignored", reason: "no matching project" }.to_json] unless project_result

  project_key, project_config = project_result
  repo_path = project_config["repo_path"]

  result = find_work_item_by_branch(branch)

  if result
    _internal_id, card_info = result
    card_number = extract_card_number(card_info)
    unless card_number
      LOG.warn "Card has no number — can't dispatch review"
      return [200, { status: "ignored", reason: "card has no number" }.to_json]
    end
  else
    card_info = {}
    card_number = nil
  end

  # Always emit the hook so gate tracking works for approvals too
  Brainiac.emit(:pr_review_received,
                card_number: card_number,
                reviewer: reviewer,
                review_state: review_state,
                pr_number: pr_number,
                repo_name: repo_name,
                project_config: project_config,
                repo_path: repo_path)

  # Only dispatch the implementation agent for changes_requested or commented reviews
  # Approvals don't need the agent to do anything (the gate hook handles the flow)
  unless %w[changes_requested commented].include?(review_state)
    LOG.info "PR review (#{review_state}) by #{reviewer} on PR ##{pr_number} — hook emitted, no agent dispatch"
    return [200, { status: "processed", card: card_number, pr: pr_number, reviewer: reviewer, action: "hook_only" }.to_json]
  end

  # If the work item's assigned agent is NOT local to this machine,
  # skip dispatch — the other machine owns this PR's agent.
  # This check is intentionally AFTER the hook emit so gate tracking
  # works on both machines, but only one machine dispatches the agent.
  if result
    work_item_agent = card_info["agent"]
    if work_item_agent && !local_agent_names.include?(work_item_agent)
      LOG.info "[GitHub] PR ##{pr_number} assigned to remote agent #{work_item_agent} — skipping review dispatch"
      return [200, { status: "ignored", reason: "work item owned by remote agent" }.to_json]
    end
  else
    # No work item found — check if the PR's branch exists as a local worktree.
    # This handles PRs opened manually (not through a card) where the worktree
    # exists on only one machine. The machine that has the worktree should handle it.
    unless branch_exists_locally?(repo_path, branch)
      LOG.info "[GitHub] PR ##{pr_number} branch '#{branch}' not found locally — skipping review dispatch"
      return [200, { status: "ignored", reason: "branch not on this machine" }.to_json]
    end
  end

  card_key = "pr-review-#{repo_name.tr("/", "-")}-#{pr_number}"

  return [200, { status: "ignored", reason: "session already active" }.to_json] if session_active?(card_key)

  card_context = card_number ? " for card ##{card_number}" : ""
  LOG.info "PR review submitted by #{reviewer} on PR ##{pr_number}#{card_context} (project: #{project_key})"
  dispatch_pr_review(card_number, card_key, card_info, pr_number, review, reviewer,
                     repo_name, project_key, project_config, repo_path)

  [200, { status: "processed", card: card_number, pr: pr_number, reviewer: reviewer, project: project_key }.to_json]
rescue StandardError => e
  LOG.error "Error handling PR review: #{e.message}"
  [500, { error: e.message }.to_json]
end

.handle_pr_synchronized(payload) ⇒ Object



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
# File 'lib/brainiac/plugins/github/handler.rb', line 101

def handle_pr_synchronized(payload)
  pr = payload["pull_request"]
  branch = pr.dig("head", "ref")
  base_branch = pr.dig("base", "ref")

  # Trigger #1: a push to an epic PR's head branch redeploys the epic env.
  # Epic envs have no card, so resolve this before the card lookup bails.
  epic_redeployed = maybe_redeploy_epic_ephemeral_env(branch: branch)

  result = find_work_item_by_branch(branch)
  unless result
    return [200, { status: "processed", action: "epic_sync", branch: branch, epic_redeployed: true }.to_json] if epic_redeployed

    return [200, { status: "ignored", reason: "no matching card" }.to_json]
  end

  _internal_id, card_info = result
  card_number = extract_card_number(card_info)
  worktree = card_info["worktree"]

  return [200, { status: "ignored", reason: "no worktree" }.to_json] unless worktree && File.directory?(worktree)

  # Pull latest changes into worktree
  system("git", "pull", "--ff-only", chdir: worktree)

  # Try to redeploy to ephemeral Belt environment if one exists
  ephemeral_redeployed = maybe_redeploy_ephemeral_belt_env(
    card_info: card_info, card_number: card_number, worktree: worktree,
    base_branch: base_branch
  )

  # Also emit the hook for other plugins (e.g., brainiac-fizzy persistent env redeploy)
  results = Brainiac.emit(:pr_synchronized, card_number: card_number, card_info: card_info,
                                            worktree: worktree, pull_request: pr, branch: branch)

  if ephemeral_redeployed || epic_redeployed || results.any?
    [200,
     { status: "processed", action: "pr_sync", card: card_number, ephemeral_redeployed: ephemeral_redeployed,
       epic_redeployed: epic_redeployed }.to_json]
  else
    [200, { status: "ignored", reason: "no deployment plugin" }.to_json]
  end
rescue StandardError => e
  LOG.error "[PR Sync] Error: #{e.message}"
  [500, { error: e.message }.to_json]
end

.handle_workflow_run(payload) ⇒ Object



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
# File 'lib/brainiac/plugins/github/handler.rb', line 366

def handle_workflow_run(payload)
  workflow = payload["workflow_run"]
  workflow_name = workflow["name"]
  conclusion = workflow["conclusion"]
  repo_full_name = payload.dig("repository", "full_name")
  run_url = workflow["html_url"]

  if workflow_name == "Deploy to Production" && conclusion == "failure"
    project_key = identify_project_by_repo(repo_full_name)&.first || repo_full_name
    Notifications.send_workflow_failure(project_key, workflow_name, run_url)
    return [200, { status: "processed", action: "prod_deploy_failure_notified", project: project_key }.to_json]
  end

  if workflow_name == "Deploy to UAT" && conclusion == "success"
    project_key = identify_project_by_repo(repo_full_name)&.first || repo_full_name
    Notifications.send_uat_deploy(project_key)
    return [200, { status: "processed", action: "uat_deploy_notified", project: project_key }.to_json]
  end

  return [200, { status: "ignored", reason: "conclusion: #{conclusion}" }.to_json] unless conclusion == "success"
  return [200, { status: "ignored", reason: "workflow: #{workflow_name}" }.to_json] unless workflow_name == "Deploy to Production"

  project_result = identify_project_by_repo(repo_full_name)
  return [200, { status: "ignored", reason: "no matching project" }.to_json] unless project_result

  project_key, project_config = project_result
  close_uat_cards_after_deploy(project_key, project_config)
rescue StandardError => e
  LOG.error "Error handling workflow run: #{e.message}"
  [500, { error: e.message }.to_json]
end