Module: Brainiac::Plugins::Fizzy::Helpers

Defined in:
lib/brainiac/plugins/fizzy/helpers.rb

Overview

Fizzy-specific helper functions. These were previously in lib/brainiac/helpers.rb in core.

Class Method Summary collapse

Class Method Details



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
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 121

def append_fizzy_comment_footer(card_number, project_config:, agent_name: nil, since: nil)
  repo_path = project_config["repo_path"]
  env = fizzy_env_for(agent_name || AI_AGENT_NAME)

  output = run_cmd("fizzy", "comment", "list", "--card", card_number.to_s, "--all", chdir: repo_path, env: env)
  comments = JSON.parse(output)["data"] || []
  agent_display = agent_display_name(agent_name || AI_AGENT_NAME)

  # Find the most recent agent comment, scoped to this session if `since` is provided.
  # Subtracts 30s buffer from `since` to account for clock skew between local server and Fizzy API.
  agent_comments = comments.select { |c| c.dig("creator", "name")&.downcase == agent_display.downcase }
  if since
    buffered_since = since - 30
    agent_comments = agent_comments.select do |c|
      comment_time = c["created_at"] && Time.parse(c["created_at"])
      comment_time && comment_time > buffered_since
    end
  end

  last_agent_comment = agent_comments.last
  return false unless last_agent_comment

  # Append footer if applicable
  body = last_agent_comment.dig("body", "html") || ""
  unless body.include?("<em>Branch:")
    branch = detect_branch_from_comment(body, card_number)
    if branch
      pr_url = detect_pr_url(branch, project_config)
      footer = "<p><em>Branch: <code>#{branch}</code>"
      footer += " | <a href=\"#{pr_url}\">PR</a>" if pr_url
      footer += "</em></p>"

      updated_body = body + footer
      run_cmd("fizzy", "comment", "update", last_agent_comment["id"], "--card", card_number.to_s,
              "--body", updated_body, chdir: repo_path, env: env)
    end
  end

  true
rescue StandardError => e
  LOG.warn "[Fizzy] Could not append footer to card ##{card_number}: #{e.message}" if defined?(LOG)
  false
end

.default_fizzy_envObject



32
33
34
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 32

def default_fizzy_env
  fizzy_env_for(AI_AGENT_NAME)
end

.detect_planning_mode(text:, tags:, card_internal_id:, card_number:) ⇒ Object

Determines whether a card should run in planning mode. Returns nil if planning is not active, or { card_id: } if it is. Planning mode is triggered by a "plan" or "planning" tag on the card.



191
192
193
194
195
196
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 191

def detect_planning_mode(text:, tags:, card_internal_id:, card_number:)
  tag_names = (tags || []).map { |t| t.is_a?(Hash) ? t["name"] : t.to_s }.map(&:downcase)
  return nil unless tag_names.include?("plan") || tag_names.include?("planning")

  { card_id: card_number || card_internal_id }
end

.ensure_fizzy_yaml!(chdir, project_config) ⇒ Object



165
166
167
168
169
170
171
172
173
174
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 165

def ensure_fizzy_yaml!(chdir, project_config)
  fizzy_yaml_dest = File.join(chdir, ".fizzy.yaml")
  return if File.exist?(fizzy_yaml_dest)

  fizzy_yaml_src = File.join(project_config["repo_path"], ".fizzy.yaml")
  return unless File.exist?(fizzy_yaml_src)

  FileUtils.cp(fizzy_yaml_src, fizzy_yaml_dest)
  LOG.info "[Fizzy] Copied .fizzy.yaml to #{chdir}" if defined?(LOG)
end

.fetch_card_comments(card_number, repo_path:, env:) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 77

def fetch_card_comments(card_number, repo_path:, env:)
  output = run_cmd("fizzy", "comment", "list", "--card", card_number.to_s, "--all", chdir: repo_path, env: env)
  comments = JSON.parse(output)["data"] || []
  return "" if comments.empty?

  comments.last(15).map do |c|
    body = c.dig("body", "plain_text") || ""
    body = "#{body[0..500]}..." if body.length > 500
    "**#{c.dig("creator", "name")}** (#{c["id"]}):\n#{body}"
  end.join("\n\n---\n\n")
