lex-apollo 0.4.44 → 0.4.45
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +33 -0
- data/README.md +72 -14
- data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -41
- data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
- data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
- data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
- data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
- data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +4 -16
- data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
- data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
- data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
- data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
- data/lib/legion/extensions/apollo/api.rb +96 -41
- data/lib/legion/extensions/apollo/client.rb +20 -9
- data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
- data/lib/legion/extensions/apollo/helpers/capability.rb +10 -51
- data/lib/legion/extensions/apollo/helpers/confidence.rb +8 -52
- data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
- data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
- data/lib/legion/extensions/apollo/helpers/graph_query.rb +99 -43
- data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
- data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
- data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
- data/lib/legion/extensions/apollo/helpers/writeback.rb +64 -102
- data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
- data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
- data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
- data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +110 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +87 -136
- data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
- data/lib/legion/extensions/apollo/runners/maintenance.rb +151 -64
- data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
- data/lib/legion/extensions/apollo/runners/request.rb +51 -46
- data/lib/legion/extensions/apollo/runners/search.rb +88 -0
- data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
- data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
- data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
- data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
- data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +26 -24
- data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
- data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
- data/spec/legion/extensions/apollo/api_spec.rb +240 -8
- data/spec/legion/extensions/apollo/contradiction_spec.rb +28 -50
- data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
- data/spec/legion/extensions/apollo/helpers/capability_spec.rb +24 -27
- data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
- data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
- data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +108 -0
- data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
- data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
- data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
- data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +73 -74
- data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +32 -3
- data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
- data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
- data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
- data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +124 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +23 -7
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -77
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +138 -6
- data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
- data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +314 -655
- data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +11 -2
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +33 -65
- data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
- data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
- data/spec/legion/extensions/apollo/runners/request_spec.rb +120 -98
- data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
- data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
- data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
- data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
- data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
- data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
- data/spec/spec_helper.rb +13 -15
- metadata +40 -14
- data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
- data/spec/legion/extensions/apollo/actors/contradiction_scanner_spec.rb +0 -38
- data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
- data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
- data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
- data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +0 -39
- data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
- data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
- data/spec/legion/extensions/apollo/helpers/entity_watchdog_spec.rb +0 -64
|
@@ -2,19 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
require 'legion/json'
|
|
4
4
|
require 'legion/settings'
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
require 'legion/logging/helper'
|
|
6
|
+
require 'legion/extensions/apollo/helpers/confidence'
|
|
7
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
8
|
+
require 'legion/extensions/apollo/helpers/embedding'
|
|
9
|
+
require 'legion/extensions/apollo/helpers/storage'
|
|
10
|
+
require 'legion/extensions/apollo/helpers/tag_normalizer'
|
|
11
|
+
require 'legion/extensions/apollo/runners/contradictions'
|
|
12
|
+
require 'legion/extensions/apollo/runners/embedding'
|
|
13
|
+
require 'legion/extensions/apollo/runners/search'
|
|
8
14
|
module Legion
|
|
9
15
|
module Extensions
|
|
10
16
|
module Apollo
|
|
11
17
|
module Runners
|
|
12
18
|
module Knowledge
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
19
|
+
include Legion::Logging::Helper
|
|
20
|
+
include Legion::JSON::Helper
|
|
21
|
+
include Legion::Settings::Helper
|
|
22
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
23
|
+
extend Legion::Extensions::Apollo::Helpers::Confidence
|
|
24
|
+
extend Legion::Extensions::Apollo::Helpers::TagNormalizer
|
|
25
|
+
extend Legion::Extensions::Apollo::Helpers::Storage
|
|
26
|
+
extend Legion::Extensions::Apollo::Helpers::Embedding
|
|
27
|
+
extend Legion::Extensions::Apollo::Helpers::Similarity
|
|
28
|
+
extend Legion::Extensions::Apollo::Helpers::GraphQuery
|
|
29
|
+
extend self
|
|
18
30
|
|
|
19
31
|
CONTENT_TYPE_ALIASES = {
|
|
20
32
|
reasoning: :concept, analysis: :concept, explanation: :concept,
|
|
@@ -27,10 +39,10 @@ module Legion
|
|
|
27
39
|
UNSET = Object.new.freeze
|
|
28
40
|
|
|
29
41
|
def store_knowledge(content:, content_type:, tags: [], source_agent: nil, context: {}, **)
|
|
30
|
-
content_type =
|
|
31
|
-
log.debug("Apollo Knowledge.store_knowledge content_type=#{content_type} tags=#{Array(tags).size} source_agent=#{source_agent || 'nil'} data_available=#{
|
|
42
|
+
content_type = knowledge_normalize_content_type(content_type)
|
|
43
|
+
log.debug("Apollo Knowledge.store_knowledge content_type=#{content_type} tags=#{Array(tags).size} source_agent=#{source_agent || 'nil'} data_available=#{!data_model_entry.nil?}") # rubocop:disable Layout/LineLength
|
|
32
44
|
|
|
33
|
-
|
|
45
|
+
unless data_model_entry.nil?
|
|
34
46
|
return handle_ingest(content: content, content_type: content_type,
|
|
35
47
|
tags: Array(tags), source_agent: source_agent, context: context, **)
|
|
36
48
|
end
|
|
@@ -45,9 +57,9 @@ module Legion
|
|
|
45
57
|
}
|
|
46
58
|
end
|
|
47
59
|
|
|
48
|
-
def query_knowledge(query:, limit:
|
|
49
|
-
log.debug("Apollo Knowledge.query_knowledge query_length=#{query.to_s.length} limit=#{limit} statuses=#{Array(status).join(',')} tags=#{Array(tags).size} data_available=#{
|
|
50
|
-
|
|
60
|
+
def query_knowledge(query:, limit: settings[:query][:default_limit], min_confidence: settings[:query][:default_min_confidence], status: %i[confirmed candidate], tags: nil, **) # rubocop:disable Layout/LineLength
|
|
61
|
+
log.debug("Apollo Knowledge.query_knowledge query_length=#{query.to_s.length} limit=#{limit} statuses=#{Array(status).join(',')} tags=#{Array(tags).size} data_available=#{!data_model_entry.nil?}") # rubocop:disable Layout/LineLength
|
|
62
|
+
unless data_model_entry.nil?
|
|
51
63
|
return handle_query(query: query, limit: limit, min_confidence: min_confidence,
|
|
52
64
|
status: status, tags: tags, **)
|
|
53
65
|
end
|
|
@@ -62,9 +74,9 @@ module Legion
|
|
|
62
74
|
}
|
|
63
75
|
end
|
|
64
76
|
|
|
65
|
-
def related_entries(entry_id:, relation_types: nil, depth:
|
|
66
|
-
log.debug("Apollo Knowledge.related_entries entry_id=#{entry_id} depth=#{depth} relation_types=#{Array(relation_types).join(',')} data_available=#{
|
|
67
|
-
return handle_traverse(entry_id: entry_id, depth: depth, relation_types: relation_types, **)
|
|
77
|
+
def related_entries(entry_id:, relation_types: nil, depth: settings[:graph][:default_depth], **)
|
|
78
|
+
log.debug("Apollo Knowledge.related_entries entry_id=#{entry_id} depth=#{depth} relation_types=#{Array(relation_types).join(',')} data_available=#{!data_model_entry.nil?}") # rubocop:disable Layout/LineLength
|
|
79
|
+
return handle_traverse(entry_id: entry_id, depth: depth, relation_types: relation_types, **) unless data_model_entry.nil?
|
|
68
80
|
|
|
69
81
|
{
|
|
70
82
|
action: :traverse,
|
|
@@ -74,12 +86,18 @@ module Legion
|
|
|
74
86
|
}
|
|
75
87
|
end
|
|
76
88
|
|
|
77
|
-
def deprecate_entry(entry_id:, reason:, **)
|
|
78
|
-
return { action: :deprecate, entry_id: entry_id, reason: reason }
|
|
89
|
+
def deprecate_entry(entry_id:, reason:, requesting_principal_id: nil, **)
|
|
90
|
+
return { action: :deprecate, entry_id: entry_id, reason: reason } if data_model_entry.nil?
|
|
79
91
|
|
|
80
|
-
entry_model =
|
|
92
|
+
entry_model = data_model_entry
|
|
93
|
+
requesting_principal_id = knowledge_resolve_requesting_principal_id(requesting_principal_id)
|
|
81
94
|
entry_model.db.transaction do
|
|
82
|
-
|
|
95
|
+
entries = entry_model.for_update
|
|
96
|
+
if requesting_principal_id
|
|
97
|
+
entries = entries.where(Sequel.lit(graph_access_scope_sql(global_only: requesting_principal_id.zero?),
|
|
98
|
+
requesting_principal_id: requesting_principal_id))
|
|
99
|
+
end
|
|
100
|
+
entry = entries.with_pk(entry_id)
|
|
83
101
|
next({ success: false, error: 'entry_not_found', entry_id: entry_id }) unless entry
|
|
84
102
|
|
|
85
103
|
context = entry[:source_context]
|
|
@@ -100,132 +118,116 @@ module Legion
|
|
|
100
118
|
{ success: false, error: e.message, entry_id: entry_id }
|
|
101
119
|
end
|
|
102
120
|
|
|
103
|
-
def handle_ingest(content
|
|
104
|
-
source_provider: nil, source_channel: nil, knowledge_domain: nil,
|
|
121
|
+
def handle_ingest(content:, content_type: :observation, tags: [], source_agent: 'unknown', # rubocop:disable Metrics/ParameterLists
|
|
122
|
+
source_provider: nil, source_model: nil, source_channel: nil, knowledge_domain: nil,
|
|
105
123
|
submitted_by: nil, submitted_from: nil, content_hash: nil, context: {},
|
|
106
|
-
skip: false, access_scope: 'global', embedding: nil,
|
|
124
|
+
skip: false, access_scope: 'global', embedding: nil, embedding_provenance: nil,
|
|
125
|
+
identity_principal_id: UNSET, identity_id: UNSET, identity_canonical_name: UNSET, **)
|
|
107
126
|
return { status: :skipped } if skip
|
|
108
127
|
|
|
109
|
-
identity =
|
|
110
|
-
|
|
111
|
-
|
|
128
|
+
identity = knowledge_resolve_process_identity(principal_id: identity_principal_id, identity_id: identity_id,
|
|
129
|
+
canonical_name: identity_canonical_name)
|
|
130
|
+
access_scope = (access_scope || 'global').to_s
|
|
131
|
+
return { success: false, error: 'invalid_access_scope' } unless %w[global private team].include?(access_scope)
|
|
132
|
+
if access_scope != 'global' && !(identity[:principal_id].is_a?(Integer) && identity[:principal_id].positive?)
|
|
133
|
+
return { success: false, error: 'identity_required' }
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
content = knowledge_normalize_text_input(content)
|
|
137
|
+
content_type = knowledge_normalize_content_type(content_type.nil? ? :observation : content_type)
|
|
112
138
|
log.debug("Apollo Knowledge.handle_ingest content_length=#{content.length} content_type=#{content_type} tags=#{Array(tags).size} source_agent=#{source_agent} source_channel=#{source_channel || 'nil'}") # rubocop:disable Layout/LineLength
|
|
113
|
-
early_error =
|
|
139
|
+
early_error = knowledge_ingest_early_return_error(content: content, content_type: content_type, tags: tags)
|
|
114
140
|
return early_error if early_error
|
|
115
141
|
|
|
116
|
-
hash = content_hash ||
|
|
117
|
-
existing =
|
|
118
|
-
|
|
142
|
+
hash = content_hash || Legion::Extensions::Apollo::Helpers::Writeback.content_hash(content: content)
|
|
143
|
+
existing = knowledge_active_duplicate_for_hash(content_hash: hash, access_scope: access_scope,
|
|
144
|
+
identity_principal_id: identity[:principal_id])
|
|
119
145
|
if existing
|
|
146
|
+
knowledge_refresh_duplicate_embedding(entry: existing)
|
|
120
147
|
log.info("Apollo Knowledge.handle_ingest deduped entry_id=#{existing.id} source_agent=#{source_agent}")
|
|
121
148
|
return { success: true, entry_id: existing.id, deduped: true }
|
|
122
149
|
end
|
|
123
150
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
existing_id = create_candidate_entry(
|
|
141
|
-
content: content, content_type: content_type_sym, context: context,
|
|
142
|
-
metadata: metadata, content_hash: hash, embedding: embedding
|
|
143
|
-
)
|
|
144
|
-
end
|
|
145
|
-
raise Sequel::Error, 'entry_persistence_failed' unless existing_id
|
|
146
|
-
|
|
147
|
-
upsert_expertise(source_agent: metadata[:source_agent], domain: metadata[:domain])
|
|
148
|
-
Helpers::DataModels.apollo_access_log.create(
|
|
149
|
-
entry_id: existing_id, agent_id: metadata[:source_agent], action: 'ingest'
|
|
150
|
-
)
|
|
151
|
-
{ success: true, entry_id: existing_id, status: corroborated ? 'corroborated' : 'candidate',
|
|
152
|
-
corroborated: corroborated, contradictions: [] }
|
|
153
|
-
end
|
|
154
|
-
schedule_contradiction_detection(entry_id: result[:entry_id], embedding: embedding, content: content)
|
|
151
|
+
document = Legion::Extensions::Apollo::Runners::Embedding.document(
|
|
152
|
+
text: content, vector: embedding, provenance: embedding_provenance
|
|
153
|
+
)
|
|
154
|
+
metadata = knowledge_ingest_metadata(tags: tags, knowledge_domain: knowledge_domain, source_agent: source_agent,
|
|
155
|
+
source_provider: source_provider, source_channel: source_channel,
|
|
156
|
+
submitted_by: submitted_by, submitted_from: submitted_from,
|
|
157
|
+
access_scope: access_scope,
|
|
158
|
+
identity_principal_id: identity[:principal_id],
|
|
159
|
+
identity_id: identity[:identity_id],
|
|
160
|
+
identity_canonical_name: identity[:canonical_name])
|
|
161
|
+
|
|
162
|
+
context = (context.is_a?(Hash) ? context : {}).merge(source_model: source_model) unless source_model.nil?
|
|
163
|
+
result = knowledge_persist_ingest(content: content, content_type: content_type.to_s, context: context,
|
|
164
|
+
metadata: metadata, content_hash: hash,
|
|
165
|
+
embedding: document[:vector], provenance: document[:provenance])
|
|
166
|
+
knowledge_schedule_contradiction_detection(entry_id: result[:entry_id])
|
|
155
167
|
log.debug("Apollo Knowledge.handle_ingest complete entry_id=#{result[:entry_id]} corroborated=#{result[:corroborated]}")
|
|
156
168
|
result
|
|
157
|
-
rescue Sequel::Error => e
|
|
169
|
+
rescue Sequel::Error, Legion::LLM::LLMError, Legion::Extensions::Apollo::Helpers::Embedding::Error => e
|
|
158
170
|
handle_exception(e, level: :error, operation: 'apollo.knowledge.handle_ingest')
|
|
159
171
|
{ success: false, error: e.message }
|
|
160
172
|
end
|
|
161
173
|
|
|
162
|
-
def handle_query(query:, limit:
|
|
163
|
-
min_confidence:
|
|
164
|
-
status: UNSET, tags: nil, domain: nil, agent_id: 'unknown',
|
|
174
|
+
def handle_query(query:, limit: settings[:query][:default_limit], # rubocop:disable Metrics/ParameterLists
|
|
175
|
+
min_confidence: settings[:query][:default_min_confidence],
|
|
176
|
+
status: UNSET, tags: nil, tag_match: :any, exclude_source_agents: [], domain: nil, agent_id: 'unknown',
|
|
165
177
|
requesting_principal_id: nil, **)
|
|
166
|
-
return { success: false, error: 'apollo_data_not_available' }
|
|
178
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
179
|
+
return { success: false, error: 'invalid_tag_match' } unless %w[any all].include?(tag_match.to_s)
|
|
167
180
|
|
|
168
|
-
requesting_principal_id =
|
|
169
|
-
entry_model =
|
|
170
|
-
query =
|
|
181
|
+
requesting_principal_id = knowledge_resolve_requesting_principal_id(requesting_principal_id)
|
|
182
|
+
entry_model = data_model_entry
|
|
183
|
+
query = knowledge_normalize_text_input(query)
|
|
171
184
|
status_defaulted = status.equal?(UNSET)
|
|
172
185
|
requested_status = status_defaulted ? DEFAULT_QUERY_STATUS : status
|
|
173
186
|
log.debug("Apollo Knowledge.handle_query query_length=#{query.length} limit=#{limit} statuses=#{requested_status.inspect} status_defaulted=#{status_defaulted} domain=#{domain.inspect} agent_id=#{agent_id}") # rubocop:disable Layout/LineLength
|
|
174
|
-
if
|
|
175
|
-
return
|
|
176
|
-
|
|
177
|
-
|
|
187
|
+
if knowledge_browse_query?(query)
|
|
188
|
+
return knowledge_list_entries_chronologically(query: query, limit: limit, status: requested_status,
|
|
189
|
+
status_defaulted: status_defaulted, tags: tags, domain: domain,
|
|
190
|
+
requesting_principal_id: requesting_principal_id, min_confidence: min_confidence,
|
|
191
|
+
tag_match: tag_match, exclude_source_agents: exclude_source_agents)
|
|
178
192
|
end
|
|
179
193
|
|
|
180
|
-
|
|
194
|
+
if data_model_access_log.nil?
|
|
181
195
|
log.warn('Apollo Knowledge.handle_query skipped: apollo_data_not_available missing=access_log')
|
|
182
196
|
return { success: false, error: 'apollo_data_not_available' }
|
|
183
197
|
end
|
|
184
198
|
|
|
185
|
-
embedding =
|
|
186
|
-
if embedding.nil?
|
|
187
|
-
log.warn('Apollo Knowledge.handle_query embedding unavailable; falling back to browse query')
|
|
188
|
-
return list_entries_chronologically(query: query, limit: limit, status: requested_status,
|
|
189
|
-
status_defaulted: status_defaulted, tags: tags, domain: domain,
|
|
190
|
-
requesting_principal_id: requesting_principal_id)
|
|
191
|
-
end
|
|
199
|
+
embedding = Legion::Extensions::Apollo::Runners::Embedding.generate(text: query, task: :query)
|
|
192
200
|
|
|
193
201
|
query_options = {
|
|
194
202
|
limit: limit, min_confidence: min_confidence,
|
|
195
|
-
statuses: Array(requested_status).map(&:to_s), tags:
|
|
203
|
+
statuses: Array(requested_status).map(&:to_s), tags: Array(tags).map(&:to_s),
|
|
204
|
+
tag_match: tag_match, exclude_source_agents: Array(exclude_source_agents).map(&:to_s),
|
|
196
205
|
domain: domain&.to_s, requesting_principal_id: requesting_principal_id&.to_i
|
|
197
206
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
entries = db.fetch(sql, **query_options, embedding: "[#{embedding.join(',')}]").all
|
|
202
|
-
|
|
203
|
-
entries.reject! { |entry| entry[:distance].to_f.nan? }
|
|
207
|
+
entries = Legion::Extensions::Apollo::Runners::Search.semantic_search(
|
|
208
|
+
db: entry_model.db, embedding: embedding[:vector], provenance: embedding[:provenance], **query_options
|
|
209
|
+
).fetch(:entries)
|
|
204
210
|
|
|
205
211
|
entries.each do |entry|
|
|
206
|
-
|
|
212
|
+
knowledge_boost_entry_after_query(entry_model, entry)
|
|
207
213
|
end
|
|
208
214
|
|
|
209
|
-
|
|
215
|
+
knowledge_record_query_access(entry_id: entries.first[:id], agent_id: agent_id) if entries.any?
|
|
210
216
|
|
|
211
|
-
formatted = entries.map
|
|
212
|
-
{ id: entry[:id], content: entry[:content], content_type: entry[:content_type],
|
|
213
|
-
confidence: entry[:confidence], distance: entry[:distance]&.to_f,
|
|
214
|
-
tags: entry[:tags], source_agent: entry[:source_agent],
|
|
215
|
-
knowledge_domain: entry[:knowledge_domain] }
|
|
216
|
-
end
|
|
217
|
+
formatted = entries.map { |entry| knowledge_format_entry(entry: entry) }
|
|
217
218
|
|
|
218
219
|
log.info("Apollo Knowledge.handle_query results=#{formatted.size} mode=semantic agent_id=#{agent_id}")
|
|
219
220
|
{ success: true, entries: formatted, count: formatted.size }
|
|
220
|
-
rescue Sequel::Error => e
|
|
221
|
+
rescue Sequel::Error, Legion::JSON::ParseError, Legion::LLM::LLMError, Legion::Extensions::Apollo::Helpers::Embedding::Error => e
|
|
221
222
|
handle_exception(e, level: :error, operation: 'apollo.knowledge.handle_query')
|
|
222
223
|
{ success: false, error: e.message }
|
|
223
224
|
end
|
|
224
225
|
|
|
225
|
-
def handle_traverse(entry_id:, depth:
|
|
226
|
-
|
|
226
|
+
def handle_traverse(entry_id:, depth: settings[:graph][:default_depth], relation_types: nil,
|
|
227
|
+
agent_id: 'unknown', requesting_principal_id: nil, **)
|
|
228
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
227
229
|
|
|
228
|
-
if agent_id != 'unknown' &&
|
|
230
|
+
if agent_id != 'unknown' && data_model_access_log.nil?
|
|
229
231
|
log.warn('Apollo Knowledge.handle_traverse skipped: apollo_data_not_available missing=access_log')
|
|
230
232
|
return { success: false, error: 'apollo_data_not_available' }
|
|
231
233
|
end
|
|
@@ -233,25 +235,29 @@ module Legion
|
|
|
233
235
|
log.debug("Apollo Knowledge.handle_traverse entry_id=#{entry_id} depth=#{depth} relation_types=#{Array(relation_types).join(',')} agent_id=#{agent_id}") # rubocop:disable Layout/LineLength
|
|
234
236
|
# Keep traversal limited to the supported relation vocabulary.
|
|
235
237
|
if relation_types
|
|
236
|
-
allowed = Helpers::Confidence::RELATION_TYPES
|
|
238
|
+
allowed = Legion::Extensions::Apollo::Helpers::Confidence::RELATION_TYPES
|
|
237
239
|
relation_types = relation_types.map(&:to_s).select { |type| allowed.include?(type) }
|
|
238
240
|
end
|
|
239
241
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
+
requesting_principal_id = knowledge_resolve_requesting_principal_id(requesting_principal_id)
|
|
243
|
+
sql = graph_build_traversal_sql(depth: depth, relation_types: relation_types,
|
|
244
|
+
requesting_principal_id: requesting_principal_id)
|
|
245
|
+
db = data_model_entry.db
|
|
242
246
|
entries = db.fetch(sql, entry_id: entry_id, depth: depth, relation_types: relation_types,
|
|
243
|
-
|
|
244
|
-
|
|
247
|
+
requesting_principal_id: requesting_principal_id,
|
|
248
|
+
spread_factor: settings[:graph][:spread_factor],
|
|
249
|
+
min_activation: settings[:graph][:min_activation]).all
|
|
245
250
|
|
|
246
251
|
if entries.any? && agent_id != 'unknown'
|
|
247
|
-
|
|
252
|
+
data_model_access_log.create(
|
|
248
253
|
entry_id: entry_id, agent_id: agent_id, action: 'query'
|
|
249
254
|
)
|
|
250
255
|
end
|
|
251
256
|
|
|
252
257
|
formatted = entries.map do |entry|
|
|
253
258
|
{ id: entry[:id], content: entry[:content], content_type: entry[:content_type],
|
|
254
|
-
confidence: entry[:confidence], tags:
|
|
259
|
+
confidence: entry[:confidence], tags: storage_deserialize_tags(tags: entry[:tags]),
|
|
260
|
+
source_agent: entry[:source_agent],
|
|
255
261
|
depth: entry[:depth], activation: entry[:activation] }
|
|
256
262
|
end
|
|
257
263
|
|
|
@@ -263,27 +269,29 @@ module Legion
|
|
|
263
269
|
end
|
|
264
270
|
|
|
265
271
|
def redistribute_knowledge(agent_id:, min_confidence: settings[:query][:redistribute_min_confidence], **)
|
|
266
|
-
return { success: false, error: 'apollo_data_not_available' }
|
|
272
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
267
273
|
|
|
268
274
|
log.debug("Apollo Knowledge.redistribute_knowledge agent_id=#{agent_id} min_confidence=#{min_confidence}")
|
|
269
|
-
entries =
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
275
|
+
entries = data_model_entry
|
|
276
|
+
.where(source_agent: agent_id, status: 'confirmed')
|
|
277
|
+
.where { confidence > min_confidence }
|
|
278
|
+
.all
|
|
273
279
|
|
|
274
280
|
return { success: true, redistributed: 0 } if entries.empty?
|
|
275
281
|
|
|
276
282
|
store = (Legion::Extensions::Agentic::Memory::Trace.shared_store if defined?(Legion::Extensions::Agentic::Memory::Trace))
|
|
283
|
+
return { success: false, error: 'memory_trace_not_available', redistributed: 0 } unless store
|
|
277
284
|
|
|
278
285
|
redistributed = 0
|
|
279
286
|
entries.each do |entry|
|
|
280
287
|
if store
|
|
288
|
+
tags = storage_deserialize_tags(tags: entry.tags)
|
|
281
289
|
trace = Legion::Extensions::Agentic::Memory::Trace::Helpers::Trace.new_trace(
|
|
282
290
|
type: :semantic,
|
|
283
291
|
content_payload: { content: entry.content, source_agent: agent_id,
|
|
284
|
-
content_type: entry.content_type, tags:
|
|
292
|
+
content_type: entry.content_type, tags: tags },
|
|
285
293
|
strength: entry.confidence.to_f,
|
|
286
|
-
domain_tag:
|
|
294
|
+
domain_tag: tags.first || 'general'
|
|
287
295
|
)
|
|
288
296
|
store.store(trace)
|
|
289
297
|
end
|
|
@@ -297,67 +305,58 @@ module Legion
|
|
|
297
305
|
{ success: false, error: e.message }
|
|
298
306
|
end
|
|
299
307
|
|
|
300
|
-
def retrieve_relevant(query: nil, limit: settings[:query][:retrieval_limit],
|
|
301
|
-
min_confidence:
|
|
302
|
-
tags: nil,
|
|
308
|
+
def retrieve_relevant(query: nil, limit: settings[:query][:retrieval_limit], # rubocop:disable Metrics/ParameterLists
|
|
309
|
+
min_confidence: settings[:query][:default_min_confidence],
|
|
310
|
+
status: %i[confirmed candidate], tags: nil, tag_match: :any, exclude_source_agents: [], domain: nil,
|
|
311
|
+
skip: false, requesting_principal_id: nil, **)
|
|
303
312
|
return { status: :skipped } if skip
|
|
304
313
|
|
|
305
|
-
return { success: false, error: 'apollo_data_not_available' }
|
|
314
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
315
|
+
return { success: false, error: 'invalid_tag_match' } unless %w[any all].include?(tag_match.to_s)
|
|
306
316
|
|
|
307
|
-
requesting_principal_id =
|
|
308
|
-
query =
|
|
317
|
+
requesting_principal_id = knowledge_resolve_requesting_principal_id(requesting_principal_id)
|
|
318
|
+
query = knowledge_normalize_text_input(query)
|
|
309
319
|
log.debug("Apollo Knowledge.retrieve_relevant query_length=#{query.length} limit=#{limit} min_confidence=#{min_confidence} tags=#{Array(tags).size} domain=#{domain.inspect}") # rubocop:disable Layout/LineLength
|
|
310
|
-
return { success: true, entries: [], count: 0 } if query.
|
|
320
|
+
return { success: true, entries: [], count: 0 } if query.to_s.strip.empty?
|
|
311
321
|
|
|
312
|
-
embedding =
|
|
313
|
-
if embedding.nil?
|
|
314
|
-
log.warn('Apollo Knowledge.retrieve_relevant embedding unavailable; returning empty result')
|
|
315
|
-
return { success: true, entries: [], count: 0, degraded: :no_embedding }
|
|
316
|
-
end
|
|
322
|
+
embedding = Legion::Extensions::Apollo::Runners::Embedding.generate(text: query, task: :query)
|
|
317
323
|
|
|
318
324
|
query_options = {
|
|
319
325
|
limit: limit, min_confidence: min_confidence,
|
|
320
|
-
statuses:
|
|
326
|
+
statuses: Array(status).map(&:to_s), tags: Array(tags).map(&:to_s),
|
|
327
|
+
tag_match: tag_match, exclude_source_agents: Array(exclude_source_agents).map(&:to_s),
|
|
321
328
|
domain: domain&.to_s, requesting_principal_id: requesting_principal_id&.to_i
|
|
322
329
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
entries.reject! { |entry| entry[:distance].to_f.nan? }
|
|
330
|
+
entries = Legion::Extensions::Apollo::Runners::Search.semantic_search(
|
|
331
|
+
db: data_model_entry.db,
|
|
332
|
+
embedding: embedding[:vector], provenance: embedding[:provenance], **query_options
|
|
333
|
+
).fetch(:entries)
|
|
328
334
|
|
|
329
335
|
entries.each do |entry|
|
|
330
|
-
|
|
331
|
-
confidence:
|
|
336
|
+
data_model_entry.where(id: entry[:id]).update(
|
|
337
|
+
confidence: confidence_apply_retrieval_boost(confidence: entry[:confidence]),
|
|
332
338
|
updated_at: Time.now
|
|
333
339
|
)
|
|
334
340
|
end
|
|
335
341
|
|
|
336
|
-
formatted = entries.map
|
|
337
|
-
{ id: entry[:id], content: entry[:content], content_type: entry[:content_type],
|
|
338
|
-
confidence: entry[:confidence], distance: entry[:distance]&.to_f,
|
|
339
|
-
tags: entry[:tags], source_agent: entry[:source_agent],
|
|
340
|
-
knowledge_domain: entry[:knowledge_domain] }
|
|
341
|
-
end
|
|
342
|
+
formatted = entries.map { |entry| knowledge_format_entry(entry: entry) }
|
|
342
343
|
|
|
343
344
|
log.info("Apollo Knowledge.retrieve_relevant results=#{formatted.size} limit=#{limit}")
|
|
344
345
|
{ success: true, entries: formatted, count: formatted.size }
|
|
345
|
-
rescue Sequel::Error => e
|
|
346
|
+
rescue Sequel::Error, Legion::JSON::ParseError, Legion::LLM::LLMError, Legion::Extensions::Apollo::Helpers::Embedding::Error => e
|
|
346
347
|
handle_exception(e, level: :error, operation: 'apollo.knowledge.retrieve_relevant')
|
|
347
348
|
{ success: false, error: e.message }
|
|
348
349
|
end
|
|
349
350
|
|
|
350
351
|
def prepare_mesh_export(target_domain:, min_confidence: settings[:query][:mesh_export_min_confidence], limit: settings[:query][:mesh_export_limit], **) # rubocop:disable Layout/LineLength
|
|
351
|
-
|
|
352
|
-
return { success: false, error: 'apollo_data_not_available' }
|
|
353
|
-
end
|
|
352
|
+
return { success: false, error: 'apollo_data_not_available' } unless Legion::Data.connection
|
|
354
353
|
|
|
355
354
|
log.debug("Apollo Knowledge.prepare_mesh_export target_domain=#{target_domain} min_confidence=#{min_confidence} limit=#{limit}")
|
|
356
355
|
conn = Legion::Data.connection
|
|
357
|
-
allowed =
|
|
356
|
+
allowed = knowledge_allowed_domains_for(target_domain)
|
|
358
357
|
|
|
359
358
|
dataset = conn[:apollo_entries]
|
|
360
|
-
.where(status: 'confirmed')
|
|
359
|
+
.where(status: 'confirmed', access_scope: 'global')
|
|
361
360
|
.where { confidence >= min_confidence }
|
|
362
361
|
.limit(limit)
|
|
363
362
|
|
|
@@ -368,7 +367,7 @@ module Legion
|
|
|
368
367
|
formatted = entries.map do |entry|
|
|
369
368
|
{ id: entry[:id], content: entry[:content], content_type: entry[:content_type],
|
|
370
369
|
confidence: entry[:confidence], knowledge_domain: entry[:knowledge_domain],
|
|
371
|
-
tags: entry[:tags], source_agent: entry[:source_agent] }
|
|
370
|
+
tags: storage_deserialize_tags(tags: entry[:tags]), source_agent: entry[:source_agent] }
|
|
372
371
|
end
|
|
373
372
|
|
|
374
373
|
{ success: true, entries: formatted, count: formatted.size, target_domain: target_domain }
|
|
@@ -379,9 +378,7 @@ module Legion
|
|
|
379
378
|
end
|
|
380
379
|
|
|
381
380
|
def handle_erasure_request(agent_id:, **)
|
|
382
|
-
|
|
383
|
-
return { deleted: 0, redacted: 0, error: 'apollo_data_not_available' }
|
|
384
|
-
end
|
|
381
|
+
return { deleted: 0, redacted: 0, error: 'apollo_data_not_available' } unless Legion::Data.connection
|
|
385
382
|
|
|
386
383
|
log.warn("Apollo Knowledge.handle_erasure_request agent_id=#{agent_id}")
|
|
387
384
|
conn = Legion::Data.connection
|
|
@@ -410,11 +407,31 @@ module Legion
|
|
|
410
407
|
{ deleted: 0, redacted: 0, error: e.message }
|
|
411
408
|
end
|
|
412
409
|
|
|
413
|
-
CONFLICT_CHECK_MAX_CHARS = 4000
|
|
414
|
-
|
|
415
410
|
private
|
|
416
411
|
|
|
417
|
-
def
|
|
412
|
+
def knowledge_persist_ingest(content:, content_type:, context:, metadata:, content_hash:, embedding:, provenance:, **)
|
|
413
|
+
data_model_entry.db.transaction do
|
|
414
|
+
corroborated, existing_id = knowledge_find_corroboration(
|
|
415
|
+
embedding: embedding, provenance: provenance, content_type: content_type, metadata: metadata
|
|
416
|
+
)
|
|
417
|
+
unless corroborated
|
|
418
|
+
existing_id = knowledge_create_candidate_entry(
|
|
419
|
+
content: content, content_type: content_type, context: context,
|
|
420
|
+
metadata: metadata, content_hash: content_hash, embedding: embedding, provenance: provenance
|
|
421
|
+
)
|
|
422
|
+
end
|
|
423
|
+
raise Sequel::Error, 'entry_persistence_failed' unless existing_id
|
|
424
|
+
|
|
425
|
+
knowledge_upsert_expertise(source_agent: metadata[:source_agent], domain: metadata[:domain])
|
|
426
|
+
data_model_access_log.create(
|
|
427
|
+
entry_id: existing_id, agent_id: metadata[:source_agent], action: 'ingest'
|
|
428
|
+
)
|
|
429
|
+
{ success: true, entry_id: existing_id, status: corroborated ? 'corroborated' : 'candidate',
|
|
430
|
+
corroborated: corroborated, contradictions: [] }
|
|
431
|
+
end
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
def knowledge_ingest_early_return_error(content:, content_type:, tags:)
|
|
418
435
|
if content.strip.empty?
|
|
419
436
|
safe_tags = Array(tags).map(&:to_s).map { |t| t.gsub(/[\r\n]+/, ' ') }
|
|
420
437
|
log.warn('[apollo][handle_ingest] early-return: content is required ' \
|
|
@@ -423,9 +440,9 @@ module Legion
|
|
|
423
440
|
end
|
|
424
441
|
|
|
425
442
|
missing = []
|
|
426
|
-
missing << 'entry'
|
|
427
|
-
missing << 'expertise'
|
|
428
|
-
missing << 'access_log'
|
|
443
|
+
missing << 'entry' if data_model_entry.nil?
|
|
444
|
+
missing << 'expertise' if data_model_expertise.nil?
|
|
445
|
+
missing << 'access_log' if data_model_access_log.nil?
|
|
429
446
|
return nil if missing.empty?
|
|
430
447
|
|
|
431
448
|
log.warn('[apollo][handle_ingest] early-return: apollo_data_not_available ' \
|
|
@@ -433,48 +450,23 @@ module Legion
|
|
|
433
450
|
{ success: false, error: 'apollo_data_not_available' }
|
|
434
451
|
end
|
|
435
452
|
|
|
436
|
-
def
|
|
453
|
+
def knowledge_normalize_content_type(raw)
|
|
437
454
|
sym = raw.to_s.delete_prefix(':').gsub(%r{[/\s]}, '_').strip.downcase.to_sym
|
|
438
455
|
sym = CONTENT_TYPE_ALIASES.fetch(sym, sym)
|
|
439
|
-
Helpers::Confidence::CONTENT_TYPES.include?(sym) ? sym : :observation
|
|
440
|
-
end
|
|
441
|
-
|
|
442
|
-
def embed_text(text)
|
|
443
|
-
text = normalize_text_input(text)
|
|
444
|
-
log.debug("Apollo Knowledge.embed_text text_length=#{text.length}")
|
|
445
|
-
result = Legion::LLM::Call::Embeddings.generate(text: text)
|
|
446
|
-
vector = result.is_a?(Hash) ? result[:vector] : result
|
|
447
|
-
if usable_embedding?(vector)
|
|
448
|
-
log.debug("Apollo Knowledge.embed_text vector_dimensions=#{vector.length}")
|
|
449
|
-
vector
|
|
450
|
-
else
|
|
451
|
-
log.warn('Apollo Knowledge.embed_text returned no usable vector; skipping embedding')
|
|
452
|
-
nil
|
|
453
|
-
end
|
|
454
|
-
rescue StandardError => e
|
|
455
|
-
handle_exception(e, level: :warn, operation: 'apollo.knowledge.embed_text')
|
|
456
|
-
nil
|
|
457
|
-
end
|
|
458
|
-
|
|
459
|
-
def usable_embedding?(vector)
|
|
460
|
-
vector.is_a?(Array) && vector.any? { |value| value != 0.0 } &&
|
|
461
|
-
vector.all? { |value| value.is_a?(Numeric) && value.real? && value.finite? }
|
|
456
|
+
Legion::Extensions::Apollo::Helpers::Confidence::CONTENT_TYPES.include?(sym) ? sym : :observation
|
|
462
457
|
end
|
|
463
458
|
|
|
464
|
-
def
|
|
459
|
+
def knowledge_normalize_text_input(value)
|
|
465
460
|
result = if defined?(Legion::Apollo) && Legion::Apollo.respond_to?(:normalize_text_input, true)
|
|
466
461
|
Legion::Apollo.send(:normalize_text_input, value)
|
|
467
462
|
else
|
|
468
463
|
value.to_s
|
|
469
464
|
end
|
|
470
465
|
|
|
471
|
-
|
|
472
|
-
rescue StandardError => e
|
|
473
|
-
handle_exception(e, level: :warn, operation: 'apollo.knowledge.normalize_text_input')
|
|
474
|
-
''
|
|
466
|
+
knowledge_sanitize_for_postgres(result)
|
|
475
467
|
end
|
|
476
468
|
|
|
477
|
-
def
|
|
469
|
+
def knowledge_sanitize_for_postgres(value)
|
|
478
470
|
return value unless value.is_a?(String)
|
|
479
471
|
|
|
480
472
|
string = value.encoding == Encoding::UTF_8 ? value.dup : value.dup.force_encoding(Encoding::UTF_8)
|
|
@@ -485,58 +477,73 @@ module Legion
|
|
|
485
477
|
sanitized
|
|
486
478
|
end
|
|
487
479
|
|
|
488
|
-
def
|
|
480
|
+
def knowledge_truncate_for_column(value, max_length)
|
|
489
481
|
return nil if value.nil?
|
|
490
482
|
|
|
491
|
-
|
|
483
|
+
knowledge_normalize_text_input(value)[0, max_length]
|
|
492
484
|
end
|
|
493
485
|
|
|
494
|
-
def
|
|
495
|
-
return nil unless
|
|
486
|
+
def knowledge_active_duplicate_for_hash(content_hash:, access_scope: nil, identity_principal_id: nil, **)
|
|
487
|
+
return nil unless content_hash
|
|
496
488
|
|
|
497
|
-
dataset =
|
|
498
|
-
|
|
499
|
-
|
|
489
|
+
dataset = data_model_entry
|
|
490
|
+
.where(content_hash: content_hash, access_scope: access_scope)
|
|
491
|
+
.exclude(status: 'archived')
|
|
500
492
|
|
|
501
|
-
dataset = dataset.where(identity_principal_id: identity_principal_id) if access_scope
|
|
493
|
+
dataset = dataset.where(identity_principal_id: identity_principal_id) if access_scope != 'global'
|
|
502
494
|
|
|
503
495
|
existing = dataset.first
|
|
504
|
-
existing&.update(confidence: [existing.confidence + Helpers::Confidence.retrieval_boost, 1.0].min)
|
|
505
496
|
log.debug("Apollo Knowledge.active_duplicate_for_hash matched entry_id=#{existing.id}") if existing
|
|
506
497
|
existing
|
|
507
498
|
end
|
|
508
499
|
|
|
509
|
-
def
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
500
|
+
def knowledge_refresh_duplicate_embedding(entry:, **)
|
|
501
|
+
provenance = embedding_parse_provenance(value: entry[:embedding_provenance])
|
|
502
|
+
vector = similarity_parse_vector(vector: entry[:embedding])
|
|
503
|
+
updates = { confidence: [entry.confidence + settings[:confidence][:retrieval_boost], 1.0].min, updated_at: Time.now }
|
|
504
|
+
unless embedding_valid?(vector: vector, provenance: provenance, task: :document)
|
|
505
|
+
document = Legion::Extensions::Apollo::Runners::Embedding.generate(text: entry.content, task: :document)
|
|
506
|
+
db = data_model_entry.db
|
|
507
|
+
updates.merge!(
|
|
508
|
+
embedding: storage_serialize_embedding(db: db, vector: document[:vector]),
|
|
509
|
+
embedding_provenance: storage_serialize_provenance(db: db, provenance: document[:provenance]),
|
|
510
|
+
embedding_space_id: document[:provenance][:space_id], embedding_dimensions: document[:vector].length
|
|
511
|
+
)
|
|
512
|
+
end
|
|
513
|
+
data_model_entry.db.transaction { entry.update(updates) }
|
|
514
|
+
end
|
|
515
|
+
|
|
516
|
+
def knowledge_ingest_metadata(tags:, knowledge_domain:, source_agent:, source_provider:, source_channel:, # rubocop:disable Metrics/ParameterLists
|
|
517
|
+
submitted_by:, submitted_from:, access_scope: 'global',
|
|
518
|
+
identity_principal_id: nil, identity_id: nil, identity_canonical_name: nil)
|
|
519
|
+
tag_array = tag_normalize_all(tags: tags)
|
|
520
|
+
agent = knowledge_truncate_for_column(source_agent, 50) || 'unknown'
|
|
514
521
|
|
|
515
522
|
{ tags: tag_array,
|
|
516
|
-
domain:
|
|
523
|
+
domain: knowledge_truncate_for_column(knowledge_domain || tag_array.first || 'general', 50),
|
|
517
524
|
source_agent: agent,
|
|
518
|
-
source_provider:
|
|
519
|
-
source_channel:
|
|
520
|
-
submitted_by:
|
|
521
|
-
submitted_from:
|
|
525
|
+
source_provider: knowledge_truncate_for_column(source_provider || knowledge_derive_provider_from_agent(agent), 50),
|
|
526
|
+
source_channel: knowledge_truncate_for_column(source_channel, 100),
|
|
527
|
+
submitted_by: knowledge_truncate_for_column(submitted_by, 255),
|
|
528
|
+
submitted_from: knowledge_truncate_for_column(submitted_from, 255),
|
|
522
529
|
access_scope: (access_scope || 'global').to_s,
|
|
523
530
|
identity_principal_id: identity_principal_id.is_a?(Integer) ? identity_principal_id : nil,
|
|
524
531
|
identity_id: identity_id.is_a?(Integer) ? identity_id : nil,
|
|
525
532
|
identity_canonical_name: identity_canonical_name&.to_s&.slice(0, 255) }
|
|
526
533
|
end
|
|
527
534
|
|
|
528
|
-
def
|
|
529
|
-
entry_model =
|
|
535
|
+
def knowledge_create_candidate_entry(content:, content_type:, context:, metadata:, content_hash:, embedding:, provenance:, **)
|
|
536
|
+
entry_model = data_model_entry
|
|
530
537
|
new_entry = entry_model.db.transaction(savepoint: true) do
|
|
531
538
|
entry_model.create(
|
|
532
539
|
content: content,
|
|
533
540
|
content_type: content_type,
|
|
534
|
-
confidence:
|
|
541
|
+
confidence: settings[:confidence][:initial],
|
|
535
542
|
source_agent: metadata[:source_agent],
|
|
536
543
|
source_provider: metadata[:source_provider],
|
|
537
544
|
source_channel: metadata[:source_channel],
|
|
538
545
|
source_context: json_dump(context.is_a?(Hash) ? context : {}),
|
|
539
|
-
tags:
|
|
546
|
+
tags: storage_serialize_tags(db: entry_model.db, tags: metadata[:tags]),
|
|
540
547
|
status: 'candidate',
|
|
541
548
|
knowledge_domain: metadata[:domain],
|
|
542
549
|
submitted_by: metadata[:submitted_by],
|
|
@@ -546,13 +553,18 @@ module Legion
|
|
|
546
553
|
identity_principal_id: metadata[:identity_principal_id],
|
|
547
554
|
identity_id: metadata[:identity_id],
|
|
548
555
|
identity_canonical_name: metadata[:identity_canonical_name],
|
|
549
|
-
embedding:
|
|
556
|
+
embedding: storage_serialize_embedding(db: entry_model.db, vector: embedding),
|
|
557
|
+
embedding_provenance: storage_serialize_provenance(db: entry_model.db, provenance: provenance),
|
|
558
|
+
embedding_space_id: provenance[:space_id],
|
|
559
|
+
embedding_dimensions: embedding.length
|
|
550
560
|
)
|
|
551
561
|
end
|
|
552
562
|
log.info("Apollo Knowledge.handle_ingest created entry_id=#{new_entry.id} status=candidate domain=#{metadata[:domain]} source_agent=#{metadata[:source_agent]} access_scope=#{metadata[:access_scope]}") # rubocop:disable Layout/LineLength
|
|
553
563
|
new_entry.id
|
|
554
564
|
rescue Sequel::UniqueConstraintViolation => e
|
|
555
|
-
|
|
565
|
+
winner_scope = entry_model.where(content_hash: content_hash, access_scope: metadata[:access_scope]).exclude(status: 'archived')
|
|
566
|
+
winner_scope = winner_scope.where(identity_principal_id: metadata[:identity_principal_id]) if metadata[:access_scope] != 'global'
|
|
567
|
+
winner = winner_scope.first
|
|
556
568
|
if winner
|
|
557
569
|
log.warn("Apollo Knowledge.create_candidate_entry race_dedup entry_id=#{winner.id} content_hash=#{content_hash} error=#{e.message}")
|
|
558
570
|
return winner.id
|
|
@@ -562,27 +574,32 @@ module Legion
|
|
|
562
574
|
raise
|
|
563
575
|
end
|
|
564
576
|
|
|
565
|
-
def
|
|
577
|
+
def knowledge_browse_query?(query)
|
|
566
578
|
query.to_s.strip.length < 3
|
|
567
579
|
end
|
|
568
580
|
|
|
569
|
-
def
|
|
581
|
+
def knowledge_list_entries_chronologically(query:, limit:, status:, status_defaulted:, tags:, domain:, # rubocop:disable Metrics/ParameterLists
|
|
582
|
+
min_confidence:, requesting_principal_id: nil, tag_match: :any, exclude_source_agents: [], **)
|
|
570
583
|
log.debug("Apollo Knowledge.list_entries_chronologically limit=#{limit} statuses=#{Array(status).join(',')} status_defaulted=#{status_defaulted} tags=#{Array(tags).size} domain=#{domain || 'nil'}") # rubocop:disable Layout/LineLength
|
|
571
|
-
dataset =
|
|
584
|
+
dataset = data_model_entry.exclude(status: 'archived')
|
|
572
585
|
requested = Array(status).map(&:to_s).reject(&:empty?)
|
|
573
586
|
dataset = dataset.where(status: requested) unless status_defaulted || requested.empty?
|
|
574
|
-
dataset = dataset
|
|
575
|
-
dataset = dataset.where
|
|
587
|
+
dataset = storage_filter_tags(dataset: dataset, tags: tags, tag_match: tag_match)
|
|
588
|
+
dataset = dataset.where { confidence >= min_confidence }
|
|
589
|
+
if Array(exclude_source_agents).any?
|
|
590
|
+
dataset = dataset.where(Sequel.lit('(source_agent IS NULL OR source_agent NOT IN ?)', Array(exclude_source_agents).map(&:to_s)))
|
|
591
|
+
end
|
|
592
|
+
dataset = dataset.where(knowledge_domain: domain) unless domain.to_s.empty?
|
|
576
593
|
|
|
577
594
|
if requesting_principal_id
|
|
578
595
|
dataset = dataset.where(
|
|
579
|
-
Sequel.lit(
|
|
596
|
+
Sequel.lit(graph_access_scope_sql(global_only: requesting_principal_id.zero?),
|
|
580
597
|
requesting_principal_id: requesting_principal_id.to_i)
|
|
581
598
|
)
|
|
582
599
|
end
|
|
583
600
|
|
|
584
601
|
entries = dataset.order(Sequel.desc(:created_at)).limit(limit).all.map do |entry|
|
|
585
|
-
|
|
602
|
+
knowledge_format_entry(entry: entry.is_a?(Hash) ? entry : entry.values)
|
|
586
603
|
end
|
|
587
604
|
log.info("Apollo Knowledge.list_entries_chronologically results=#{entries.size}")
|
|
588
605
|
{ success: true, mode: :browse, query: query, entries: entries, count: entries.size }
|
|
@@ -591,34 +608,28 @@ module Legion
|
|
|
591
608
|
{ success: false, error: e.message }
|
|
592
609
|
end
|
|
593
610
|
|
|
594
|
-
def
|
|
611
|
+
def knowledge_format_entry(entry:, **)
|
|
595
612
|
{ id: entry[:id], content: entry[:content], content_type: entry[:content_type],
|
|
596
613
|
confidence: entry[:confidence], distance: entry[:distance]&.to_f,
|
|
597
|
-
tags: entry[:tags], source_agent: entry[:source_agent],
|
|
614
|
+
tags: storage_deserialize_tags(tags: entry[:tags]), source_agent: entry[:source_agent],
|
|
598
615
|
knowledge_domain: entry[:knowledge_domain] }
|
|
599
616
|
end
|
|
600
617
|
|
|
601
|
-
def
|
|
602
|
-
|
|
618
|
+
def knowledge_record_query_access(entry_id:, agent_id:)
|
|
619
|
+
data_model_access_log.create(
|
|
603
620
|
entry_id: entry_id, agent_id: agent_id, action: 'query'
|
|
604
621
|
)
|
|
605
622
|
end
|
|
606
623
|
|
|
607
|
-
def
|
|
624
|
+
def knowledge_boost_entry_after_query(entry_model, entry)
|
|
608
625
|
entry_model.where(id: entry[:id]).update(
|
|
609
626
|
access_count: Sequel.expr(:access_count) + 1,
|
|
610
|
-
confidence:
|
|
611
|
-
confidence: entry[:confidence]
|
|
612
|
-
),
|
|
627
|
+
confidence: confidence_apply_retrieval_boost(confidence: entry[:confidence]),
|
|
613
628
|
updated_at: Time.now
|
|
614
629
|
)
|
|
615
630
|
end
|
|
616
631
|
|
|
617
|
-
def
|
|
618
|
-
Legion::Extensions::Apollo.settings
|
|
619
|
-
end
|
|
620
|
-
|
|
621
|
-
def allowed_domains_for(target_domain)
|
|
632
|
+
def knowledge_allowed_domains_for(target_domain)
|
|
622
633
|
rules = settings[:domain_isolation]
|
|
623
634
|
|
|
624
635
|
allowed = rules[target_domain]
|
|
@@ -627,89 +638,17 @@ module Legion
|
|
|
627
638
|
Array(allowed)
|
|
628
639
|
end
|
|
629
640
|
|
|
630
|
-
def
|
|
631
|
-
settings[:contradiction][:enabled] == true
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
def schedule_contradiction_detection(entry_id:, embedding:, content:)
|
|
635
|
-
return unless contradiction_detection_enabled?
|
|
636
|
-
return unless embedding && Helpers::DataModels.apollo_entry_available?
|
|
641
|
+
def knowledge_schedule_contradiction_detection(entry_id:, **)
|
|
642
|
+
return unless settings[:contradiction][:enabled] == true
|
|
643
|
+
return if data_model_entry.nil?
|
|
637
644
|
|
|
638
|
-
Legion::Extensions::Apollo::
|
|
639
|
-
entry_id: entry_id, embedding: embedding, content: content
|
|
640
|
-
)
|
|
645
|
+
Legion::Extensions::Apollo::Runners::Contradictions.enqueue(entry_id: entry_id)
|
|
641
646
|
log.debug("Apollo Knowledge.schedule_contradiction_detection enqueued entry_id=#{entry_id}")
|
|
642
647
|
rescue StandardError => e
|
|
643
648
|
handle_exception(e, level: :warn, operation: 'apollo.knowledge.schedule_contradiction_detection')
|
|
644
649
|
end
|
|
645
650
|
|
|
646
|
-
def
|
|
647
|
-
return [] unless embedding && Helpers::DataModels.apollo_entry_available?
|
|
648
|
-
|
|
649
|
-
sim_limit = settings[:contradiction][:similar_limit]
|
|
650
|
-
sim_threshold = settings[:contradiction][:similarity_threshold]
|
|
651
|
-
rel_weight = settings[:contradiction][:relation_weight]
|
|
652
|
-
|
|
653
|
-
db = Helpers::DataModels.apollo_entry.db
|
|
654
|
-
log.debug("Apollo Knowledge.detect_contradictions entry_id=#{entry_id} similar_limit=#{sim_limit} threshold=#{sim_threshold}")
|
|
655
|
-
similar = db.fetch(
|
|
656
|
-
'SELECT id, content, embedding FROM apollo_entries WHERE id != :entry_id AND embedding IS NOT NULL ' \
|
|
657
|
-
'ORDER BY embedding <=> :embedding LIMIT :limit',
|
|
658
|
-
entry_id: entry_id,
|
|
659
|
-
embedding: Sequel.lit('?::vector', "[#{embedding.join(',')}]"),
|
|
660
|
-
limit: sim_limit
|
|
661
|
-
).all
|
|
662
|
-
|
|
663
|
-
contradictions = []
|
|
664
|
-
similar.each do |existing|
|
|
665
|
-
existing_embedding = existing[:embedding]
|
|
666
|
-
next unless existing_embedding
|
|
667
|
-
|
|
668
|
-
sim = Helpers::Similarity.cosine_similarity(vec_a: embedding, vec_b: existing_embedding)
|
|
669
|
-
next unless sim > sim_threshold
|
|
670
|
-
next unless llm_detects_conflict?(content, existing[:content])
|
|
671
|
-
|
|
672
|
-
contradictions << existing[:id]
|
|
673
|
-
end
|
|
674
|
-
unless contradictions.empty?
|
|
675
|
-
db.transaction do
|
|
676
|
-
contradictions.each do |contradicted_id|
|
|
677
|
-
Legion::Extensions::Apollo::Helpers::DataModels.apollo_relation.create(
|
|
678
|
-
from_entry_id: entry_id, to_entry_id: contradicted_id,
|
|
679
|
-
relation_type: 'contradicts', source_agent: 'system:contradiction', weight: rel_weight
|
|
680
|
-
)
|
|
681
|
-
end
|
|
682
|
-
Legion::Extensions::Apollo::Helpers::DataModels.apollo_entry
|
|
683
|
-
.where(id: [entry_id, *contradictions]).update(status: 'disputed')
|
|
684
|
-
end
|
|
685
|
-
end
|
|
686
|
-
log.info("Apollo Knowledge.detect_contradictions entry_id=#{entry_id} contradictions=#{contradictions.size}") if contradictions.any?
|
|
687
|
-
contradictions
|
|
688
|
-
rescue Sequel::Error => e
|
|
689
|
-
handle_exception(e, level: :error, operation: 'apollo.knowledge.detect_contradictions')
|
|
690
|
-
raise
|
|
691
|
-
end
|
|
692
|
-
|
|
693
|
-
def llm_detects_conflict?(content_a, content_b)
|
|
694
|
-
return false unless defined?(Legion::LLM) && Legion::LLM.respond_to?(:structured)
|
|
695
|
-
|
|
696
|
-
a = content_a.to_s[0, CONFLICT_CHECK_MAX_CHARS]
|
|
697
|
-
b = content_b.to_s[0, CONFLICT_CHECK_MAX_CHARS]
|
|
698
|
-
result = Legion::LLM.structured(
|
|
699
|
-
messages: [
|
|
700
|
-
{ role: 'system', content: 'Do these two statements contradict each other? Return JSON.' },
|
|
701
|
-
{ role: 'user', content: "A: #{a}\n\nB: #{b}" }
|
|
702
|
-
],
|
|
703
|
-
schema: { type: 'object', properties: { contradicts: { type: 'boolean' } } },
|
|
704
|
-
caller: { extension: 'lex-apollo', runner: 'knowledge' }
|
|
705
|
-
)
|
|
706
|
-
result[:data]&.dig(:contradicts) == true
|
|
707
|
-
rescue StandardError => e
|
|
708
|
-
handle_exception(e, level: :warn, operation: 'apollo.knowledge.llm_detects_conflict')
|
|
709
|
-
false
|
|
710
|
-
end
|
|
711
|
-
|
|
712
|
-
def find_corroboration(embedding:, content_type:, metadata:)
|
|
651
|
+
def knowledge_find_corroboration(embedding:, provenance:, content_type:, metadata:, **)
|
|
713
652
|
return [false, nil] unless embedding
|
|
714
653
|
return [false, nil] if metadata[:access_scope] != 'global' && metadata[:identity_principal_id].nil?
|
|
715
654
|
|
|
@@ -717,26 +656,25 @@ module Legion
|
|
|
717
656
|
source_channel = metadata[:source_channel]
|
|
718
657
|
scan_limit = settings[:corroboration][:scan_limit]
|
|
719
658
|
# Candidate evidence is retained for the bounded maintenance bootstrap scan.
|
|
720
|
-
existing =
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
Sequel.lit(Legion::Extensions::Apollo::Helpers::GraphQuery.access_scope_sql,
|
|
727
|
-
requesting_principal_id: metadata[:identity_principal_id])
|
|
728
|
-
)
|
|
729
|
-
end
|
|
659
|
+
existing = data_model_entry
|
|
660
|
+
.where(content_type: content_type, knowledge_domain: metadata[:domain],
|
|
661
|
+
access_scope: metadata[:access_scope], status: 'confirmed',
|
|
662
|
+
embedding_space_id: provenance[:space_id], embedding_dimensions: provenance[:dimensions])
|
|
663
|
+
.exclude(embedding: nil)
|
|
664
|
+
existing = existing.where(identity_principal_id: metadata[:identity_principal_id]) if metadata[:access_scope] != 'global'
|
|
730
665
|
existing = existing.limit(scan_limit)
|
|
731
666
|
|
|
732
667
|
existing.each do |entry|
|
|
733
|
-
|
|
668
|
+
stored_provenance = embedding_parse_provenance(value: entry[:embedding_provenance])
|
|
669
|
+
stored_vector = similarity_parse_vector(vector: entry.embedding)
|
|
670
|
+
next unless embedding_valid?(vector: stored_vector, provenance: stored_provenance, task: :document)
|
|
671
|
+
next unless embedding_compatible?(left: provenance, right: stored_provenance)
|
|
734
672
|
|
|
735
|
-
sim =
|
|
736
|
-
next unless
|
|
673
|
+
sim = similarity_cosine(vec_a: embedding, vec_b: stored_vector)
|
|
674
|
+
next unless similarity_above_corroboration_threshold?(similarity: sim)
|
|
737
675
|
|
|
738
676
|
same_provider_wt = settings[:corroboration][:same_provider_weight]
|
|
739
|
-
weight =
|
|
677
|
+
weight = knowledge_same_source_provider?(source_agent, entry) ? same_provider_wt : 1.0
|
|
740
678
|
|
|
741
679
|
# Reject corroboration entirely if same channel (same data source)
|
|
742
680
|
if source_channel && entry.respond_to?(:source_channel)
|
|
@@ -746,7 +684,7 @@ module Legion
|
|
|
746
684
|
next if weight.zero?
|
|
747
685
|
|
|
748
686
|
entry.update(
|
|
749
|
-
confidence:
|
|
687
|
+
confidence: confidence_apply_corroboration_boost(confidence: entry.confidence, weight: weight),
|
|
750
688
|
updated_at: Time.now
|
|
751
689
|
)
|
|
752
690
|
log.info("Apollo Knowledge.find_corroboration matched entry_id=#{entry.id} source_agent=#{source_agent} similarity=#{sim}")
|
|
@@ -757,28 +695,28 @@ module Legion
|
|
|
757
695
|
[false, nil]
|
|
758
696
|
end
|
|
759
697
|
|
|
760
|
-
def
|
|
698
|
+
def knowledge_same_source_provider?(submitting_agent, entry)
|
|
761
699
|
stored = entry.respond_to?(:source_provider) ? entry.source_provider : nil
|
|
762
700
|
return false if stored.nil? || stored.to_s.empty? || stored.to_s == 'unknown'
|
|
763
701
|
|
|
764
|
-
|
|
702
|
+
knowledge_derive_provider_from_agent(submitting_agent) == stored.to_s
|
|
765
703
|
end
|
|
766
704
|
|
|
767
|
-
def
|
|
705
|
+
def knowledge_derive_provider_from_agent(source_agent)
|
|
768
706
|
return 'unknown' if source_agent.nil? || source_agent == 'unknown'
|
|
769
707
|
|
|
770
708
|
provider = source_agent.to_s.split(/[-_]/).first.downcase
|
|
771
709
|
%w[claude openai gemini human system].include?(provider) ? provider : 'unknown'
|
|
772
710
|
end
|
|
773
711
|
|
|
774
|
-
def
|
|
712
|
+
def knowledge_upsert_expertise(source_agent:, domain:)
|
|
775
713
|
log.debug("Apollo Knowledge.upsert_expertise source_agent=#{source_agent} domain=#{domain}")
|
|
776
|
-
expertise =
|
|
777
|
-
|
|
714
|
+
expertise = data_model_expertise
|
|
715
|
+
.where(agent_id: source_agent, domain: domain).first
|
|
778
716
|
if expertise
|
|
779
717
|
expertise.update(entry_count: expertise.entry_count + 1, last_active_at: Time.now)
|
|
780
718
|
else
|
|
781
|
-
|
|
719
|
+
data_model_expertise.create(
|
|
782
720
|
agent_id: source_agent, domain: domain,
|
|
783
721
|
proficiency: settings[:expertise][:initial_proficiency],
|
|
784
722
|
entry_count: 1, last_active_at: Time.now
|
|
@@ -786,7 +724,12 @@ module Legion
|
|
|
786
724
|
end
|
|
787
725
|
end
|
|
788
726
|
|
|
789
|
-
def
|
|
727
|
+
def knowledge_resolve_process_identity(principal_id: UNSET, identity_id: UNSET, canonical_name: UNSET, **)
|
|
728
|
+
unless principal_id.equal?(UNSET)
|
|
729
|
+
return { principal_id: principal_id,
|
|
730
|
+
identity_id: identity_id.equal?(UNSET) ? nil : identity_id,
|
|
731
|
+
canonical_name: canonical_name.equal?(UNSET) ? nil : canonical_name }
|
|
732
|
+
end
|
|
790
733
|
return { principal_id: nil, identity_id: nil, canonical_name: nil } unless defined?(Legion::Identity::Process)
|
|
791
734
|
|
|
792
735
|
{
|
|
@@ -794,27 +737,14 @@ module Legion
|
|
|
794
737
|
identity_id: Legion::Identity::Process.db_identity_id,
|
|
795
738
|
canonical_name: Legion::Identity::Process.canonical_name
|
|
796
739
|
}
|
|
797
|
-
rescue StandardError => e
|
|
798
|
-
handle_exception(e, level: :warn, operation: 'apollo.knowledge.resolve_process_identity')
|
|
799
|
-
{ principal_id: nil, identity_id: nil, canonical_name: nil }
|
|
800
740
|
end
|
|
801
741
|
|
|
802
|
-
def
|
|
742
|
+
def knowledge_resolve_requesting_principal_id(explicit_value)
|
|
803
743
|
return explicit_value if explicit_value
|
|
804
744
|
return nil unless defined?(Legion::Identity::Process)
|
|
805
745
|
|
|
806
746
|
Legion::Identity::Process.db_principal_id
|
|
807
|
-
rescue StandardError => e
|
|
808
|
-
handle_exception(e, level: :warn, operation: 'apollo.knowledge.resolve_requesting_principal_id')
|
|
809
|
-
nil
|
|
810
747
|
end
|
|
811
|
-
|
|
812
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
813
|
-
include Legion::JSON::Helper
|
|
814
|
-
include Legion::Settings::Helper
|
|
815
|
-
extend Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
816
|
-
extend Legion::JSON::Helper
|
|
817
|
-
extend Legion::Settings::Helper
|
|
818
748
|
end
|
|
819
749
|
end
|
|
820
750
|
end
|