Module: Legion::Gaia

Extended by:
Logging, TeamsAuth
Includes:
Logging::Helper
Defined in:
lib/legion/gaia.rb,
lib/legion/gaia/gut.rb,
lib/legion/gaia/router.rb,
lib/legion/gaia/routes.rb,
lib/legion/gaia/logging.rb,
lib/legion/gaia/version.rb,
lib/legion/gaia/advisory.rb,
lib/legion/gaia/registry.rb,
lib/legion/gaia/settings.rb,
lib/legion/gaia/workflow.rb,
lib/legion/gaia/proactive.rb,
lib/legion/gaia/bond_store.rb,
lib/legion/gaia/disclosure.rb,
lib/legion/gaia/teams_auth.rb,
lib/legion/gaia/input_frame.rb,
lib/legion/gaia/runner_host.rb,
lib/legion/gaia/anticipation.rb,
lib/legion/gaia/bond_tracker.rb,
lib/legion/gaia/output_frame.rb,
lib/legion/gaia/phase_wiring.rb,
lib/legion/gaia/tick_history.rb,
lib/legion/gaia/bond_registry.rb,
lib/legion/gaia/cognitive_bus.rb,
lib/legion/gaia/output_router.rb,
lib/legion/gaia/partner_model.rb,
lib/legion/gaia/session_store.rb,
lib/legion/gaia/audit_observer.rb,
lib/legion/gaia/death_protocol.rb,
lib/legion/gaia/sensory_buffer.rb,
lib/legion/gaia/visible_growth.rb,
lib/legion/gaia/channel_adapter.rb,
lib/legion/gaia/offline_handler.rb,
lib/legion/gaia/workflow/errors.rb,
lib/legion/gaia/actors/heartbeat.rb,
lib/legion/gaia/channel_registry.rb,
lib/legion/gaia/intent_classifier.rb,
lib/legion/gaia/notification_gate.rb,
lib/legion/gaia/workflow/instance.rb,
lib/legion/gaia/behavioral_synapse.rb,
lib/legion/gaia/proactive_delivery.rb,
lib/legion/gaia/router/agent_bridge.rb,
lib/legion/gaia/tracker_persistence.rb,
lib/legion/gaia/workflow/checkpoint.rb,
lib/legion/gaia/workflow/definition.rb,
lib/legion/gaia/channels/cli_adapter.rb,
lib/legion/gaia/proactive_dispatcher.rb,
lib/legion/gaia/router/router_bridge.rb,
lib/legion/gaia/router/worker_routing.rb,
lib/legion/gaia/channel_aware_renderer.rb,
lib/legion/gaia/channels/slack_adapter.rb,
lib/legion/gaia/channels/teams_adapter.rb,
lib/legion/gaia/notification_gate/delay_queue.rb,
lib/legion/gaia/channels/teams/webhook_handler.rb,
lib/legion/gaia/channels/slack/signing_verifier.rb,
lib/legion/gaia/router/transport/exchanges/gaia.rb,
lib/legion/gaia/router/transport/queues/inbound.rb,
lib/legion/gaia/router/transport/queues/outbound.rb,
lib/legion/gaia/channels/teams/bot_framework_auth.rb,
lib/legion/gaia/channels/teams/conversation_store.rb,
lib/legion/gaia/notification_gate/presence_evaluator.rb,
lib/legion/gaia/notification_gate/schedule_evaluator.rb,
lib/legion/gaia/notification_gate/behavioral_evaluator.rb,
lib/legion/gaia/router/transport/messages/input_frame_message.rb,
lib/legion/gaia/router/transport/messages/output_frame_message.rb

Overview

rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Modules: Actors, Advisory, Anticipation, BehavioralSynapse, BondRegistry, BondTracker, Channels, DeathProtocol, Disclosure, Gut, IntentClassifier, Logging, OfflineHandler, PartnerModel, PhaseWiring, Proactive, ProactiveDelivery, Router, Routes, Settings, TeamsAuth, TrackerPersistence, VisibleGrowth, Workflow Classes: AuditObserver, BondStore, ChannelAdapter, ChannelAwareRenderer, ChannelRegistry, CognitiveBus, InputFrame, NotificationGate, OutputFrame, OutputRouter, ProactiveDispatcher, Registry, RunnerHost, SensoryBuffer, SessionStore, TickHistory

Constant Summary collapse

ABSENCE_SIGNAL_THRESHOLD =
5
ABSENCE_SIGNAL_COOLDOWN =
1800
ABSENCE_SIGNAL_SALIENCE =
0.75
ABSENCE_SIGNAL_TEXT =
'partner absence exceeded expected pattern'
ABSENCE_PATTERN_CACHE_TTL =
60
VERSION =
'0.9.67'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.agent_bridgeObject (readonly)