rescue StandardError => e
  LOG.warn "[Fizzy] Could not fetch comments for card ##{card_number}: #{e.message}" if defined?(LOG)
  ""
end

.fetch_card_details(card_number, repo_path:, env:) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 63

def fetch_card_details(card_number, repo_path:, env:)
  output = run_cmd("fizzy", "card", "show", card_number.to_s, chdir: repo_path, env: env)
  card = JSON.parse(output)["data"]
  return "" unless card

  parts = []
  parts << "**Title:** #{card["title"]}"
  parts << "**Body:**\n#{card.dig("body", "plain_text")}" if card.dig("body", "plain_text")
  parts.join("\n")
rescue StandardError => e
  LOG.warn "[Fizzy] Could not fetch card ##{card_number}: #{e.message}" if defined?(LOG)
  ""
end

.fetch_intent_context(card_number, repo_path:, agent_name: nil) ⇒ Object

Lightweight recent comment context for intent classification. Returns a simple "author: message" format (last 5 comments).



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 94

def fetch_intent_context(card_number, repo_path:, agent_name: nil)
  env = fizzy_env_for(agent_name || AI_AGENT_NAME)
  output = run_cmd("fizzy", "comment", "list", "--card", card_number.to_s, "--all", chdir: repo_path, env: env)
  comments = JSON.parse(output)["data"] || []
  return nil if comments.empty?

  comments.last(5).map do |c|
    creator = c.dig("creator", "name") || "unknown"
    body = (c.dig("body", "plain_text") || "").lines.first(3).join.strip
    body = "#{body[0..200]}..." if body.length > 200
    "#{creator}: #{body}"
  end.join("\n")
rescue StandardError => e
  LOG.warn "[Fizzy] Could not fetch intent context for card ##{card_number}: #{e.message}" if defined?(LOG)
  nil
end

.fizzy_env_for(agent_name) ⇒ Object



27
28
29
30
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 27

def fizzy_env_for(agent_name)
  token = fizzy_token_for(agent_name) || fizzy_token_for(AI_AGENT_NAME)
  token ? { "FIZZY_TOKEN" => token } : {}
end

.fizzy_token_for(agent_name) ⇒ Object



23
24
25
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 23

def fizzy_token_for(agent_name)
  agent_env_var(agent_name, "FIZZY_TOKEN")
end

.lookup_fizzy_card_info(card_internal_id) ⇒ Object

Look up a Fizzy card's work item info by its internal ID. Returns a hash with top-level "number", "agent", "branch", "worktree", "project" keys for backward compatibility with handler code, or nil if not found.



201
202
203
204
205
206
207
208
209
210
211
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 201

def lookup_fizzy_card_info(card_internal_id)
  return nil unless card_internal_id

  result = find_work_item_by_card(card_internal_id)
  return nil unless result

  _work_item_id, info = result
  # Ensure "number" is at top level for fizzy handler compat
  info["number"] ||= info.dig("sources", "fizzy", "card_number")
  info
end

.move_card_to_column(card_number, column_name, project_config:, agent_name: nil, board_key: nil) ⇒ Object



111
112
113
114
115
116
117
118
119
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 111

def move_card_to_column(card_number, column_name, project_config:, agent_name: nil, board_key: nil)
  board_key ||= Config.board_key_for_project(project_config)
  column_id = Config.board_column_id(board_key, column_name) if board_key
  return unless column_id

  repo_path = project_config["repo_path"]
  env = fizzy_env_for(agent_name || AI_AGENT_NAME)
  run_cmd("fizzy", "card", "column", card_number.to_s, "--column", column_id, chdir: repo_path, env: env)
end

