Module: Legion::Extensions::MicrosoftTeams::Runners::ProfileIngest

Extended by:
Definitions, ProfileIngest
Includes:
Helpers::Client, Helpers::GraphCache, Helpers::HighWaterMark, Helpers::PermissionGuard
Included in:
ProfileIngest
Defined in:
lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb

Constant Summary

Constants included from Helpers::HighWaterMark

Helpers::HighWaterMark::HWM_TTL

Constants included from Helpers::PermissionGuard

Helpers::PermissionGuard::BACKOFF_SCHEDULE

Instance Method Summary collapse

Methods included from Helpers::GraphCache

#cached_graph_get, #graph_cache_ttl, #graph_user_key, #invalidate_graph_cache

Methods included from Helpers::HighWaterMark

#get_extended_hwm, #get_hwm, #hwm_key, #new_messages, #persist_hwm_as_trace, #restore_hwm_from_traces, #set_extended_hwm, #set_hwm, #update_extended_hwm, #update_hwm_from_messages

Methods included from Helpers::PermissionGuard

#denial_info, #guarded_request, #permission_denied?, #record_denial, #reset_denials!

Methods included from Helpers::Client

#bot_connection, #graph_connection, #oauth_connection, #user_path

Instance Method Details

#full_ingest(token:, top_people: 10, message_depth: 50) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 30

def full_ingest(token:, top_people: 10, message_depth: 50, **)
  log.debug("ProfileIngest#full_ingest top_people=#{top_people} message_depth=#{message_depth}")
  self_result = ingest_self(token: token)
  people_result = ingest_people(token: token, top: 25)
  people = people_result[:skipped] ? [] : (people_result[:people] || [])
  conv_result = ingest_conversations(token: token, people: people,
                                     top_people: top_people, message_depth: message_depth)
  teams_result = ingest_teams_and_meetings(token: token)

  { self: self_result, people: people_result, conversations: conv_result, teams: teams_result }
rescue Errors::Throttled => e
  # Once Graph throttles us, the shared circuit is open and every
  # remaining stage would just raise Throttled(attempts: 0)
  # instantly — a burst of identical errors that ingests nothing.
  # Stop the fan-out at the first throttled stage and report it.
  log.warn('[microsoft_teams][profile_ingest] throttled mid-ingest; ' \
           'aborting remaining stages (retry_after=' \
           "#{e.retry_after_known? ? format('%.1f', e.retry_after) : 'unknown'} path=#{e.request})")
  { throttled: true, retry_after: e.retry_after, request: e.request }
end

#incremental_sync(token:, top_people: 10, message_depth: 50) ⇒ Object



240
241
242
243
244
245
246
247
248
249
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 240

def incremental_sync(token:, top_people: 10, message_depth: 50, **)
  ingest_self(token: token)
  people_result = ingest_people(token: token, top: 25)
  people = people_result[:skipped] ? [] : (people_result[:people] || [])

  return { refreshed: true, conversations: 0 } if people.empty?

  ingest_conversations(token: token, people: people,
                       top_people: top_people, message_depth: message_depth)
end

#ingest_conversations(token:, people:, top_people: 10, message_depth: 50) ⇒ Object



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
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 131

def ingest_conversations(token:, people:, top_people: 10, message_depth: 50, **)
  return { ingested: 0 } if people.empty?

  conn = graph_connection(token: token)
  chats = cached_graph_get(conn: conn, path: 'me/chats',
                           params: { '$top' => 50 })
          .then { |body| (body || {}).fetch('value', []) }
  one_on_ones = chats.select { |c| c['chatType'] == 'oneOnOne' }

  email_to_chat = build_chat_member_index(conn: conn, chats: one_on_ones)
  ingested = 0

  people.first(top_people).each do |person|
    email = person.dig('scoredEmailAddresses', 0, 'address')&.downcase
    next unless email

    chat = email_to_chat[email]
    next unless chat

    messages = fetch_new_messages(conn: conn, chat_id: chat['id'], depth: message_depth)
    next if messages.empty?

    extraction = extract_conversation(messages: messages, peer_name: person['displayName'])
    next unless extraction

    memory_runner.store_trace(
      type:            :episodic,
      content_payload: ::JSON.dump({
                                     peer: person['displayName'], chat_id: chat['id'],
        summary: extraction, last_active: messages.first&.dig('createdDateTime')
                                   }),
      domain_tags:     ['teams', 'conversation', "peer:#{person['displayName']}"],
      confidence:      0.6,
      origin:          :direct_experience
    )

    update_extended_hwm(chat_id: chat['id'],
                        last_message_at: messages.map { |m| m['createdDateTime'] }.max,
                        new_message_count: messages.length, ingested: true)
    persist_hwm_as_trace(chat_id: chat['id'])
    ingested += 1
  end

  { ingested: ingested }
# rubocop:disable Legion/RescueLogging/NoCapture
# Re-raise unlogged: full_ingest logs the throttle once and aborts
# the fan-out. A throttle is a fleet signal, not a per-stage error;
# logging it here too would just duplicate the line per stage.
rescue Errors::Throttled
  raise
  # rubocop:enable Legion/RescueLogging/NoCapture
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'ProfileIngest#ingest_conversations')
  { error: e.message, ingested: ingested || 0 }