Returns the value of attribute agent_bridge.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def agent_bridge
  @agent_bridge
end

.channel_registryObject (readonly)

Returns the value of attribute channel_registry.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def channel_registry
  @channel_registry
end

.last_valencesObject (readonly)

Returns the value of attribute last_valences.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def last_valences
  @last_valences
end

.output_routerObject (readonly)

Returns the value of attribute output_router.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def output_router
  @output_router
end

.partner_observationsObject (readonly)

Returns the value of attribute partner_observations.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def partner_observations
  @partner_observations
end

.registryObject (readonly)

Returns the value of attribute registry.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def registry
  @registry
end

.router_bridgeObject (readonly)

Returns the value of attribute router_bridge.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def router_bridge
  @router_bridge
end

.sensory_bufferObject (readonly)

Returns the value of attribute sensory_buffer.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def sensory_buffer
  @sensory_buffer
end

.session_storeObject (readonly)

Returns the value of attribute session_store.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def session_store
  @session_store
end

.tick_countObject (readonly)

Returns the value of attribute tick_count.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def tick_count
  @tick_count
end

.tick_historyObject (readonly)

Returns the value of attribute tick_history.



57
58
59
# File 'lib/legion/gaia.rb', line 57

def tick_history
  @tick_history
end

Class Method Details

.advise(conversation_id:, messages:, caller:) ⇒ Object



65
66
67
# File 'lib/legion/gaia.rb', line 65

def advise(conversation_id:, messages:, caller:)
  Advisory.advise(conversation_id: conversation_id, messages: messages, caller: caller)
end

.boot(mode: nil) ⇒ Object



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/gaia.rb', line 69

def boot(mode: nil)
  @mode = mode || (settings&.dig(:router, :mode) ? :router : :agent)
  @shutting_down = false
  @active_heartbeats = 0
  @quiescing_phase_handlers_cache = nil
  log.info("Legion::Gaia booting mode=#{@mode}")

  if router_mode?
    boot_router
  else
    boot_agent
  end

  @started = true
  settings_hash = settings
  settings_hash[:connected] = true if settings_hash

  register_routes
  check_teams_auth

  log.info("Legion::Gaia booted mode=#{@mode} summary=#{boot_summary}")
end

.drain_growth_framesObject



335
336
337
338
339
# File 'lib/legion/gaia.rb', line 335

def drain_growth_frames
  frames = @pending_growth_frames || []
  @pending_growth_frames = []
  frames
end

.erase_attribution!(identity:) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/legion/gaia.rb', line 260

def erase_attribution!(identity:)
  store = apollo_local_store
  unless store
    log.info("[gaia] erase_attribution! skipped identity=#{identity} reason=no_apollo_local")
    return { erased: false, identity: identity, count: 0, reason: :no_apollo_local }
  end

  tags = %w[self-knowledge attribution] + ["partner:#{identity}"]
  # TODO: legion-apollo needs delete_by_tags(tags:) — using query_by_tags + individual deletes once available
  # Until then: store.delete_by_tags is the target API; this no-ops with count=0 until implemented
  count = 0
  if store.respond_to?(:delete_by_tags)
    result = store.delete_by_tags(tags: tags)
    count = result[:count].to_i if result.is_a?(Hash)
  else
    log.info("[gaia] erase_attribution! identity=#{identity} " \
             'reason=delete_by_tags_not_available count=0')
  end
  log.info("[gaia] erase_attribution! identity=#{identity} count=#{count}")
  { erased: true, identity: identity, count: count }
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'gaia.erase_attribution', identity: identity)
  { erased: false, identity: identity, count: 0 }
end

.heartbeatObject



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
# File 'lib/legion/gaia.rb', line 156

def heartbeat(**)
  return { error: :not_started } unless begin_heartbeat

  begin
    signals = @sensory_buffer.drain
    @registry.ensure_wired

    tick_host = @registry.tick_host
    unless tick_host
      unless @tick_unavailable_warned
        log.warn('[gaia] lex-tick not available, will retry next heartbeat')
        @tick_unavailable_warned = true
      end
      return { error: :no_tick_extension }
    end
    @tick_unavailable_warned = false if @tick_unavailable_warned

    phase_handlers = quiescing_phase_handlers(@registry.phase_handlers)

    log.debug("[gaia] heartbeat signals=#{signals.size} wired_phases=#{phase_handlers.size}")

    observations = @partner_observations.dup
    @partner_observations = []

    result = tick_host.execute_tick(signals: signals, phase_handlers: phase_handlers,
                                    partner_observations: observations)

    @tick_history&.record(result)
    @tick_count = (@tick_count || 0) + 1

    if result.is_a?(Hash) && result[:results]
      valence_result = result[:results][:emotional_evaluation]
      @last_valences = [valence_result[:valence]] if valence_result.is_a?(Hash) && valence_result[:valence]
      tick_host.last_tick_result = result
      PhaseWiring.capture_tick_results(result[:results])
      log_cognitive_markers(result, signals: signals, observations: observations)
    end

    check_partner_absence(observations, phase_handlers)

    feed_notification_gate(result)
    @output_router&.process_delayed

    maybe_flush_trackers

    if result.is_a?(Hash) && result[:results]
      process_dream_proactive(result[:results])
      try_dispatch_pending
    end

    result
  ensure
    finish_heartbeat
  end
