Module: Legion::Extensions::Apollo::Runners::Knowledge

Includes:
Helpers::Lex
Included in:
Actor::EntityWatchdog, Client
Defined in:
lib/legion/extensions/apollo/runners/knowledge.rb

Constant Summary collapse

DOMAIN_ISOLATION =
{
  'claims_optimization' => ['claims_optimization'],
  'clinical_care'       => %w[clinical_care general],
  'general'             => :all
}.freeze

Instance Method Summary collapse

Instance Method Details

#deprecate_entry(entry_id:, reason:) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 53

def deprecate_entry(entry_id:, reason:, **)
  {
    action:   :deprecate,
    entry_id: entry_id,
    reason:   reason
  }
end

#handle_erasure_request(agent_id:) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 287

def handle_erasure_request(agent_id:, **)
  unless defined?(Legion::Data) && Legion::Data.respond_to?(:connection) && Legion::Data.connection
    return { deleted: 0, redacted: 0, error: 'apollo_data_not_available' }
  end

  conn = Legion::Data.connection

  # Delete entries solely from dead agent (not confirmed by others)
  deleted = conn[:apollo_entries]
            .where(source_agent: agent_id)
            .exclude(status: 'confirmed')
            .delete

  # Redact attribution on confirmed entries (corroborated, retain knowledge)
  redacted = conn[:apollo_entries]
             .where(source_agent: agent_id, status: 'confirmed')
             .update(source_agent: 'redacted', source_provider: nil, source_channel: nil)

  { deleted: deleted, redacted: redacted, agent_id: agent_id }
rescue Sequel::Error => e
  { deleted: 0, redacted: 0, error: e.message }
end

#handle_ingest(content:, content_type:, tags: [], source_agent: 'unknown', source_provider: nil, source_channel: nil, knowledge_domain: nil, submitted_by: nil, submitted_from: nil, content_hash: nil, context: {}) ⇒ Object

rubocop:disable Metrics/ParameterLists, Layout/LineLength



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
91
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
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 61

def handle_ingest(content:, content_type:, tags: [], source_agent: 'unknown', source_provider: nil, source_channel: nil, knowledge_domain: nil, submitted_by: nil, submitted_from: nil, content_hash: nil, context: {}, **) # rubocop:disable Metrics/ParameterLists, Layout/LineLength
  return { success: false, error: 'apollo_data_not_available' } unless defined?(Legion::Data::Model::ApolloEntry)

  # Content hash dedup
  hash = content_hash || (defined?(Helpers::Writeback) ? Helpers::Writeback.content_hash(content) : nil)
  if hash
    existing = Legion::Data::Model::ApolloEntry
               .where(content_hash: hash)
               .exclude(status: 'archived')
               .first
    if existing
      existing.update(confidence: [existing.confidence + Helpers::Confidence.retrieval_boost, 1.0].min)
      return { success: true, entry_id: existing.id, deduped: true }
    end
  end

  embedding = embed_text(content)
  content_type_sym = content_type.to_s
  tag_array = defined?(Helpers::TagNormalizer) ? Helpers::TagNormalizer.normalize_all(tags) : Array(tags)
  domain = knowledge_domain || tag_array.first || 'general'

  corroborated, existing_id = find_corroboration(embedding, content_type_sym, source_agent, source_channel)

  unless corroborated
    new_entry = Legion::Data::Model::ApolloEntry.create(
      content:          content,
      content_type:     content_type_sym,
      confidence:       Helpers::Confidence.initial_confidence,
      source_agent:     source_agent,
      source_provider:  source_provider || derive_provider_from_agent(source_agent),
      source_channel:   source_channel,
      source_context:   ::JSON.dump(context.is_a?(Hash) ? context : {}),
      tags:             Sequel.pg_array(tag_array),
      status:           'candidate',
      knowledge_domain: domain,
      submitted_by:     ,
      submitted_from:   ,
      content_hash:     hash,
      embedding:        Sequel.lit("'[#{embedding.join(',')}]'::vector")
    )
    existing_id = new_entry.id
  end

  upsert_expertise(source_agent: source_agent, domain: domain)

  Legion::Data::Model::ApolloAccessLog.create(
    entry_id: existing_id, agent_id: source_agent, action: 'ingest'
  )

  contradictions = detect_contradictions(existing_id, embedding, content)

  { success: true, entry_id: existing_id, status: corroborated ? 'corroborated' : 'candidate',
    corroborated: corroborated, contradictions: contradictions }
rescue Sequel::Error => e
  { success: false, error: e.message }
end

#handle_query(query:, limit: Helpers::GraphQuery.default_query_limit, min_confidence: Helpers::GraphQuery.default_query_min_confidence, status: [:confirmed], tags: nil, domain: nil, agent_id: 'unknown') ⇒ Object

rubocop:disable Metrics/ParameterLists, Layout/LineLength



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
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 118

