lex-apollo 0.4.44 → 0.4.49
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 +54 -0
- data/README.md +76 -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 +16 -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 +146 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +120 -142
- data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
- data/lib/legion/extensions/apollo/runners/maintenance.rb +154 -65
- 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/transport.rb +8 -5
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +28 -24
- data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +9 -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 +16 -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 +35 -6
- 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 +205 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +14 -91
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +28 -11
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +87 -77
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +14 -89
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +141 -9
- 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 +14 -5
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +48 -64
- 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/legion/extensions/apollo/transport_spec.rb +33 -0
- data/spec/spec_helper.rb +42 -13
- metadata +41 -13
- 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/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
|
@@ -1,41 +1,72 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
require 'legion/logging/helper'
|
|
4
|
+
require 'legion/settings/helper'
|
|
5
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
6
|
+
require 'legion/extensions/apollo/helpers/storage'
|
|
4
7
|
|
|
5
8
|
module Legion
|
|
6
9
|
module Extensions
|
|
7
10
|
module Apollo
|
|
8
11
|
module Runners
|
|
9
12
|
module Expertise
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
include Legion::Logging::Helper
|
|
14
|
+
include Legion::Settings::Helper
|
|
15
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
16
|
+
extend Legion::Extensions::Apollo::Helpers::Storage
|
|
17
|
+
extend self
|
|
18
|
+
|
|
19
|
+
def get_expertise(domain:, min_proficiency: settings[:expertise][:initial_proficiency], **)
|
|
20
|
+
model = data_model_expertise
|
|
21
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
22
|
+
|
|
23
|
+
entries = model.where(domain: domain).where { proficiency >= min_proficiency }.order(Sequel.desc(:proficiency)).all
|
|
24
|
+
formatted = entries.map(&:values)
|
|
25
|
+
{ success: true, domain: domain, min_proficiency: min_proficiency, entries: formatted, count: formatted.size }
|
|
26
|
+
rescue Sequel::Error => e
|
|
27
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.get_expertise', domain: domain)
|
|
28
|
+
{ success: false, error: e.message, entries: [], count: 0 }
|
|
12
29
|
end
|
|
13
30
|
|
|
14
|
-
def domains_at_risk(min_agents:
|
|
15
|
-
|
|
31
|
+
def domains_at_risk(min_agents: settings[:expertise][:min_agents_at_risk], **)
|
|
32
|
+
model = data_model_expertise
|
|
33
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
34
|
+
|
|
35
|
+
agent_count = Sequel.function(:count, :agent_id).distinct
|
|
36
|
+
domains = model.select_group(:domain).select_append(agent_count.as(:agent_count))
|
|
37
|
+
.having(agent_count < min_agents).order(:domain).naked.all
|
|
38
|
+
{ success: true, min_agents: min_agents, domains: domains, count: domains.size }
|
|
39
|
+
rescue Sequel::Error => e
|
|
40
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.domains_at_risk')
|
|
41
|
+
{ success: false, error: e.message, domains: [], count: 0 }
|
|
16
42
|
end
|
|
17
43
|
|
|
18
44
|
def agent_profile(agent_id:, **)
|
|
19
|
-
|
|
45
|
+
model = data_model_expertise
|
|
46
|
+
return { success: false, error: 'apollo_data_not_available' } unless model
|
|
47
|
+
|
|
48
|
+
entries = model.where(agent_id: agent_id).order(:domain).all.map(&:values)
|
|
49
|
+
{ success: true, agent_id: agent_id, entries: entries, count: entries.size }
|
|
50
|
+
rescue Sequel::Error => e
|
|
51
|
+
handle_exception(e, level: :error, operation: 'apollo.expertise.agent_profile', agent_id: agent_id)
|
|
52
|
+
{ success: false, error: e.message, agent_id: agent_id, entries: [], count: 0 }
|
|
20
53
|
end
|
|
21
54
|
|
|
22
55
|
def aggregate(**)
|
|
23
|
-
|
|
56
|
+
model = data_model_entry
|
|
57
|
+
expertise_model = data_model_expertise
|
|
58
|
+
unless model && expertise_model
|
|
24
59
|
log.warn('Apollo Expertise.aggregate skipped: apollo_data_not_available')
|
|
25
60
|
return { success: false, error: 'apollo_data_not_available' }
|
|
26
61
|
end
|
|
27
62
|
|
|
28
|
-
entries =
|
|
29
|
-
.select(:source_agent, :tags, :confidence)
|
|
30
|
-
.exclude(source_agent: nil)
|
|
31
|
-
.all
|
|
63
|
+
entries = model.select(:source_agent, :knowledge_domain, :tags, :confidence).exclude(source_agent: nil).all
|
|
32
64
|
log.debug("Apollo Expertise.aggregate entries=#{entries.size}")
|
|
33
65
|
|
|
34
66
|
agent_set = Set.new
|
|
35
67
|
domain_set = Set.new
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
upsert_expertise_group(group)
|
|
68
|
+
expertise_groups(entries: entries).each_value do |group|
|
|
69
|
+
expertise_upsert_group(model: expertise_model, group: group)
|
|
39
70
|
agent_set << group[:agent_id]
|
|
40
71
|
domain_set << group[:domain]
|
|
41
72
|
end
|
|
@@ -47,39 +78,37 @@ module Legion
|
|
|
47
78
|
{ success: false, error: e.message }
|
|
48
79
|
end
|
|
49
80
|
|
|
50
|
-
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
def expertise_groups(entries:, **)
|
|
51
84
|
entries.each_with_object({}) do |entry, groups|
|
|
52
85
|
agent = entry.source_agent
|
|
53
|
-
domain = entry.
|
|
54
|
-
|
|
86
|
+
domain = entry.knowledge_domain ||
|
|
87
|
+
storage_deserialize_tags(tags: entry.tags).first || 'general'
|
|
88
|
+
key = [agent, domain]
|
|
55
89
|
groups[key] ||= { agent_id: agent, domain: domain, confidences: [] }
|
|
56
90
|
groups[key][:confidences] << entry.confidence.to_f
|
|
57
91
|
end
|
|
58
92
|
end
|
|
59
93
|
|
|
60
|
-
def
|
|
94
|
+
def expertise_upsert_group(model:, group:, **)
|
|
61
95
|
count = group[:confidences].size
|
|
62
|
-
proficiency = expertise_proficiency(group[:confidences])
|
|
63
|
-
existing =
|
|
64
|
-
.where(agent_id: group[:agent_id], domain: group[:domain]).first
|
|
96
|
+
proficiency = expertise_proficiency(confidences: group[:confidences])
|
|
97
|
+
existing = model.first(agent_id: group[:agent_id], domain: group[:domain])
|
|
65
98
|
|
|
66
99
|
if existing
|
|
67
100
|
existing.update(proficiency: proficiency, entry_count: count, last_active_at: Time.now)
|
|
68
101
|
else
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
proficiency: proficiency, entry_count: count, last_active_at: Time.now
|
|
72
|
-
)
|
|
102
|
+
model.create(agent_id: group[:agent_id], domain: group[:domain], proficiency: proficiency,
|
|
103
|
+
entry_count: count, last_active_at: Time.now)
|
|
73
104
|
end
|
|
74
105
|
end
|
|
75
106
|
|
|
76
|
-
def expertise_proficiency(confidences)
|
|
107
|
+
def expertise_proficiency(confidences:, **)
|
|
77
108
|
avg = confidences.sum / confidences.size
|
|
78
|
-
cap =
|
|
109
|
+
cap = settings[:expertise][:proficiency_cap]
|
|
79
110
|
[avg * Math.log2(confidences.size + 1), cap].min
|
|
80
111
|
end
|
|
81
|
-
|
|
82
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
83
112
|
end
|
|
84
113
|
end
|
|
85
114
|
end
|
|
@@ -1,54 +1,51 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require 'legion/llm/inference'
|
|
4
|
+
require 'legion/llm/inference/steps/classification'
|
|
5
|
+
require 'legion/logging/helper'
|
|
6
|
+
require 'legion/settings/helper'
|
|
7
|
+
require 'legion/json'
|
|
8
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
9
|
+
require 'legion/extensions/apollo/runners/entity_extractor'
|
|
10
|
+
require 'legion/extensions/apollo/runners/knowledge'
|
|
11
|
+
|
|
3
12
|
module Legion
|
|
4
13
|
module Extensions
|
|
5
14
|
module Apollo
|
|
6
15
|
module Runners
|
|
7
16
|
module Gas
|
|
8
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
9
17
|
include Legion::Logging::Helper
|
|
10
18
|
include Legion::JSON::Helper
|
|
11
|
-
|
|
12
|
-
extend Legion::
|
|
13
|
-
extend Legion::JSON::Helper
|
|
19
|
+
include Legion::Settings::Helper
|
|
20
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
14
21
|
|
|
15
22
|
RELATION_TYPES = %w[
|
|
16
23
|
similar_to contradicts depends_on causes
|
|
17
24
|
part_of supersedes supports_by extends
|
|
18
25
|
].freeze
|
|
19
26
|
|
|
20
|
-
|
|
21
|
-
SYNTHESIS_CONFIDENCE_CAP = 0.7
|
|
22
|
-
MAX_ANTICIPATIONS = 3
|
|
23
|
-
|
|
24
|
-
module_function
|
|
25
|
-
|
|
26
|
-
def json_load(str)
|
|
27
|
-
json_parse(str)
|
|
28
|
-
end
|
|
29
|
-
|
|
30
|
-
def relate_confidence_gate = Legion::Extensions::Apollo.settings[:gas][:relate_confidence_gate]
|
|
31
|
-
def synthesis_confidence_cap = Legion::Extensions::Apollo.settings[:gas][:synthesis_confidence_cap]
|
|
32
|
-
def max_anticipations = Legion::Extensions::Apollo.settings[:gas][:max_anticipations]
|
|
33
|
-
def similar_entries_limit = Legion::Extensions::Apollo.settings[:gas][:similar_entries_limit]
|
|
34
|
-
def fallback_confidence = Legion::Extensions::Apollo.settings[:gas][:fallback_confidence]
|
|
27
|
+
extend self
|
|
35
28
|
|
|
36
|
-
def process(audit_event)
|
|
37
|
-
unless
|
|
29
|
+
def process(**audit_event)
|
|
30
|
+
unless gas_processable?(audit_event)
|
|
38
31
|
log.debug('GAS process skipped reason=no_content')
|
|
39
|
-
return { phases_completed: 0, reason: 'no content' }
|
|
32
|
+
return { success: true, phases_completed: 0, reason: 'no content' }
|
|
40
33
|
end
|
|
34
|
+
return { success: true, phases_completed: 0, reason: 'disabled' } unless settings[:gas][:enabled] == true
|
|
35
|
+
return { success: true, phases_completed: 0, reason: 'unsafe_audit_event' } unless gas_persistable_event?(audit_event)
|
|
36
|
+
return { success: true, phases_completed: 0, reason: 'llm_unavailable' } unless Legion::LLM.started?
|
|
41
37
|
|
|
42
38
|
log.debug("GAS process start request_id=#{audit_event[:request_id] || 'nil'} messages=#{Array(audit_event[:messages]).size} response_length=#{audit_event[:response_content].to_s.length}") # rubocop:disable Layout/LineLength
|
|
43
39
|
|
|
44
|
-
facts =
|
|
45
|
-
entities =
|
|
46
|
-
relations =
|
|
47
|
-
synthesis =
|
|
48
|
-
deposit_result =
|
|
49
|
-
anticipations =
|
|
40
|
+
facts = gas_phase_comprehend(audit_event).reject { |fact| gas_sensitive_content?(fact[:content]) }
|
|
41
|
+
entities = gas_phase_extract(audit_event, facts)
|
|
42
|
+
relations = gas_phase_relate(facts: facts, requesting_principal_id: audit_event[:identity_principal_id])
|
|
43
|
+
synthesis = gas_phase_synthesize(facts, relations)
|
|
44
|
+
deposit_result = gas_phase_deposit(facts: facts, relations: relations, synthesis: synthesis, audit_event: audit_event)
|
|
45
|
+
anticipations = []
|
|
50
46
|
|
|
51
47
|
result = {
|
|
48
|
+
success: deposit_result[:failed].zero? && deposit_result[:relations_failed].zero?,
|
|
52
49
|
phases_completed: 6,
|
|
53
50
|
facts: facts.length,
|
|
54
51
|
entities: entities.length,
|
|
@@ -61,49 +58,56 @@ module Legion
|
|
|
61
58
|
result
|
|
62
59
|
rescue StandardError => e
|
|
63
60
|
handle_exception(e, level: :error, operation: 'apollo.gas.process')
|
|
64
|
-
{ phases_completed: 0, error: e.message }
|
|
61
|
+
{ success: false, phases_completed: 0, error: e.message }
|
|
65
62
|
end
|
|
66
63
|
|
|
67
|
-
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
def gas_processable?(event)
|
|
68
67
|
event[:messages]&.any? == true && !event[:response_content].nil?
|
|
69
68
|
end
|
|
70
69
|
|
|
70
|
+
def gas_persistable_event?(event)
|
|
71
|
+
return false unless event[:access_scope].to_s == 'private'
|
|
72
|
+
return false unless event[:identity_principal_id].is_a?(Integer) && event[:identity_principal_id].positive?
|
|
73
|
+
return false unless event[:content_sanitized] == true
|
|
74
|
+
|
|
75
|
+
!gas_sensitive_content?(Legion::JSON.dump([event[:messages], event[:response_content]]))
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def gas_sensitive_content?(content)
|
|
79
|
+
text = content.to_s
|
|
80
|
+
classification = Legion::LLM::Inference::Steps::Classification
|
|
81
|
+
classification::PII_PATTERNS.each_value do |pattern|
|
|
82
|
+
return true if text.match?(pattern)
|
|
83
|
+
end
|
|
84
|
+
classification::PHI_KEYWORDS.any? { |keyword| text.downcase.include?(keyword) }
|
|
85
|
+
end
|
|
86
|
+
|
|
71
87
|
# Phase 1: Comprehend - extract typed facts from the exchange
|
|
72
|
-
def
|
|
88
|
+
def gas_phase_comprehend(audit_event)
|
|
73
89
|
messages = audit_event[:messages]
|
|
74
90
|
response = audit_event[:response_content]
|
|
75
91
|
|
|
76
|
-
mode
|
|
77
|
-
|
|
78
|
-
facts = mode == :llm ? llm_comprehend(messages, response) : mechanical_comprehend(messages, response)
|
|
92
|
+
log.debug("GAS phase_comprehend mode=llm messages=#{Array(messages).size} response_length=#{response.to_s.length}")
|
|
93
|
+
facts = gas_llm_comprehend(messages, response)
|
|
79
94
|
log.debug("GAS phase_comprehend facts=#{facts.size}")
|
|
80
95
|
facts
|
|
81
96
|
end
|
|
82
97
|
|
|
83
98
|
# Phase 2: Extract - entity extraction (delegates to existing EntityExtractor)
|
|
84
|
-
def
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return []
|
|
88
|
-
end
|
|
99
|
+
def gas_phase_extract(audit_event, _facts)
|
|
100
|
+
result = Legion::Extensions::Apollo::Runners::EntityExtractor.extract_entities(text: audit_event[:response_content])
|
|
101
|
+
raise IOError, "Apollo entity extraction failed: #{result[:error]}" unless result[:success]
|
|
89
102
|
|
|
90
|
-
|
|
91
|
-
entities = result[:success] ? (result[:entities] || []) : []
|
|
103
|
+
entities = result[:entities]
|
|
92
104
|
log.debug("GAS phase_extract success=#{result[:success]} entities=#{entities.size}")
|
|
93
105
|
entities
|
|
94
|
-
rescue StandardError => e
|
|
95
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_extract')
|
|
96
|
-
[]
|
|
97
106
|
end
|
|
98
107
|
|
|
99
108
|
# Phase 3: Relate - classify relationships between new and existing entries
|
|
100
|
-
def
|
|
101
|
-
|
|
102
|
-
log.debug('GAS phase_relate skipped reason=knowledge_runner_unavailable')
|
|
103
|
-
return []
|
|
104
|
-
end
|
|
105
|
-
|
|
106
|
-
existing = fetch_similar_entries(facts)
|
|
109
|
+
def gas_phase_relate(facts:, requesting_principal_id: nil, **)
|
|
110
|
+
existing = gas_fetch_similar_entries(facts: facts, requesting_principal_id: requesting_principal_id)
|
|
107
111
|
if existing.empty?
|
|
108
112
|
log.debug("GAS phase_relate skipped reason=no_existing_entries facts=#{facts.size}")
|
|
109
113
|
return []
|
|
@@ -112,7 +116,7 @@ module Legion
|
|
|
112
116
|
relations = []
|
|
113
117
|
facts.each do |fact|
|
|
114
118
|
existing.each do |entry|
|
|
115
|
-
relation =
|
|
119
|
+
relation = gas_classify_relation(fact, entry)
|
|
116
120
|
relations << relation if relation
|
|
117
121
|
end
|
|
118
122
|
end
|
|
@@ -121,36 +125,32 @@ module Legion
|
|
|
121
125
|
end
|
|
122
126
|
|
|
123
127
|
# Phase 4: Synthesize - generate derivative knowledge
|
|
124
|
-
def
|
|
128
|
+
def gas_phase_synthesize(facts, _relations)
|
|
125
129
|
if facts.length < 2
|
|
126
130
|
log.debug("GAS phase_synthesize skipped reason=insufficient_facts facts=#{facts.length}")
|
|
127
131
|
return []
|
|
128
132
|
end
|
|
129
|
-
unless
|
|
133
|
+
unless Legion::LLM.started?
|
|
130
134
|
log.debug('GAS phase_synthesize skipped reason=llm_unavailable')
|
|
131
135
|
return []
|
|
132
136
|
end
|
|
133
137
|
|
|
134
|
-
synthesis =
|
|
138
|
+
synthesis = gas_llm_synthesize(facts)
|
|
135
139
|
log.debug("GAS phase_synthesize synthesis=#{synthesis.size}")
|
|
136
140
|
synthesis
|
|
137
|
-
rescue StandardError => e
|
|
138
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_synthesize')
|
|
139
|
-
[]
|
|
140
141
|
end
|
|
141
142
|
|
|
142
143
|
# Phase 5: Deposit entries, then link successfully stored facts.
|
|
143
|
-
def
|
|
144
|
+
def gas_phase_deposit(facts:, relations:, synthesis:, audit_event:, **)
|
|
144
145
|
counts = { deposited: 0, failed: 0, facts: 0, synthesis: 0 }
|
|
145
|
-
unless defined?(Legion::Extensions::Apollo::Runners::Knowledge)
|
|
146
|
-
return counts.merge(failed: facts.size + synthesis.size, relations: 0,
|
|
147
|
-
relations_failed: relations.size, relations_skipped: 0)
|
|
148
|
-
end
|
|
149
|
-
|
|
150
146
|
fact_ids = Array.new(facts.size)
|
|
151
147
|
source_ids = {}
|
|
152
148
|
{ facts: facts, synthesis: synthesis }.each do |kind, entries|
|
|
153
149
|
entries.each_with_index do |item, index|
|
|
150
|
+
if gas_sensitive_content?(item[:content])
|
|
151
|
+
counts[:skipped_sensitive] = counts.fetch(:skipped_sensitive, 0) + 1
|
|
152
|
+
next
|
|
153
|
+
end
|
|
154
154
|
context = { source_request_id: audit_event[:request_id] }
|
|
155
155
|
if kind == :synthesis
|
|
156
156
|
context[:source_indices] = Array(item[:source_indices])
|
|
@@ -162,7 +162,8 @@ module Legion
|
|
|
162
162
|
content: item[:content], content_type: item[:content_type].to_s,
|
|
163
163
|
tags: %w[gas auto_extracted], source_agent: 'gas_pipeline',
|
|
164
164
|
source_provider: audit_event.dig(:routing, :provider),
|
|
165
|
-
knowledge_domain: 'general', context: context
|
|
165
|
+
knowledge_domain: 'general', context: context,
|
|
166
|
+
access_scope: 'private', identity_principal_id: audit_event[:identity_principal_id]
|
|
166
167
|
)
|
|
167
168
|
unless result.is_a?(Hash) && result[:success] == true && result[:entry_id]
|
|
168
169
|
counts[:failed] += 1
|
|
@@ -189,13 +190,13 @@ module Legion
|
|
|
189
190
|
def gas_deposit_relations(relations:, source_ids:)
|
|
190
191
|
counts = { relations: 0, relations_failed: 0, relations_skipped: 0 }
|
|
191
192
|
return counts if relations.empty?
|
|
192
|
-
unless
|
|
193
|
-
|
|
193
|
+
unless !data_model_entry.nil? &&
|
|
194
|
+
!data_model_relation.nil?
|
|
194
195
|
return counts.merge(relations_failed: relations.size)
|
|
195
196
|
end
|
|
196
197
|
|
|
197
|
-
entry_model =
|
|
198
|
-
relation_model =
|
|
198
|
+
entry_model = data_model_entry
|
|
199
|
+
relation_model = data_model_relation
|
|
199
200
|
seen = {}
|
|
200
201
|
relations.each do |relation|
|
|
201
202
|
type = relation[:relation_type].to_s
|
|
@@ -213,7 +214,7 @@ module Legion
|
|
|
213
214
|
end
|
|
214
215
|
|
|
215
216
|
key = [source.id, target.id, type]
|
|
216
|
-
if source.id == target.id || source
|
|
217
|
+
if source.id == target.id || gas_relation_crosses_scope?(source: source, target: target) || seen[key]
|
|
217
218
|
counts[:relations_skipped] += 1
|
|
218
219
|
next
|
|
219
220
|
end
|
|
@@ -231,58 +232,58 @@ module Legion
|
|
|
231
232
|
def gas_relation_accepted?(type:, confidence:)
|
|
232
233
|
Legion::Extensions::Apollo::Helpers::Confidence::RELATION_TYPES.include?(type) &&
|
|
233
234
|
confidence.is_a?(Numeric) && confidence.real? && confidence.finite? &&
|
|
234
|
-
confidence.between?(relate_confidence_gate, 1.0)
|
|
235
|
+
confidence.between?(settings[:gas][:relate_confidence_gate], 1.0)
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
def gas_relation_crosses_scope?(source:, target:)
|
|
239
|
+
source[:access_scope] != target[:access_scope] ||
|
|
240
|
+
source[:identity_principal_id] != target[:identity_principal_id]
|
|
235
241
|
end
|
|
236
|
-
private_class_method :gas_deposit_relations, :gas_relation_accepted?
|
|
237
242
|
|
|
238
243
|
# Phase 6: Anticipate - pre-cache likely follow-up questions
|
|
239
|
-
def
|
|
244
|
+
def gas_phase_anticipate(facts, _synthesis)
|
|
240
245
|
if facts.empty?
|
|
241
246
|
log.debug('GAS phase_anticipate skipped reason=no_facts')
|
|
242
247
|
return []
|
|
243
248
|
end
|
|
244
|
-
unless
|
|
249
|
+
unless Legion::LLM.started?
|
|
245
250
|
log.debug('GAS phase_anticipate skipped reason=llm_unavailable')
|
|
246
251
|
return []
|
|
247
252
|
end
|
|
248
253
|
|
|
249
|
-
anticipations =
|
|
254
|
+
anticipations = gas_llm_anticipate(facts)
|
|
250
255
|
log.debug("GAS phase_anticipate anticipations=#{anticipations.size}")
|
|
251
256
|
anticipations
|
|
252
|
-
rescue StandardError => e
|
|
253
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.phase_anticipate')
|
|
254
|
-
[]
|
|
255
257
|
end
|
|
256
258
|
|
|
257
|
-
def
|
|
258
|
-
lim = similar_entries_limit
|
|
259
|
-
min_conf =
|
|
259
|
+
def gas_fetch_similar_entries(facts:, requesting_principal_id: nil, **)
|
|
260
|
+
lim = settings[:gas][:similar_entries_limit]
|
|
261
|
+
min_conf = settings[:query][:default_min_confidence]
|
|
260
262
|
entries = []
|
|
261
263
|
facts.each do |fact|
|
|
262
|
-
result = Runners::Knowledge.retrieve_relevant(
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
264
|
+
result = Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(
|
|
265
|
+
query: fact[:content], limit: lim, min_confidence: min_conf,
|
|
266
|
+
requesting_principal_id: requesting_principal_id
|
|
267
|
+
)
|
|
268
|
+
raise IOError, "Apollo semantic retrieval failed: #{result[:error]}" unless result[:success]
|
|
269
|
+
|
|
270
|
+
entries.concat(result[:entries])
|
|
267
271
|
end
|
|
268
272
|
unique = entries.uniq { |e| e[:id] }
|
|
269
273
|
log.debug("GAS fetch_similar_entries facts=#{facts.size} entries=#{unique.size}")
|
|
270
274
|
unique
|
|
271
275
|
end
|
|
272
276
|
|
|
273
|
-
def
|
|
274
|
-
fb_conf = fallback_confidence
|
|
275
|
-
if
|
|
276
|
-
|
|
277
|
+
def gas_classify_relation(fact, entry)
|
|
278
|
+
fb_conf = settings[:gas][:fallback_confidence]
|
|
279
|
+
if Legion::LLM.started?
|
|
280
|
+
gas_llm_classify_relation(fact, entry)
|
|
277
281
|
else
|
|
278
282
|
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fb_conf }
|
|
279
283
|
end
|
|
280
|
-
rescue StandardError => e
|
|
281
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.classify_relation')
|
|
282
|
-
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fallback_confidence }
|
|
283
284
|
end
|
|
284
285
|
|
|
285
|
-
def
|
|
286
|
+
def gas_llm_classify_relation(fact, entry) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
|
|
286
287
|
prompt = <<~PROMPT
|
|
287
288
|
Classify the relationship between these two knowledge entries.
|
|
288
289
|
Valid types: #{RELATION_TYPES.join(', ')}
|
|
@@ -293,7 +294,7 @@ module Legion
|
|
|
293
294
|
Return JSON with relation_type and confidence (0.0-1.0).
|
|
294
295
|
PROMPT
|
|
295
296
|
|
|
296
|
-
result = Legion::LLM::
|
|
297
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
297
298
|
message: prompt.strip,
|
|
298
299
|
schema: {
|
|
299
300
|
type: :object,
|
|
@@ -319,28 +320,25 @@ module Legion
|
|
|
319
320
|
result[:data][:relations] || result.dig(:data, 'relations') || []
|
|
320
321
|
else
|
|
321
322
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
322
|
-
parsed =
|
|
323
|
+
parsed = json_parse(content)
|
|
323
324
|
parsed.is_a?(Hash) ? (parsed[:relations] || parsed['relations'] || []) : []
|
|
324
325
|
end
|
|
325
326
|
best = rels.max_by { |r| r[:confidence] || r['confidence'] || 0 }
|
|
326
327
|
|
|
327
|
-
return
|
|
328
|
+
return gas_fallback_relation(fact, entry) unless best
|
|
328
329
|
|
|
329
330
|
conf = best[:confidence] || best['confidence'] || 0
|
|
330
331
|
rtype = best[:relation_type] || best['relation_type']
|
|
331
|
-
return
|
|
332
|
+
return gas_fallback_relation(fact, entry) if conf < settings[:gas][:relate_confidence_gate] || !RELATION_TYPES.include?(rtype)
|
|
332
333
|
|
|
333
334
|
{ from_content: fact[:content], to_id: entry[:id], relation_type: rtype, confidence: conf }
|
|
334
|
-
rescue StandardError => e
|
|
335
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_classify_relation')
|
|
336
|
-
fallback_relation(fact, entry)
|
|
337
335
|
end
|
|
338
336
|
|
|
339
|
-
def
|
|
340
|
-
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: fallback_confidence }
|
|
337
|
+
def gas_fallback_relation(fact, entry)
|
|
338
|
+
{ from_content: fact[:content], to_id: entry[:id], relation_type: 'similar_to', confidence: settings[:gas][:fallback_confidence] }
|
|
341
339
|
end
|
|
342
340
|
|
|
343
|
-
def
|
|
341
|
+
def gas_llm_synthesize(facts)
|
|
344
342
|
facts_text = facts.each_with_index.map { |f, i| "[#{i}] (#{f[:content_type]}) #{f[:content]}" }.join("\n")
|
|
345
343
|
|
|
346
344
|
prompt = <<~PROMPT
|
|
@@ -353,7 +351,7 @@ module Legion
|
|
|
353
351
|
Return JSON with a "synthesis" array where each item has: content (string), content_type (inference/implication/connection), source_indices (array of entry indices used).
|
|
354
352
|
PROMPT
|
|
355
353
|
|
|
356
|
-
result = Legion::LLM::
|
|
354
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
357
355
|
message: prompt.strip,
|
|
358
356
|
schema: {
|
|
359
357
|
type: :object,
|
|
@@ -380,39 +378,36 @@ module Legion
|
|
|
380
378
|
result[:data][:synthesis] || result.dig(:data, 'synthesis') || []
|
|
381
379
|
else
|
|
382
380
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
383
|
-
parsed =
|
|
381
|
+
parsed = json_parse(content)
|
|
384
382
|
parsed.is_a?(Hash) ? (parsed[:synthesis] || parsed['synthesis'] || []) : []
|
|
385
383
|
end
|
|
386
384
|
|
|
387
|
-
items.map { |item|
|
|
388
|
-
rescue StandardError => e
|
|
389
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_synthesize')
|
|
390
|
-
[]
|
|
385
|
+
items.map { |item| gas_build_synthesis_entry(item, facts) }
|
|
391
386
|
end
|
|
392
387
|
|
|
393
|
-
def
|
|
388
|
+
def gas_build_synthesis_entry(item, facts)
|
|
394
389
|
source_indices = item[:source_indices] || item['source_indices'] || []
|
|
395
390
|
source_confs = source_indices.filter_map { |i| facts[i]&.dig(:confidence) }
|
|
396
|
-
fb = fallback_confidence
|
|
397
|
-
geo_mean = source_confs.empty? ? fb :
|
|
391
|
+
fb = settings[:gas][:fallback_confidence]
|
|
392
|
+
geo_mean = source_confs.empty? ? fb : gas_geometric_mean(source_confs)
|
|
398
393
|
|
|
399
394
|
{
|
|
400
395
|
content: item[:content] || item['content'],
|
|
401
396
|
content_type: (item[:content_type] || item['content_type'] || 'inference').to_sym,
|
|
402
397
|
status: :candidate,
|
|
403
|
-
confidence: [geo_mean, synthesis_confidence_cap].min,
|
|
398
|
+
confidence: [geo_mean, settings[:gas][:synthesis_confidence_cap]].min,
|
|
404
399
|
source_indices: source_indices
|
|
405
400
|
}
|
|
406
401
|
end
|
|
407
402
|
|
|
408
|
-
def
|
|
403
|
+
def gas_geometric_mean(values)
|
|
409
404
|
return 0.0 if values.empty?
|
|
410
405
|
|
|
411
406
|
product = values.reduce(1.0) { |acc, v| acc * v }
|
|
412
407
|
product**(1.0 / values.length)
|
|
413
408
|
end
|
|
414
409
|
|
|
415
|
-
def
|
|
410
|
+
def gas_llm_anticipate(facts)
|
|
416
411
|
facts_text = facts.map { |f| "(#{f[:content_type]}) #{f[:content]}" }.join("\n")
|
|
417
412
|
|
|
418
413
|
prompt = <<~PROMPT
|
|
@@ -424,7 +419,7 @@ module Legion
|
|
|
424
419
|
Return JSON with a "questions" array of question strings.
|
|
425
420
|
PROMPT
|
|
426
421
|
|
|
427
|
-
result = Legion::LLM::
|
|
422
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
428
423
|
message: prompt.strip,
|
|
429
424
|
schema: {
|
|
430
425
|
type: :object,
|
|
@@ -440,45 +435,31 @@ module Legion
|
|
|
440
435
|
result[:data][:questions] || result.dig(:data, 'questions') || []
|
|
441
436
|
else
|
|
442
437
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
443
|
-
parsed =
|
|
438
|
+
parsed = json_parse(content)
|
|
444
439
|
parsed.is_a?(Hash) ? (parsed[:questions] || parsed['questions'] || []) : []
|
|
445
440
|
end
|
|
446
|
-
questions = questions.first(max_anticipations)
|
|
441
|
+
questions = questions.first(settings[:gas][:max_anticipations])
|
|
447
442
|
|
|
448
443
|
questions.map do |q|
|
|
449
|
-
|
|
444
|
+
gas_promote_to_pattern_store(question: q, facts: facts)
|
|
450
445
|
{ question: q }
|
|
451
446
|
end
|
|
452
|
-
rescue StandardError => e
|
|
453
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_anticipate')
|
|
454
|
-
[]
|
|
455
447
|
end
|
|
456
448
|
|
|
457
|
-
def
|
|
449
|
+
def gas_promote_to_pattern_store(question:, facts:)
|
|
458
450
|
return unless defined?(Legion::Extensions::Agentic::TBI::PatternStore)
|
|
459
451
|
|
|
460
452
|
Legion::Extensions::Agentic::TBI::PatternStore.promote_candidate(
|
|
461
453
|
intent: question,
|
|
462
454
|
resolution: { source: 'gas_anticipate', facts: facts.map { |f| f[:content] } },
|
|
463
|
-
confidence: fallback_confidence
|
|
455
|
+
confidence: settings[:gas][:fallback_confidence]
|
|
464
456
|
)
|
|
465
457
|
rescue StandardError => e
|
|
466
458
|
handle_exception(e, level: :warn, operation: 'apollo.gas.promote_to_pattern_store')
|
|
467
459
|
nil
|
|
468
460
|
end
|
|
469
461
|
|
|
470
|
-
def
|
|
471
|
-
defined?(Legion::LLM::Pipeline::GaiaCaller)
|
|
472
|
-
rescue StandardError => e
|
|
473
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_available')
|
|
474
|
-
false
|
|
475
|
-
end
|
|
476
|
-
|
|
477
|
-
def mechanical_comprehend(_messages, response)
|
|
478
|
-
[{ content: response, content_type: :observation }]
|
|
479
|
-
end
|
|
480
|
-
|
|
481
|
-
def llm_comprehend(messages, response)
|
|
462
|
+
def gas_llm_comprehend(messages, response)
|
|
482
463
|
prompt = <<~PROMPT
|
|
483
464
|
Extract distinct facts from this exchange. Return JSON array of {content:, content_type:} where content_type is one of: fact, concept, procedure, association.
|
|
484
465
|
|
|
@@ -486,7 +467,7 @@ module Legion
|
|
|
486
467
|
Assistant: #{response}
|
|
487
468
|
PROMPT
|
|
488
469
|
|
|
489
|
-
result = Legion::LLM::
|
|
470
|
+
result = Legion::LLM::Inference::GaiaCaller.structured(
|
|
490
471
|
message: prompt.strip,
|
|
491
472
|
schema: {
|
|
492
473
|
type: :object,
|
|
@@ -512,7 +493,7 @@ module Legion
|
|
|
512
493
|
result[:data][:facts] || result.dig(:data, 'facts') || []
|
|
513
494
|
else
|
|
514
495
|
content = result.respond_to?(:message) ? result.message[:content] : result.to_s
|
|
515
|
-
parsed =
|
|
496
|
+
parsed = json_parse(content)
|
|
516
497
|
parsed.is_a?(Hash) ? (parsed[:facts] || parsed['facts'] || []) : Array(parsed)
|
|
517
498
|
end
|
|
518
499
|
facts_array.map do |f|
|
|
@@ -521,9 +502,6 @@ module Legion
|
|
|
521
502
|
content_type: (f[:content_type] || f['content_type'] || 'fact').to_sym
|
|
522
503
|
}
|
|
523
504
|
end
|
|
524
|
-
rescue StandardError => e
|
|
525
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas.llm_comprehend')
|
|
526
|
-
mechanical_comprehend(messages, response)
|
|
527
505
|
end
|
|
528
506
|
end
|
|
529
507
|
end
|