end

.ingest(input_frame) ⇒ Object



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/gaia.rb', line 212

def ingest(input_frame)
  return { ingested: false, reason: :not_started } unless started?

  identity = extract_identity(input_frame)
  if identity && (BondRegistry.terminating?(identity.to_s) || BondRegistry.terminated?(identity.to_s))
    log.warn("[gaia] rejected ingest for terminated/terminating identity=#{identity}")
    return { ingested: false, reason: :identity_terminated }
  end

  signal = input_frame.to_signal
  @sensory_buffer.push(signal)

  session = @session_store&.find_or_create(identity: identity || :anonymous)
  @session_store&.touch(session.id, channel_id: input_frame.channel_id) if session

  if identity
    BondRegistry.record_channel(identity.to_s, channel_id: input_frame.channel_id,
                                               channel_identity: channel_identity(input_frame))
  end
  observe_interlocutor(input_frame, identity) if identity && identity != :anonymous

  log.info(
    "Legion::Gaia ingested frame_id=#{input_frame.id} " \
    "channel=#{input_frame.channel_id} buffer_depth=#{@sensory_buffer.size}"
  )
  { ingested: true, buffer_depth: @sensory_buffer.size, session_id: session&.id }
end

.mark_pipeline_observation(exchange_id) ⇒ Object



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/legion/gaia.rb', line 384

def mark_pipeline_observation(exchange_id)
  return if exchange_id.nil?

  @pipeline_observations ||= {}
  @pipeline_observation_order ||= []

  @pipeline_observations[exchange_id] = true
  @pipeline_observation_order << exchange_id

  max_size = settings&.dig(:pipeline_observation, :max_tracked) || 10_000
  while @pipeline_observation_order.size > max_size
    oldest = @pipeline_observation_order.shift
    @pipeline_observations.delete(oldest)
  end
end

.observe_from_pipeline(identity:, caller:, exchange_id:) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/legion/gaia.rb', line 341

def observe_from_pipeline(identity:, caller:, exchange_id:)
  return unless started?

  caller_type = caller&.dig(:requested_by, :type)
  return unless caller_type == :human

  identity_str = identity.to_s
  return if identity_str.empty?
  return if identity_lifecycle_blocked?(identity_str)
  return if pipeline_observation_seen?(exchange_id)

  mark_pipeline_observation(exchange_id)

  if BondRegistry.bond(identity_str) == :unknown
    if BondRegistry.partner_entry.nil?
      BondRegistry.register(identity_str, bond: :partner, priority: :primary,
                                          origin: :provisional,
                                          strength: settings&.dig(:partner, :prior_strength) || 0.5)
      log.info("[gaia] pipeline duckling bond identity=#{identity_str}")
    else
      BondRegistry.register(identity_str, bond: nil)
    end
  end

  BondRegistry.reinforce(identity_str, multiplier: fetch_imprint_multiplier)

  if defined?(Legion::Extensions::Coldstart)
    bootstrap = Legion::Extensions::Coldstart::Helpers::Bootstrap.instance
    bootstrap.record_observation
  end

  log.debug("[gaia] pipeline observation identity=#{identity_str} exchange_id=#{exchange_id}")
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'gaia.observe_from_pipeline', identity: identity)
end

.pipeline_observation_seen?(exchange_id) ⇒ Boolean

Returns:

  • (Boolean)


377
378
379
380
381
382
# File 'lib/legion/gaia.rb', line 377

def pipeline_observation_seen?(exchange_id)
  return false if exchange_id.nil?

  @pipeline_observations ||= {}
  @pipeline_observations.key?(exchange_id)
end

.proactive_dispatcherObject



61
62
63
# File 'lib/legion/gaia.rb', line 61

def proactive_dispatcher
  @proactive_dispatcher ||= ProactiveDispatcher.new
end

.record_advisory_meta(advisory_id:, advisory_types:) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/legion/gaia.rb', line 285