def handle_query(query:, limit: Helpers::GraphQuery.default_query_limit, min_confidence: Helpers::GraphQuery.default_query_min_confidence, status: [:confirmed], tags: nil, domain: nil, agent_id: 'unknown', **) # rubocop:disable Metrics/ParameterLists, Layout/LineLength
  return { success: false, error: 'apollo_data_not_available' } unless defined?(Legion::Data::Model::ApolloEntry)

  embedding = embed_text(query)
  sql = Helpers::GraphQuery.build_semantic_search_sql(
    limit: limit, min_confidence: min_confidence,
    statuses: Array(status).map(&:to_s), tags: tags, domain: domain
  )

  db = Legion::Data::Model::ApolloEntry.db
  entries = db.fetch(sql, embedding: Sequel.lit("'[#{embedding.join(',')}]'::vector")).all

  entries = entries.reject { |e| e[:distance].respond_to?(:nan?) && e[:distance].nan? }

  entries.each do |entry|
    Legion::Data::Model::ApolloEntry.where(id: entry[:id]).update(
      access_count: Sequel.expr(:access_count) + 1,
      confidence:   Helpers::Confidence.apply_retrieval_boost(
        confidence: entry[:confidence]
      ),
      updated_at:   Time.now
    )
  end

  if entries.any?
    Legion::Data::Model::ApolloAccessLog.create(
      entry_id: entries.first&.dig(:id), agent_id: agent_id, action: 'query'
    )
  end

  formatted = entries.map do |entry|
    { id: entry[:id], content: entry[:content], content_type: entry[:content_type],
      confidence: entry[:confidence], distance: entry[:distance]&.to_f,
      tags: entry[:tags], source_agent: entry[:source_agent],
      knowledge_domain: entry[:knowledge_domain] }
  end

  { success: true, entries: formatted, count: formatted.size }
rescue Sequel::Error => e
  { success: false, error: e.message }
end

#handle_traverse(entry_id:, depth: Helpers::GraphQuery.default_depth, relation_types: nil, agent_id: 'unknown') ⇒ Object



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
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 160

def handle_traverse(entry_id:, depth: Helpers::GraphQuery.default_depth, relation_types: nil, agent_id: 'unknown', **)
  return { success: false, error: 'apollo_data_not_available' } unless defined?(Legion::Data::Model::ApolloEntry)

  # Whitelist relation_types to prevent SQL injection (they are string-interpolated in build_traversal_sql)
  if relation_types
    allowed = Helpers::Confidence::RELATION_TYPES
    relation_types = relation_types.select { |t| allowed.include?(t.to_s) }
  end

  sql = Helpers::GraphQuery.build_traversal_sql(depth: depth, relation_types: relation_types)
  db = Legion::Data::Model::ApolloEntry.db
  entries = db.fetch(sql, entry_id: entry_id).all

  if entries.any? && agent_id != 'unknown'
    Legion::Data::Model::ApolloAccessLog.create(
      entry_id: entry_id, agent_id: agent_id, action: 'query'
    )
  end

  formatted = entries.map do |entry|
    { id: entry[:id], content: entry[:content], content_type: entry[:content_type],
      confidence: entry[:confidence], tags: entry[:tags], source_agent: entry[:source_agent],
      depth: entry[:depth], activation: entry[:activation] }
  end

  { success: true, entries: formatted, count: formatted.size }
rescue Sequel::Error => e
  { success: false, error: e.message }
end

#prepare_mesh_export(target_domain:, min_confidence: Helpers::Confidence.apollo_setting(:query, :mesh_export_min_confidence, default: 0.5), limit: Helpers::Confidence.apollo_setting(:query, :mesh_export_limit, default: 100)) ⇒ Object

rubocop:disable Layout/LineLength



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
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 259

def prepare_mesh_export(target_domain:, min_confidence: Helpers::Confidence.apollo_setting(:query, :mesh_export_min_confidence, default: 0.5), limit: Helpers::Confidence.apollo_setting(:query, :mesh_export_limit, default: 100), **) # rubocop:disable Layout/LineLength
  unless defined?(Legion::Data) && Legion::Data.respond_to?(:connection) && Legion::Data.connection
    return { success: false, error: 'apollo_data_not_available' }
  end

  conn = Legion::Data.connection
  allowed = allowed_domains_for(target_domain)

  dataset = conn[:apollo_entries]
            .where(status: 'confirmed')
            .where { confidence >= min_confidence }
            .limit(limit)

  dataset = dataset.where(knowledge_domain: allowed) unless allowed == :all

  entries = dataset.all

  formatted = entries.map do |entry|
    { id: entry[:id], content: entry[:content], content_type: entry[:content_type],
      confidence: entry[:confidence], knowledge_domain: entry[:knowledge_domain],
      tags: entry[:tags], source_agent: entry[:source_agent] }
  end

  { success: true, entries: formatted, count: formatted.size, target_domain: target_domain }
rescue Sequel::Error => e
  { success: false, error: e.message }
end

#query_knowledge(query:, limit: Helpers::GraphQuery.default_query_limit, min_confidence: Helpers::GraphQuery.default_query_min_confidence, status: [:confirmed], tags: nil) ⇒ Object

rubocop:disable Layout/LineLength



33
34
35
36
37
38
39
40
41
42
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 33