end

#ingest_people(token:, top: 25) ⇒ Object



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
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 92

def ingest_people(token:, top: 25, **)
  return { skipped: true, reason: :permission_denied } if permission_denied?('/me/people')

  conn = graph_connection(token: token)
  resp = conn.get('me/people', { '$top' => top })

  if resp.respond_to?(:status) && resp.status == 403
    record_denial('/me/people', resp.body.dig('error', 'message') || 'Forbidden')
    return { skipped: true, reason: :permission_denied }
  end

  people = (resp.body || {}).fetch('value', [])
  people.sort_by! { |p| -(p.dig('scoredEmailAddresses', 0, 'relevanceScore') || 0) }

  people.each do |person|
    name = person['displayName'] || 'Unknown'
    memory_runner.store_trace(
      type:            :semantic,
      content_payload: ::JSON.dump(person.slice('displayName', 'jobTitle', 'department',
                                                'officeLocation', 'scoredEmailAddresses')),
      domain_tags:     ['teams', 'peer', "peer:#{name}"],
      confidence:      0.7,
      origin:          :direct_experience
    )
  end

  { people: people, count: people.length }
# rubocop:disable Legion/RescueLogging/NoCapture
# Re-raise unlogged: full_ingest logs the throttle once and aborts
# the fan-out. A throttle is a fleet signal, not a per-stage error;
# logging it here too would just duplicate the line per stage.
rescue Errors::Throttled
  raise
  # rubocop:enable Legion/RescueLogging/NoCapture
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'ProfileIngest#ingest_people')
  { error: e.message, skipped: false }
end

#ingest_self(token:) ⇒ Object



51
52
53
54
55
56
57
58
59
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
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 51

def ingest_self(token:, **)
  conn = graph_connection(token: token)
  profile = conn.get('me').body

  memory_runner.store_trace(
    type:            :identity,
    content_payload: ::JSON.dump(profile),
    domain_tags:     %w[teams self owner],
    confidence:      1.0,
    origin:          :direct_experience
  )

  presence = begin
    conn.get('me/presence').body
  rescue StandardError => e
    handle_exception(e, level: :debug, operation: 'ProfileIngest#ingest_self presence') if defined?(handle_exception)
    {}
  end
  unless presence.empty?
    memory_runner.store_trace(
      type:            :sensory,
      content_payload: ::JSON.dump(presence),
      domain_tags:     %w[teams presence self],
      confidence:      0.8,
      origin:          :direct_experience
    )
  end

  { profile: profile, presence: presence }
# rubocop:disable Legion/RescueLogging/NoCapture
# Re-raise unlogged: full_ingest logs the throttle once and aborts
# the fan-out. A throttle is a fleet signal, not a per-stage error;
# logging it here too would just duplicate the line per stage.
rescue Errors::Throttled
  raise
  # rubocop:enable Legion/RescueLogging/NoCapture
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'ProfileIngest#ingest_self')
  { error: e.message }
end

#ingest_teams_and_meetings(token:) ⇒ Object



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
# File 'lib/legion/extensions/microsoft_teams/runners/profile_ingest.rb', line 187

def ingest_teams_and_meetings(token:, **)
  conn = graph_connection(token: token)
  teams_count = 0

  unless permission_denied?('/me/joinedTeams')
    teams_resp = conn.get('me/joinedTeams')
    teams = (teams_resp.body || {}).fetch('value', [])

    teams.each do |team|
      members_resp = conn.get("teams/#{team['id']}/members")
      members = (members_resp.body || {}).fetch('value', [])
      memory_runner.store_trace(
        type:            :semantic,
        content_payload: ::JSON.dump({ team: team['displayName'], member_count: members.length,
                                       members: members.map { |m| m['displayName'] } }),
        domain_tags:     ['teams', 'org', "team:#{team['displayName']}"],
        confidence:      0.8,
        origin:          :direct_experience
      )
      teams_count += 1
    end
  end

  meetings_count = 0
  unless permission_denied?('/me/onlineMeetings')
    meetings_resp = conn.get('me/onlineMeetings')
    meetings = (meetings_resp.body || {}).fetch('value', [])
    meetings.each do |meeting|
      memory_runner.store_trace(
        type:            :episodic,
        content_payload: ::JSON.dump(meeting.slice('subject', 'startDateTime', 'endDateTime',
                                                   'participants')),
        domain_tags:     %w[teams meeting],
        confidence:      0.5,
        origin:          :direct_experience
      )
      meetings_count += 1
    end
  end

  { teams: teams_count, meetings: meetings_count }
# rubocop:disable Legion/RescueLogging/NoCapture
# Re-raise unlogged: full_ingest logs the throttle once and aborts
# the fan-out. A throttle is a fleet signal, not a per-stage error;
# logging it here too would just duplicate the line per stage.
rescue Errors::Throttled
  raise
  # rubocop:enable Legion/RescueLogging/NoCapture
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'ProfileIngest#ingest_teams_and_meetings')
  { error: e.message }
end