collavre_github 0.6.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/collavre_github/creatives/integrations_controller.rb +253 -36
  3. data/app/controllers/collavre_github/webhooks_controller.rb +563 -44
  4. data/app/javascript/collavre_github.js +32 -123
  5. data/app/jobs/collavre_github/initial_markdown_sync_job.rb +6 -4
  6. data/app/jobs/collavre_github/markdown_sync_job.rb +6 -4
  7. data/app/jobs/collavre_github/pr_blocker_sweep_job.rb +18 -0
  8. data/app/jobs/collavre_github/webhook_delivery_prune_job.rb +14 -0
  9. data/app/models/collavre_github/github_pr_channel.rb +124 -28
  10. data/app/models/collavre_github/repository_link.rb +63 -2
  11. data/app/models/collavre_github/webhook_delivery.rb +159 -0
  12. data/app/services/collavre_github/client.rb +37 -0
  13. data/app/services/collavre_github/markdown_sync/content_creative.rb +56 -0
  14. data/app/services/collavre_github/markdown_sync/content_processor.rb +16 -1
  15. data/app/services/collavre_github/markdown_sync/incremental_sync_service.rb +12 -34
  16. data/app/services/collavre_github/markdown_sync/initial_import_service.rb +6 -19
  17. data/app/services/collavre_github/pr_blocker_monitor.rb +93 -0
  18. data/app/services/collavre_github/pr_channel_state_updater.rb +83 -0
  19. data/app/services/collavre_github/pr_discussion_event.rb +25 -0
  20. data/app/services/collavre_github/repository_identity_synchronizer.rb +145 -0
  21. data/app/services/collavre_github/repository_provisioning_lock.rb +95 -0
  22. data/app/services/collavre_github/tools/concerns/pr_channel_locator.rb +50 -0
  23. data/app/services/collavre_github/tools/pr_monitor_service.rb +82 -62
  24. data/app/services/collavre_github/tools/pr_state_set_service.rb +170 -0
  25. data/app/services/collavre_github/webhook_provisioner.rb +601 -42
  26. data/app/services/collavre_github/webhook_reprovisioner.rb +118 -0
  27. data/config/locales/en.yml +4 -0
  28. data/config/locales/ko.yml +4 -0
  29. data/config/locales/tool_descriptions.en.yml +20 -0
  30. data/config/locales/tool_descriptions.ko.yml +20 -0
  31. data/config/routes.rb +13 -3
  32. data/db/migrate/20260727000001_add_webhook_hook_id_to_github_repository_links.rb +17 -0
  33. data/db/migrate/20260727000002_create_github_webhook_deliveries.rb +30 -0
  34. data/db/migrate/20260729000000_add_repository_id_index_to_github_repository_links.rb +13 -0
  35. data/db/seeds.rb +2 -1
  36. data/lib/collavre_github/engine.rb +9 -0
  37. data/lib/collavre_github/version.rb +1 -1
  38. metadata +19 -2
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CollavreGithub
4
+ # Out-of-band PR state correction: applies the same end-state the webhook
5
+ # would have produced when a `pull_request` event was never delivered (hook
6
+ # added after the merge, delivery failure, repo renamed mid-flight).
7
+ #
8
+ # The webhook path does NOT route through here on purpose. There, `handle`
9
+ # only *returns* the closing message and WebhooksController injects it and
10
+ # detaches, because the controller owns the per-channel lock that also
11
+ # de-duplicates GitHub retries. This class owns the whole transition instead,
12
+ # so it takes the lock itself. Both paths share the message builders on
13
+ # GithubPrChannel, which is the part that would otherwise drift.
14
+ class PrChannelStateUpdater
15
+ # status ∈ :updated / :noop
16
+ Result = Struct.new(:status, :channel, :previous_state, keyword_init: true)
17
+
18
+ def self.call(channel:, state:)
19
+ new(channel: channel, state: state).call
20
+ end
21
+
22
+ def initialize(channel:, state:)
23
+ @channel = channel
24
+ @state = state.to_s
25
+ unless GithubPrChannel::PR_STATES.include?(@state)
26
+ raise ArgumentError, "Invalid pr_state: #{state.inspect}"
27
+ end
28
+ end
29
+
30
+ def call
31
+ channel.with_lock do
32
+ previous_state = channel.pr_state
33
+ next Result.new(status: :noop, channel: channel, previous_state: previous_state) if settled?
34
+
35
+ if state == "open"
36
+ reopen!
37
+ else
38
+ close!
39
+ end
40
+ Result.new(status: :updated, channel: channel, previous_state: previous_state)
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :channel, :state
47
+
48
+ # A repeat call must not inject a second timeline message. "Same state" is
49
+ # not enough on its own: a channel can read "open" while sitting detached
50
+ # (dismissed by the user, or reopened only in GitHub), and that still needs
51
+ # the reactivation half of the transition applied.
52
+ def settled?
53
+ return false unless channel.pr_state == state
54
+
55
+ if state == "open"
56
+ channel.active? && !channel.dismissed?
57
+ else
58
+ channel.detached?
59
+ end
60
+ end
61
+
62
+ # Mirrors WebhooksController's reopen handling: state back to active and
63
+ # the chip un-dismissed, so the channel resurfaces under `not_dismissed`
64
+ # and resumes receiving events.
65
+ def reopen!
66
+ channel.state = :active
67
+ channel.dismissed_at = nil
68
+ channel.pr_state = "open"
69
+ channel.save!
70
+ channel.inject_into_topic!(channel.reopened_message)
71
+ end
72
+
73
+ # Mirrors the closed-event path: set the badge, post the closing message,
74
+ # then detach — in that order, so the chip stays visible (now merged /
75
+ # closed) until the user dismisses it.
76
+ def close!
77
+ channel.pr_state = state
78
+ channel.save!
79
+ channel.inject_into_topic!(channel.closed_message(state))
80
+ channel.detach! if channel.active?
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,25 @@
1
+ module CollavreGithub
2
+ class PrDiscussionEvent
3
+ Definition = Data.define(:resource, :action, :handler, :endpoint, :timestamp)
4
+
5
+ EVENTS = {
6
+ "issue_comment" => Definition.new("comment", "created", :handle_issue_comment, "issues/%s/comments", "created_at"),
7
+ "pull_request_review_comment" => Definition.new("comment", "created", :handle_review_comment, "pulls/%s/comments", "created_at"),
8
+ "pull_request_review" => Definition.new("review", "submitted", :handle_review_submitted, "pulls/%s/reviews", "submitted_at")
9
+ }.freeze
10
+
11
+ def self.poll(client, repo, number, since:)
12
+ EVENTS.flat_map do |event, definition|
13
+ client.pull_request_discussion(repo, format(definition.endpoint, number)).filter_map do |resource|
14
+ timestamp = resource[definition.timestamp]&.to_time
15
+ next unless resource["id"].present? && timestamp && timestamp >= since
16
+
17
+ resource["state"] = resource["state"].to_s.downcase if definition.resource == "review"
18
+ payload = { "action" => definition.action, definition.resource => resource }
19
+ payload["issue"] = { "number" => number, "pull_request" => {} } if event == "issue_comment"
20
+ [ timestamp, event, payload ]
21
+ end
22
+ end.sort_by(&:first)
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,145 @@
1
+ module CollavreGithub
2
+ # Persists a repository identity established through trusted evidence and
3
+ # keeps attached channel routing keys in sync with the canonical GitHub name.
4
+ #
5
+ # Stable repository ids are authoritative. A NULL-id anchor is accepted only
6
+ # by the explicit operator reattachment workflow; hook registrations and HMAC
7
+ # secrets are not row identity because older provisioners propagated both.
8
+ class RepositoryIdentitySynchronizer
9
+ def self.call(
10
+ anchor:,
11
+ repository_id:,
12
+ full_name:,
13
+ trusted_secret: nil,
14
+ allow_anchor_backfill: false
15
+ )
16
+ return [] if anchor.blank? || repository_id.blank? || full_name.blank?
17
+
18
+ RepositoryProvisioningLock.with_repository_name_lock(full_name) do
19
+ new(
20
+ anchor: anchor,
21
+ repository_id: repository_id,
22
+ full_name: full_name,
23
+ trusted_secret: trusted_secret,
24
+ allow_anchor_backfill: allow_anchor_backfill
25
+ ).call
26
+ end
27
+ end
28
+
29
+ def initialize(
30
+ anchor:,
31
+ repository_id:,
32
+ full_name:,
33
+ trusted_secret:,
34
+ allow_anchor_backfill:
35
+ )
36
+ @anchor = anchor
37
+ @repository_id = repository_id
38
+ @full_name = full_name.to_s
39
+ @trusted_secret = trusted_secret
40
+ @allow_anchor_backfill = allow_anchor_backfill
41
+ end
42
+
43
+ def call
44
+ return [] if anchor.blank? || repository_id.blank? || full_name.blank?
45
+
46
+ synchronized = []
47
+ old_names_by_creative = Hash.new { |hash, key| hash[key] = [] }
48
+
49
+ RepositoryLink.transaction do
50
+ candidate_links.each do |link|
51
+ old_name = link.repository_full_name
52
+ survivor = synchronize_link(link)
53
+ next unless survivor
54
+
55
+ synchronized << survivor
56
+ if old_name.to_s == full_name
57
+ next
58
+ end
59
+
60
+ old_names_by_creative[old_name.to_s.downcase] << survivor.creative_id
61
+ end
62
+
63
+ old_names_by_creative.each do |old_name, creative_ids|
64
+ rename_channels(old_name, creative_ids.uniq)
65
+ end
66
+ end
67
+
68
+ synchronized.uniq(&:id)
69
+ end
70
+
71
+ private
72
+
73
+ attr_reader :anchor,
74
+ :repository_id,
75
+ :full_name,
76
+ :trusted_secret,
77
+ :allow_anchor_backfill
78
+
79
+ def candidate_links
80
+ links = RepositoryLink.where(repository_id: repository_id).to_a
81
+ links << anchor if allow_anchor_backfill || anchor.repository_id.to_s == repository_id.to_s
82
+ links.uniq(&:id)
83
+ end
84
+
85
+ def synchronize_link(link)
86
+ if link.repository_full_name.to_s == full_name &&
87
+ link.repository_id.to_s == repository_id.to_s
88
+ return link
89
+ end
90
+
91
+ conflict = RepositoryLink.identity_conflict_in_link_scope(
92
+ creative: link.creative,
93
+ full_name: full_name,
94
+ repository_id: repository_id,
95
+ excluding_id: link.id
96
+ )
97
+ return if conflict
98
+
99
+ survivor = RepositoryLink
100
+ .where(creative_id: link.creative_id)
101
+ .where("LOWER(repository_full_name) = ?", full_name.downcase)
102
+ .where.not(id: link.id)
103
+ .first
104
+
105
+ if survivor
106
+ return unless survivor.repository_id.to_s == repository_id.to_s
107
+
108
+ merge_links!(obsolete: link, survivor: survivor)
109
+ return survivor
110
+ end
111
+
112
+ link.update_columns(repository_id: repository_id, repository_full_name: full_name)
113
+ link
114
+ end
115
+
116
+ def merge_links!(obsolete:, survivor:)
117
+ survivor.update!(
118
+ webhook_secret: trusted_secret.presence || survivor.webhook_secret,
119
+ webhook_hook_id: survivor.webhook_hook_id || obsolete.webhook_hook_id,
120
+ markdown_sync_enabled: survivor.markdown_sync_enabled? || obsolete.markdown_sync_enabled?,
121
+ markdown_root_creative_id: survivor.markdown_root_creative_id || obsolete.markdown_root_creative_id,
122
+ sync_branch: survivor.sync_branch.presence || obsolete.sync_branch,
123
+ last_synced_at: [ survivor.last_synced_at, obsolete.last_synced_at ].compact.max
124
+ )
125
+ obsolete.destroy!
126
+ end
127
+
128
+ def rename_channels(old_name, creative_ids)
129
+ GithubPrChannel.where("LOWER(repo_full_name) = ?", old_name).find_each do |channel|
130
+ creative = channel.topic&.creative
131
+ next unless creative
132
+
133
+ candidate_ids = [ creative.id ] + creative.ancestors.pluck(:id)
134
+ next if (creative_ids & candidate_ids).empty?
135
+ next if RepositoryLink.conflicting_repository_in_scope?(
136
+ creative: creative,
137
+ full_name: old_name,
138
+ repository_id: repository_id
139
+ )
140
+
141
+ channel.synchronize_repository_name!(full_name)
142
+ end
143
+ end
144
+ end
145
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "monitor"
5
+
6
+ module CollavreGithub
7
+ # Serializes link persistence and remote webhook mutation for one stable
8
+ # GitHub repository identity. Without this boundary, two creatives attaching
9
+ # a previously unseen repository can each provision from an uncommitted link
10
+ # and publish different secrets (or create duplicate hooks).
11
+ class RepositoryProvisioningLock
12
+ LOCK_PURPOSE = "collavre_github:repository_provisioning".freeze
13
+
14
+ @mutex_registry_guard = Mutex.new
15
+ @mutex_registry = {}
16
+
17
+ class << self
18
+ def with_lock(repository_id, &block)
19
+ key = repository_id.to_s
20
+ raise ArgumentError, "repository_id is required" if key.blank?
21
+
22
+ with_key_lock(key, &block)
23
+ end
24
+
25
+ def with_repository_name_lock(full_name, &block)
26
+ normalized_name = full_name.to_s.downcase
27
+ raise ArgumentError, "repository full name is required" if normalized_name.blank?
28
+
29
+ with_key_lock("name:#{normalized_name}", &block)
30
+ end
31
+
32
+ private
33
+
34
+ def with_key_lock(key, &block)
35
+ if postgres?
36
+ with_postgres_lock(key, &block)
37
+ else
38
+ # SQLite is used by tests and the single-process desktop app. Its
39
+ # adapter has no advisory-lock primitive, so use the process boundary.
40
+ with_process_lock(key, &block)
41
+ end
42
+ end
43
+
44
+ def postgres?
45
+ CollavreGithub::RepositoryLink.connection.adapter_name.casecmp?("PostgreSQL")
46
+ end
47
+
48
+ def with_postgres_lock(key)
49
+ CollavreGithub::RepositoryLink.connection_pool.with_connection do |connection|
50
+ advisory_key = advisory_lock_key(key)
51
+ # Schedule the matching unlock before asking PostgreSQL to acquire.
52
+ # If an asynchronous exception lands after PostgreSQL grants the lock
53
+ # but before the adapter returns, the ensure still releases it rather
54
+ # than returning a locked session to the connection pool.
55
+ unlock_required = true
56
+ connection.select_value("SELECT pg_advisory_lock(#{connection.quote(advisory_key)})")
57
+ yield
58
+ ensure
59
+ if unlock_required
60
+ connection.select_value("SELECT pg_advisory_unlock(#{connection.quote(advisory_key)})")
61
+ end
62
+ end
63
+ end
64
+
65
+ def advisory_lock_key(key)
66
+ Digest::SHA256.digest("#{LOCK_PURPOSE}:#{key}").unpack1("q>")
67
+ end
68
+
69
+ def with_process_lock(key)
70
+ mutex = register_mutex(key)
71
+ mutex.synchronize { yield }
72
+ ensure
73
+ unregister_mutex(key, mutex) if mutex
74
+ end
75
+
76
+ def register_mutex(key)
77
+ @mutex_registry_guard.synchronize do
78
+ entry = (@mutex_registry[key] ||= { mutex: Monitor.new, users: 0 })
79
+ entry[:users] += 1
80
+ entry[:mutex]
81
+ end
82
+ end
83
+
84
+ def unregister_mutex(key, mutex)
85
+ @mutex_registry_guard.synchronize do
86
+ entry = @mutex_registry[key]
87
+ return unless entry && entry[:mutex].equal?(mutex)
88
+
89
+ entry[:users] -= 1
90
+ @mutex_registry.delete(key) if entry[:users].zero?
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CollavreGithub
4
+ module Tools
5
+ module Concerns
6
+ # Shared PR-URL parsing and channel lookup for the PR-channel tools
7
+ # (pr_monitor attaches, pr_state_set corrects). Both must agree on how a
8
+ # URL maps to a stored channel or a state correction would silently miss
9
+ # the very channel the monitor created.
10
+ module PrChannelLocator
11
+ extend ActiveSupport::Concern
12
+
13
+ PR_URL_RE = %r{\Ahttps?://github\.com/([^/]+/[^/]+)/pull/(\d+)\z}.freeze
14
+
15
+ private
16
+
17
+ # GitHub owner/repo identifiers are case-insensitive but webhook
18
+ # payloads always carry the canonical case. Normalize on parse so user
19
+ # input like "Owner/Repo" still matches incoming events.
20
+ #
21
+ # @return [[String, Integer]] downcased repo full name and PR number
22
+ def parse_pr_url(pr_url)
23
+ m = pr_url.to_s.match(PR_URL_RE)
24
+ raise ArgumentError, "Invalid PR URL: #{pr_url}" unless m
25
+
26
+ [ m[1].downcase, m[2].to_i ]
27
+ end
28
+
29
+ # Ruby-level compare instead of a WHERE: legacy rows can carry
30
+ # mixed-case repo names, and the dispatch path matches the same way.
31
+ def lookup_channel(topic, repo, pr_number)
32
+ CollavreGithub::GithubPrChannel.where(topic_id: topic.id).find do |c|
33
+ c.repo_full_name.to_s.downcase == repo.downcase && c.pr_number == pr_number
34
+ end
35
+ end
36
+
37
+ # Creatives whose RepositoryLinks govern this topic: the topic's own
38
+ # creative plus its ancestors. Mirrors pr_monitor's provisioning scope,
39
+ # so a tool can never reach a GitHub account the monitor itself could
40
+ # not have used.
41
+ def scoped_creative_ids(topic)
42
+ creative = topic.creative
43
+ return [] unless creative
44
+
45
+ [ creative.id ] + creative.ancestors.pluck(:id)
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -8,14 +8,15 @@ module CollavreGithub
8
8
  class PrMonitorService
9
9
  extend T::Sig
10
10
  extend ToolMeta
11
-
12
- PR_URL_RE = %r{\Ahttps?://github\.com/([^/]+/[^/]+)/pull/(\d+)\z}.freeze
11
+ include Concerns::PrChannelLocator
13
12
 
14
13
  tool_name "pr_monitor"
15
14
  tool_description <<~DESC.strip
16
15
  Attach a GitHub PR monitor to a Collavre topic. After attachment,
17
- PR comments, review comments, and review submissions are injected
18
- into the topic as chat messages. Idempotent.
16
+ PR comments, reviews, merge conflicts, and failed CI checks are posted
17
+ as topic messages. Every five minutes, verified repository links are
18
+ checked for missed comments and reviews, merge conflicts, and failed
19
+ CI checks. Returns a typed channel reference. Idempotent.
19
20
  DESC
20
21
 
21
22
  tool_param :topic_id, description: "The Collavre topic id to attach the PR channel to."
@@ -23,13 +24,7 @@ module CollavreGithub
23
24
 
24
25
  sig { params(topic_id: Integer, pr_url: String).returns(T::Hash[Symbol, T.untyped]) }
25
26
  def call(topic_id:, pr_url:)
26
- m = pr_url.match(PR_URL_RE)
27
- raise ArgumentError, "Invalid PR URL: #{pr_url}" unless m
28
- # GitHub owner/repo identifiers are case-insensitive but webhook payloads
29
- # always carry the canonical case. Normalize on store so user input
30
- # like "Owner/Repo" still matches incoming events.
31
- repo = m[1].downcase
32
- pr_number = m[2].to_i
27
+ repo, pr_number = parse_pr_url(pr_url)
33
28
 
34
29
  topic = Collavre::Topic.find(topic_id)
35
30
  Collavre::Tools::TopicAuthorizer.authorize_write!(topic)
@@ -41,7 +36,14 @@ module CollavreGithub
41
36
  channel.inject_into_topic!(channel.attached_message)
42
37
  end
43
38
 
44
- result = { ok: true, channel_id: channel.id, repo: repo, pr_number: pr_number }
39
+ result = {
40
+ ok: true,
41
+ channel_ref: "ch_#{channel.id}",
42
+ topic: { id: topic.id, name: topic.name },
43
+ creative: { id: topic.creative.id, title: topic.creative.creative_snippet },
44
+ repo: repo,
45
+ pr_number: pr_number
46
+ }
45
47
  warning = ensure_webhook_events(topic, repo)
46
48
  result[:webhook_warning] = warning if warning
47
49
  result
@@ -70,13 +72,6 @@ module CollavreGithub
70
72
  )
71
73
  end
72
74
 
73
- sig { params(topic: Collavre::Topic, repo: String, pr_number: Integer).returns(T.nilable(CollavreGithub::GithubPrChannel)) }
74
- def lookup_channel(topic, repo, pr_number)
75
- CollavreGithub::GithubPrChannel.where(topic_id: topic.id).find do |c|
76
- c.repo_full_name.to_s.downcase == repo.downcase && c.pr_number == pr_number
77
- end
78
- end
79
-
80
75
  # Make sure the repo's webhook subscribes to the PR-channel events
81
76
  # (issue_comment / pull_request_review / pull_request_review_comment).
82
77
  # Without these, GitHub never delivers comment payloads and the channel
@@ -84,62 +79,87 @@ module CollavreGithub
84
79
  # Returns a warning string when provisioning cannot run or fails; nil on
85
80
  # success so the MCP response stays clean.
86
81
  def ensure_webhook_events(topic, repo)
87
- scoped_link = scoped_repository_link_for(topic, repo)
88
- return "no RepositoryLink found for #{repo} in topic creative scope; webhook events not auto-provisioned" unless scoped_link
89
-
90
- # Provision through the *global* primary link (lowest id across all
91
- # creatives), not the scoped link. WebhookProvisioner only patches hook
92
- # events when the link IS the primary; non-primary links short-circuit
93
- # to secret alignment and skip the GitHub edit_hook call. So if we
94
- # provisioned the scoped link and it was not the global primary, the
95
- # existing hook would keep its old event list. The scoped link is only
96
- # used as an authorization gate above.
97
- provisioning_link = global_primary_repository_link_for(repo) || scoped_link
98
-
99
- account = provisioning_link.github_account
100
- return "RepositoryLink for #{repo} has no GitHub account; webhook events not auto-provisioned" unless account
101
-
102
- results = CollavreGithub::WebhookProvisioner.ensure_for_links(
103
- account: account,
104
- links: [ provisioning_link ],
105
- webhook_url: github_webhook_url
106
- )
107
- status = results.first&.last
108
- # :failed means Client returned nil (Octokit/Faraday error rescued in
109
- # CollavreGithub::Client). Surface that to the MCP caller so they know
110
- # webhook events were not actually patched.
111
- return "webhook provisioning failed: GitHub API rejected the hook request (see logs)" if status == :failed
112
- nil
82
+ scoped_repository_ids(topic, repo).each do |repository_id|
83
+ outcome = CollavreGithub::RepositoryProvisioningLock.with_lock(repository_id) do
84
+ scoped_links = verified_scoped_repository_links_for(
85
+ topic,
86
+ repo,
87
+ repository_id: repository_id
88
+ )
89
+ next :unverified if scoped_links.empty?
90
+
91
+ all_failed = scoped_links.all? do |scoped_link|
92
+ results = CollavreGithub::WebhookProvisioner.ensure_for_links(
93
+ account: scoped_link.github_account,
94
+ links: [ scoped_link ],
95
+ webhook_url: github_webhook_url,
96
+ force_hook_refresh: true
97
+ )
98
+ results.first&.last == :failed
99
+ end
100
+ if all_failed
101
+ "webhook provisioning failed: GitHub API rejected the hook request (see logs)"
102
+ end
103
+ end
104
+ next if outcome == :unverified
105
+
106
+ # A nil outcome means a verified hook was refreshed successfully.
107
+ # :shared is also success: the registered hook was patched before
108
+ # WebhookProvisioner returned that status.
109
+ return outcome
110
+ end
111
+
112
+ "no verified RepositoryLink found for #{repo} in topic creative scope; " \
113
+ "webhook events not auto-provisioned"
113
114
  rescue => e
114
115
  Rails.logger.warn("[pr_monitor] webhook provisioning failed for #{repo}: #{e.class}: #{e.message}")
115
116
  "webhook provisioning failed: #{e.message}"
116
117
  end
117
118
 
118
- # Authorization gate: a RepositoryLink for `repo` must live in this
119
- # topic's creative subtree (the topic creative itself or one of its
120
- # ancestors). Without one, the dispatch path in WebhooksController would
121
- # silently drop events for this topic anyway.
122
- def scoped_repository_link_for(topic, repo)
123
- creative = topic.creative
124
- return nil unless creative
119
+ def scoped_repository_ids(topic, repo)
120
+ candidate_ids = scoped_creative_ids(topic)
121
+ return [] if candidate_ids.empty?
125
122
 
126
- candidate_ids = [ creative.id ] + creative.ancestors.pluck(:id)
127
123
  CollavreGithub::RepositoryLink
128
124
  .where("LOWER(repository_full_name) = ?", repo.downcase)
129
125
  .where(creative_id: candidate_ids)
130
- .order(:id)
131
- .first
126
+ .where.not(repository_id: nil)
127
+ .distinct
128
+ .pluck(:repository_id)
132
129
  end
133
130
 
134
- # Mirrors WebhookProvisioner#primary_link_for: the lowest-id link for the
135
- # repo across ALL creatives. This is the link whose secret + events the
136
- # hook is aligned to, so we must provision through it to trigger an
137
- # actual edit_hook call.
138
- def global_primary_repository_link_for(repo)
139
- CollavreGithub::RepositoryLink
131
+ # Authorization and identity gate: a RepositoryLink for `repo` must live
132
+ # in this topic's creative subtree, carry a stable repository id, and
133
+ # resolve to that same id through its GitHub account. A stored name alone
134
+ # is not safe provisioning evidence because GitHub can reuse a renamed
135
+ # repository's old name.
136
+ def verified_scoped_repository_links_for(topic, repo, repository_id:)
137
+ candidate_ids = scoped_creative_ids(topic)
138
+ return [] if candidate_ids.empty?
139
+
140
+ candidates = CollavreGithub::RepositoryLink
140
141
  .where("LOWER(repository_full_name) = ?", repo.downcase)
142
+ .where(creative_id: candidate_ids)
143
+ .where(repository_id: repository_id)
141
144
  .order(:id)
142
- .first
145
+ .to_a
146
+ identities = {}
147
+
148
+ candidates.uniq(&:github_account_id).select do |link|
149
+ account = link.github_account
150
+ next false if link.repository_id.blank? || account.nil?
151
+
152
+ identity = identities.fetch(account.id) do
153
+ identities[account.id] = CollavreGithub::Client.new(account).repository_identity(repo)
154
+ rescue Octokit::Error, Faraday::Error => e
155
+ Rails.logger.warn(
156
+ "[pr_monitor] repository identity lookup failed for #{repo} through " \
157
+ "account #{account.id}: #{e.class}: #{e.message}"
158
+ )
159
+ identities[account.id] = nil
160
+ end
161
+ identity&.id.to_s == link.repository_id.to_s
162
+ end
143
163
  end
144
164
 
145
165
  def github_webhook_url