def query_knowledge(query:, limit: Helpers::GraphQuery.default_query_limit, min_confidence: Helpers::GraphQuery.default_query_min_confidence, status: [:confirmed], tags: nil, **) # rubocop:disable Layout/LineLength
  {
    action:         :query,
    query:          query,
    limit:          limit,
    min_confidence: min_confidence,
    status:         Array(status),
    tags:           tags
  }
end

#redistribute_knowledge(agent_id:, min_confidence: Helpers::Confidence.apollo_setting(:query, :redistribute_min_confidence, default: 0.5)) ⇒ Object



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
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 190

def redistribute_knowledge(agent_id:, min_confidence: Helpers::Confidence.apollo_setting(:query, :redistribute_min_confidence, default: 0.5), **)
  return { success: false, error: 'apollo_data_not_available' } unless defined?(Legion::Data::Model::ApolloEntry)

  entries = Legion::Data::Model::ApolloEntry
            .where(source_agent: agent_id, status: 'confirmed')
            .where { confidence > min_confidence }
            .all

  return { success: true, redistributed: 0 } if entries.empty?

  store = (Legion::Extensions::Agentic::Memory::Trace.shared_store if defined?(Legion::Extensions::Agentic::Memory::Trace))

  redistributed = 0
  entries.each do |entry|
    if store
      trace = Legion::Extensions::Agentic::Memory::Trace::Helpers::Trace.new_trace(
        type:            :semantic,
        content_payload: { content: entry.content, source_agent: agent_id,
                           content_type: entry.content_type, tags: Array(entry.tags) },
        strength:        entry.confidence.to_f,
        domain_tag:      Array(entry.tags).first || 'general'
      )
      store.store(trace)
    end
    redistributed += 1
  end

  Legion::Logging.info("[apollo] redistributed #{redistributed} entries from departing agent=#{agent_id}") if defined?(Legion::Logging)
  { success: true, redistributed: redistributed, agent_id: agent_id }
rescue Sequel::Error => e
  { success: false, error: e.message }
end


44
45
46
47
48
49
50
51
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 44

def related_entries(entry_id:, relation_types: nil, depth: Helpers::GraphQuery.default_depth, **)
  {
    action:         :traverse,
    entry_id:       entry_id,
    relation_types: relation_types,
    depth:          depth
  }
end

#retrieve_relevant(query: nil, limit: Helpers::Confidence.apollo_setting(:query, :retrieval_limit, default: 5), min_confidence: Helpers::GraphQuery.default_query_min_confidence, tags: nil, domain: nil, skip: false) ⇒ Object

rubocop:disable Metrics/ParameterLists, Layout/LineLength



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
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 223

def retrieve_relevant(query: nil, limit: Helpers::Confidence.apollo_setting(:query, :retrieval_limit, default: 5), min_confidence: Helpers::GraphQuery.default_query_min_confidence, tags: nil, domain: nil, skip: false, **) # rubocop:disable Metrics/ParameterLists, Layout/LineLength
  return { status: :skipped } if skip

  return { success: false, error: 'apollo_data_not_available' } unless defined?(Legion::Data::Model::ApolloEntry)

  return { success: true, entries: [], count: 0 } if query.nil? || query.to_s.strip.empty?

  embedding = embed_text(query.to_s)
  sql = Helpers::GraphQuery.build_semantic_search_sql(
    limit: limit, min_confidence: min_confidence,
    statuses: ['confirmed'], tags: tags, domain: domain
  )

  db = Legion::Data::Model::ApolloEntry.db
  entries = db.fetch(sql, embedding: Sequel.lit("'[#{embedding.join(',')}]'::vector")).all
  entries = entries.reject { |e| e[:distance].respond_to?(:nan?) && e[:distance].nan? }

  entries.each do |entry|
    Legion::Data::Model::ApolloEntry.where(id: entry[:id]).update(
      confidence: Helpers::Confidence.apply_retrieval_boost(confidence: entry[:confidence]),
      updated_at: Time.now
    )
  end

  formatted = entries.map do |entry|
    { id: entry[:id], content: entry[:content], content_type: entry[:content_type],
      confidence: entry[:confidence], distance: entry[:distance]&.to_f,
      tags: entry[:tags], source_agent: entry[:source_agent],
      knowledge_domain: entry[:knowledge_domain] }
  end

  { success: true, entries: formatted, count: formatted.size }
rescue Sequel::Error => e
  { success: false, error: e.message }
end

#store_knowledge(content:, content_type:, tags: [], source_agent: nil, context: {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/legion/extensions/apollo/runners/knowledge.rb', line 17

def store_knowledge(content:, content_type:, tags: [], source_agent: nil, context: {}, **)
  content_type = content_type.to_sym
  unless Helpers::Confidence::CONTENT_TYPES.include?(content_type)
    raise ArgumentError, "invalid content_type: #{content_type}. Must be one of #{Helpers::Confidence::CONTENT_TYPES}"
  end

  {
    action:       :store,
    content:      content,
    content_type: content_type,
    tags:         Array(tags),
    source_agent: source_agent,
    context:      context
  }
end