def record_advisory_meta(advisory_id:, advisory_types:)
  return unless started?

  @last_response_at = Time.now.utc
  return unless defined?(Legion::Extensions::Agentic::Social::Calibration::Runners::Calibration)

  ensure_calibration_runner
  @calibration_runner.record_advisory_meta(advisory_id: advisory_id, advisory_types: advisory_types)
  log.info(
    "Legion::Gaia recorded advisory metadata advisory_id=#{advisory_id} " \
    "types=#{Array(advisory_types).join(',')}"
  )
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'gaia.record_advisory_meta', advisory_id: advisory_id)
end

.record_response_applied(advisory_id:, identity:, applied:) ⇒ Object



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
# File 'lib/legion/gaia.rb', line 301

def record_response_applied(advisory_id:, identity:, applied:)
  return unless started?

  identity_str = identity.to_s
  if BondRegistry.terminating?(identity_str) || BondRegistry.terminated?(identity_str)
    log.warn("[gaia] rejected write for terminated/terminating identity=#{identity_str}")
    return { recorded: false, reason: :identity_terminated }
  end

  synapse_count = Array(applied[:behavioral_synapse_ids]).size
  log.info("[gaia] attribution advisory_id=#{advisory_id} identity=#{identity} synapses=#{synapse_count}")

  store = apollo_local_store
  store&.upsert(
    content: Legion::JSON.dump(applied.merge(advisory_id: advisory_id, identity: identity)),
    tags: %w[self-knowledge attribution] + ["partner:#{identity}"],
    source_channel: 'gaia',
    confidence: 0.9,
    access_scope: 'local'
  )

  @last_applied = applied.merge(advisory_id: advisory_id, identity: identity)
  { recorded: true, advisory_id: advisory_id }
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'gaia.record_response_applied', advisory_id: advisory_id)
  { recorded: false }
end

.respond(content:, channel_id:, in_reply_to: nil, session_continuity_id: nil, metadata: {}) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/legion/gaia.rb', line 240

def respond(content:, channel_id:, in_reply_to: nil, session_continuity_id: nil, metadata: {})
  @last_response_at = Time.now.utc

  frame = OutputFrame.new(
    content: content,
    channel_id: channel_id,
    in_reply_to: in_reply_to,
    session_continuity_id: session_continuity_id,
    metadata: 
  )

  log.info("Legion::Gaia responding frame_id=#{frame.id} channel=#{channel_id} reply_to=#{in_reply_to}")

  if @agent_bridge&.started?
    @agent_bridge.publish_output(frame)
  else
    @output_router&.route(frame) || { delivered: false, reason: :no_router }
  end
end

.router_mode?Boolean

Returns:

  • (Boolean)


92
93
94
# File 'lib/legion/gaia.rb', line 92

def router_mode?
  @mode == :router
end

.settingsObject



148
149
150
151
152
153
154
# File 'lib/legion/gaia.rb', line 148

def settings
  defaults = Legion::Gaia::Settings.default
  loaded = Legion::Settings[:gaia]
  return defaults unless loaded.is_a?(Hash)

  merge_settings_hashes(defaults, loaded)
end

.shutdownObject



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
# File 'lib/legion/gaia.rb', line 96

def shutdown
  log.info('Legion::Gaia shutting down')

  heartbeat_mutex.synchronize do
    @shutting_down = true
    @started = false
    @tick_unavailable_warned = false
    wait_for_active_heartbeats
  end

  settings_hash = settings
  settings_hash[:connected] = false if settings_hash

  flush_trackers_on_shutdown
  @router_bridge&.stop
  @agent_bridge&.stop
  @channel_registry&.stop_all
  @sensory_buffer = nil
  @registry = nil
  @channel_registry = nil
  @output_router = nil
  @session_store = nil
  @notification_gate = nil
  @router_bridge = nil
  @agent_bridge = nil
  @partner_observations = nil
  @partner_absence_misses = 0
  @last_absence_signal_at = nil
  @absence_pattern_cache = nil
  @absence_pattern_checked_at = nil
  @last_valences = nil
  @last_response_at = nil
  @last_applied = nil
  @correction_counts = nil
  @tick_history = nil
  @tick_count = nil
  @started_at = nil
  @active_heartbeats = 0
  @quiescing_phase_handlers_cache = nil
  @pending_growth_frames = nil

  log.info('Legion::Gaia shut down')
end

.shutting_down?Boolean

Returns:

  • (Boolean)


144
145
146
# File 'lib/legion/gaia.rb', line 144

def shutting_down?
  heartbeat_mutex.synchronize { @shutting_down == true }
end

.started?Boolean

Returns:

  • (Boolean)


140
141
142
# File 'lib/legion/gaia.rb', line 140

def started?
  @started == true
end

.statusObject



329
330
331
332
333
# File 'lib/legion/gaia.rb', line 329

def status
  return { started: false } unless started?

  base_status.merge(router_status)
end