.prefetch_card_context(card_number, repo_path:, agent_name: nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 52

def prefetch_card_context(card_number, repo_path:, agent_name: nil)
  env = fizzy_env_for(agent_name || AI_AGENT_NAME)
  card_details = fetch_card_details(card_number, repo_path: repo_path, env: env)
  card_comments = fetch_card_comments(card_number, repo_path: repo_path, env: env)

  context = ""
  context += "## Card Details\n#{card_details}\n\n" unless card_details.empty?
  context += "## Recent Comments\n#{card_comments}\n" unless card_comments.empty?
  context
end

.resolve_card_number(internal_id, repo_path:) ⇒ Object

Resolve a card number from an internal ID by querying the Fizzy API. Searches card lists to find the matching card.



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 263

def resolve_card_number(internal_id, repo_path:)
  env = default_fizzy_env
  base_cmd = %w[fizzy card list]
  ["--all", "--all --indexed-by closed"].each do |flags|
    cmd = base_cmd + flags.split
    output = run_cmd(*cmd, chdir: repo_path, env: env)
    data = JSON.parse(output)["data"] || []
    match = data.find { |c| c["id"] == internal_id }
    if match
      LOG.info "Resolved card number #{match["number"]} for internal_id #{internal_id}" if defined?(LOG)
      return match["number"]
    end
  rescue StandardError
    next
  end

  LOG.warn "Could not resolve card number for internal_id #{internal_id}" if defined?(LOG)
  nil
end

.resolve_github_agent_env(agent_name, github_repo) ⇒ Object

Resolve GitHub App token for an agent so gh CLI runs as their bot identity. Uses brainiac-github's AppClient if available.



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 38

def resolve_github_agent_env(agent_name, github_repo)
  return {} unless github_repo

  if defined?(Brainiac::Plugins::Github::AppClient)
    repo_owner = github_repo.split("/").first
    token = Brainiac::Plugins::Github::AppClient.installation_token_for(agent_name, repo_owner: repo_owner)
    return { "GH_TOKEN" => token } if token
  end
  {}
rescue StandardError => e
  LOG.warn "[Fizzy] Could not resolve GitHub token for #{agent_name}: #{e.message}" if defined?(LOG)
  {}
end

.scrub_invalid_attachments!(dir) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 176

def scrub_invalid_attachments!(dir)
  attachments_dir = File.join(dir, ".fizzy-attachments")
  return unless Dir.exist?(attachments_dir)

  Dir.glob(File.join(attachments_dir, "*")).each do |file|
    next unless File.file?(file)
    next if File.size(file) > 100 # Keep files with real content

    File.delete(file)
  end
end

.update_fizzy_work_item(card_internal_id, updates) ⇒ Object

Update or create a work item entry for a Fizzy card. Accepts a hash of fields to merge into the existing entry. Handles both new-format (wi-xxx keyed) and creates new entries properly.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 216

def update_fizzy_work_item(card_internal_id, updates)
  return unless card_internal_id

  map = load_work_item_map
  result = nil
  work_item_id = nil

  # Find existing entry by card internal ID
  map.each do |wid, info|
    next unless info.is_a?(Hash)

    fizzy_source = info.dig("sources", "fizzy")
    next unless fizzy_source && fizzy_source["card_internal_id"] == card_internal_id

    work_item_id = wid
    result = info
    break
  end

  card_number = updates.delete("number")

  if result
    result["sources"]["fizzy"]["card_number"] = card_number if card_number
    result.merge!(updates)
    map[work_item_id] = result
  else
    new_id = generate_work_item_id(branch: updates["branch"], card_number: card_number)
    map[new_id] = {
      "id" => new_id,
      "branch" => updates["branch"],
      "worktree" => updates["worktree"],
      "project" => updates["project"],
      "agent" => updates["agent"],
      "sources" => {
        "fizzy" => {
          "card_internal_id" => card_internal_id,
          "card_number" => card_number
        }.compact
      }
    }.compact.merge(updates.except("branch", "worktree", "project", "agent"))
  end

  save_work_item_map(map)
end

.verify_signature!(request, payload_body, board_key: nil) ⇒ Object

Returns true if signature is valid (or no secret configured). Returns false if signature verification fails.



12
13
14
15
16
17
18
19
20
21
# File 'lib/brainiac/plugins/fizzy/helpers.rb', line 12

def verify_signature!(request, payload_body, board_key: nil)
  signature = request.env["HTTP_X_WEBHOOK_SIGNATURE"]
  return false unless signature

  secret = board_key ? Config.board_webhook_secret(board_key) : ENV.fetch("FIZZY_WEBHOOK_SECRET", nil)
  return false unless secret

  computed = OpenSSL::HMAC.hexdigest("sha256", secret, payload_body)
  Rack::Utils.secure_compare(signature, computed)
end