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.
Files changed (94) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +54 -0
  3. data/README.md +76 -14
  4. data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -41
  5. data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
  6. data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
  7. data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
  8. data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
  9. data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +16 -16
  10. data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
  11. data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
  12. data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
  13. data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
  14. data/lib/legion/extensions/apollo/api.rb +96 -41
  15. data/lib/legion/extensions/apollo/client.rb +20 -9
  16. data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
  17. data/lib/legion/extensions/apollo/helpers/capability.rb +10 -51
  18. data/lib/legion/extensions/apollo/helpers/confidence.rb +8 -52
  19. data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
  20. data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
  21. data/lib/legion/extensions/apollo/helpers/graph_query.rb +99 -43
  22. data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
  23. data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
  24. data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
  25. data/lib/legion/extensions/apollo/helpers/writeback.rb +64 -102
  26. data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
  27. data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
  28. data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
  29. data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +146 -0
  30. data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
  31. data/lib/legion/extensions/apollo/runners/gas.rb +120 -142
  32. data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
  33. data/lib/legion/extensions/apollo/runners/maintenance.rb +154 -65
  34. data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
  35. data/lib/legion/extensions/apollo/runners/request.rb +51 -46
  36. data/lib/legion/extensions/apollo/runners/search.rb +88 -0
  37. data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
  38. data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
  39. data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
  40. data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
  41. data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
  42. data/lib/legion/extensions/apollo/transport.rb +8 -5
  43. data/lib/legion/extensions/apollo/version.rb +1 -1
  44. data/lib/legion/extensions/apollo.rb +28 -24
  45. data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +9 -24
  46. data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
  47. data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
  48. data/spec/legion/extensions/apollo/api_spec.rb +240 -8
  49. data/spec/legion/extensions/apollo/contradiction_spec.rb +28 -50
  50. data/spec/legion/extensions/apollo/gaia_integration_spec.rb +16 -21
  51. data/spec/legion/extensions/apollo/helpers/capability_spec.rb +24 -27
  52. data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
  53. data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
  54. data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +108 -0
  55. data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
  56. data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
  57. data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
  58. data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +73 -74
  59. data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +35 -6
  60. data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
  61. data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
  62. data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
  63. data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +205 -0
  64. data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
  65. data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +14 -91
  66. data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +28 -11
  67. data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
  68. data/spec/legion/extensions/apollo/runners/gas_spec.rb +87 -77
  69. data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +14 -89
  70. data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +141 -9
  71. data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
  72. data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +314 -655
  73. data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +14 -5
  74. data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +48 -64
  75. data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
  76. data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
  77. data/spec/legion/extensions/apollo/runners/request_spec.rb +120 -98
  78. data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
  79. data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
  80. data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
  81. data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
  82. data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
  83. data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
  84. data/spec/legion/extensions/apollo/transport_spec.rb +33 -0
  85. data/spec/spec_helper.rb +42 -13
  86. metadata +41 -13
  87. data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
  88. data/spec/legion/extensions/apollo/actors/contradiction_scanner_spec.rb +0 -38
  89. data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
  90. data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
  91. data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
  92. data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
  93. data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
  94. data/spec/legion/extensions/apollo/helpers/entity_watchdog_spec.rb +0 -64
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'sequel'
5
+ require 'stringio'
6
+ require 'logger'
7
+ require 'legion/extensions/apollo/runners/entity_watchdog'
8
+
9
+ RSpec.describe Legion::Extensions::Apollo::Runners::EntityWatchdog do
10
+ let(:db) { Sequel.sqlite }
11
+ let(:published) { [] }
12
+
13
+ before do
14
+ allow(described_class).to receive(:settings).and_return(
15
+ Legion::Extensions::Apollo.default_settings.merge(
16
+ entity_watchdog: Legion::Extensions::Apollo.default_settings[:entity_watchdog].merge(enabled: true)
17
+ )
18
+ )
19
+ db.create_table(:task_logs) do
20
+ primary_key :id
21
+ String :entry
22
+ String :access_scope, default: 'global'
23
+ Integer :identity_principal_id
24
+ Integer :identity_id
25
+ DateTime :created_at
26
+ end
27
+ stub_const('Legion::Data::Model::TaskLog', Class.new(Sequel::Model(db[:task_logs])))
28
+
29
+ messages = published
30
+ message_class = Class.new do
31
+ define_singleton_method(:published) { messages }
32
+ define_method(:initialize) { |**attributes| @attributes = attributes }
33
+ define_method(:publish!) do
34
+ messages << @attributes
35
+ { accepted: true }
36
+ end
37
+ end
38
+ stub_const('Legion::Extensions::Apollo::Transport::Messages::Ingest', message_class)
39
+ described_class.instance_variable_set(:@entity_watchdog_processed_hashes, {})
40
+ end
41
+
42
+ after do
43
+ db.disconnect
44
+ described_class.remove_instance_variable(:@entity_watchdog_processed_hashes) if
45
+ described_class.instance_variable_defined?(:@entity_watchdog_processed_hashes)
46
+ end
47
+
48
+ def log_entry(text, offset: 0, access_scope: 'global', identity_principal_id: nil, identity_id: nil)
49
+ Legion::Data::Model::TaskLog.create(entry: text, created_at: Time.now - offset,
50
+ access_scope: access_scope, identity_principal_id: identity_principal_id,
51
+ identity_id: identity_id)
52
+ end
53
+
54
+ def stub_process_identity(principal_id: 42, identity_id: 9)
55
+ stub_const('Legion::Identity', Module.new) unless defined?(Legion::Identity)
56
+ stub_const('Legion::Identity::Process', Class.new do
57
+ define_singleton_method(:db_principal_id) { principal_id }
58
+ define_singleton_method(:db_identity_id) { identity_id }
59
+ end)
60
+ end
61
+
62
+ it 'does not query task logs unless explicitly enabled' do
63
+ allow(described_class).to receive(:settings).and_return(Legion::Extensions::Apollo.default_settings)
64
+ log_entry('private task text')
65
+ expect(Legion::Data::Model::TaskLog).not_to receive(:where)
66
+
67
+ expect(described_class.scan_and_ingest).to include(success: true, ingested: 0, reason: :disabled)
68
+ expect(published).to be_empty
69
+ end
70
+
71
+ it 'filters task logs in SQL before fetching their text' do
72
+ stub_process_identity
73
+ log_entry('global entry')
74
+ log_entry('public entry', access_scope: 'public')
75
+ log_entry('owned by principal', access_scope: 'private', identity_principal_id: 42)
76
+ log_entry('owned by identity', access_scope: 'private', identity_id: 9)
77
+ log_entry('other user private', access_scope: 'private', identity_principal_id: 99)
78
+ log_entry('conflicting owner', access_scope: 'private', identity_principal_id: 99, identity_id: 9)
79
+ log_entry('other team', access_scope: 'team', identity_principal_id: 99)
80
+ sql_output = StringIO.new
81
+ db.loggers << Logger.new(sql_output)
82
+
83
+ task_logs = described_class.send(:entity_watchdog_recent_task_logs)
84
+
85
+ expect(task_logs).to match_array([
86
+ { text: 'global entry', access_scope: 'global', identity_principal_id: nil },
87
+ { text: 'public entry', access_scope: 'global', identity_principal_id: nil },
88
+ { text: 'owned by principal', access_scope: 'private', identity_principal_id: 42 },
89
+ { text: 'owned by identity', access_scope: 'private', identity_principal_id: 42 }
90
+ ])
91
+ query = sql_output.string.lines.find { |line| line.include?('SELECT') && line.include?('task_logs') }
92
+ expect(query).to match(/WHERE.*access_scope.*identity_principal_id.*identity_id/)
93
+ end
94
+
95
+ it 'queries only global and public logs when no process identity is available' do
96
+ hide_const('Legion::Identity::Process') if defined?(Legion::Identity::Process)
97
+ log_entry('global entry')
98
+ log_entry('private entry', access_scope: 'private', identity_principal_id: 42)
99
+
100
+ expect(described_class.send(:entity_watchdog_recent_task_logs)).to eq(
101
+ [{ text: 'global entry', access_scope: 'global', identity_principal_id: nil }]
102
+ )
103
+ end
104
+
105
+ it 'keeps entities from an owned private log private on lookup and publication' do
106
+ stub_process_identity
107
+ log_entry('private service note', access_scope: 'private', identity_principal_id: 42)
108
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
109
+ .and_return(success: true, source: :llm,
110
+ entities: [{ name: 'private service', type: 'service', confidence: 0.95 }])
111
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
112
+ .and_return(success: true, entries: [], count: 0)
113
+
114
+ expect(described_class.scan_and_ingest).to include(success: true, ingested: 1)
115
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).to have_received(:retrieve_relevant)
116
+ .with(hash_including(requesting_principal_id: 42))
117
+ expect(published).to contain_exactly(hash_including(
118
+ content: 'Service: private service', access_scope: 'private',
119
+ identity_principal_id: 42
120
+ ))
121
+ end
122
+
123
+ it 'reports missing TaskLog storage instead of treating it as an empty scan' do
124
+ hide_const('Legion::Data::Model::TaskLog')
125
+
126
+ result = described_class.scan_and_ingest
127
+
128
+ expect(result).to include(success: false, error: 'task_log_not_available', ingested: 0)
129
+ end
130
+
131
+ it 'ingests a new entity from a real TaskLog row and deduplicates only after success' do
132
+ log_entry('deploying lex-synapse')
133
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
134
+ .and_return(success: true, source: :llm,
135
+ entities: [{ name: 'lex-synapse', type: 'repository', confidence: 0.95 }])
136
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
137
+ .and_return(success: true, entries: [], count: 0)
138
+
139
+ first = described_class.scan_and_ingest
140
+ second = described_class.scan_and_ingest
141
+
142
+ expect(first).to include(success: true, ingested: 1, logs_scanned: 1, failed: 0)
143
+ expect(second).to include(success: true, ingested: 0, logs_scanned: 1, failed: 0)
144
+ expect(Legion::Extensions::Apollo::Runners::EntityExtractor).to have_received(:extract_entities).once
145
+ expect(published).to contain_exactly(hash_including(content: 'Repository: lex-synapse'))
146
+ end
147
+
148
+ it 'reports partial acceptance and retries failed texts while retaining successful deduplication' do
149
+ log_entry('successful text')
150
+ log_entry('retry text', offset: 1)
151
+ attempts = Hash.new(0)
152
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities) do |text:, **|
153
+ attempts[text] += 1
154
+ if text == 'retry text' && attempts[text] == 1
155
+ { success: false, entities: [], source: :error }
156
+ else
157
+ { success: true, source: :llm,
158
+ entities: [{ name: text, type: 'concept', confidence: 0.9 }] }
159
+ end
160
+ end
161
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
162
+ .and_return(success: true, entries: [], count: 0)
163
+
164
+ first = described_class.scan_and_ingest
165
+ second = described_class.scan_and_ingest
166
+
167
+ expect(first).to include(success: false, ingested: 1, logs_scanned: 2, failed: 1)
168
+ expect(second).to include(success: true, ingested: 1, logs_scanned: 2, failed: 0)
169
+ expect(attempts).to eq('successful text' => 1, 'retry text' => 2)
170
+ expect(published.size).to eq(2)
171
+ end
172
+
173
+ it 'does not treat a failed entity lookup as absence and retries that text' do
174
+ log_entry('lookup failure')
175
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
176
+ .and_return(success: true, source: :llm,
177
+ entities: [{ name: 'unknown', type: 'concept', confidence: 0.9 }])
178
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
179
+ .and_return(success: false, error: 'database unavailable')
180
+
181
+ first = described_class.scan_and_ingest
182
+ second = described_class.scan_and_ingest
183
+
184
+ expect(first).to include(success: false, ingested: 0, failed: 1)
185
+ expect(second).to include(success: false, ingested: 0, failed: 1)
186
+ expect(Legion::Extensions::Apollo::Runners::EntityExtractor).to have_received(:extract_entities).twice
187
+ expect(published).to be_empty
188
+ end
189
+
190
+ it 'keeps a publication failure retryable' do
191
+ log_entry('publication failure')
192
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
193
+ .and_return(success: true, source: :llm,
194
+ entities: [{ name: 'broken', type: 'service', confidence: 0.9 }])
195
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
196
+ .and_return(success: true, entries: [], count: 0)
197
+ message = Legion::Extensions::Apollo::Transport::Messages::Ingest
198
+ allow(message).to receive(:new).and_raise(IOError, 'broker unavailable')
199
+
200
+ result = described_class.scan_and_ingest
201
+
202
+ expect(result).to include(success: false, ingested: 0, failed: 1)
203
+ expect(Legion::Extensions::Apollo::Runners::EntityExtractor).to have_received(:extract_entities).once
204
+ end
205
+ end
@@ -4,108 +4,104 @@ require 'spec_helper'
4
4
  require 'legion/extensions/apollo/runners/expertise'
5
5
 
6
6
  RSpec.describe Legion::Extensions::Apollo::Runners::Expertise do
7
- let(:runner) do
8
- obj = Object.new
9
- obj.extend(described_class)
10
- obj
7
+ let(:runner) { described_class }
8
+ let(:database) { Sequel.sqlite }
9
+ let(:entry_model) { Class.new(Sequel::Model(database[:apollo_entries])) }
10
+ let(:expertise_model) { Class.new(Sequel::Model(database[:apollo_expertise])) }
11
+
12
+ before do
13
+ allow(runner).to receive(:settings).and_return(Legion::Extensions::Apollo.settings)
14
+ database.create_table(:apollo_entries) do
15
+ primary_key :id
16
+ String :source_agent
17
+ String :knowledge_domain
18
+ String :tags
19
+ Float :confidence
20
+ end
21
+ database.create_table(:apollo_expertise) do
22
+ primary_key :id
23
+ String :agent_id
24
+ String :domain
25
+ Float :proficiency
26
+ Integer :entry_count
27
+ DateTime :last_active_at
28
+ end
29
+ stub_const('Legion::Data::Model::Apollo::Entry', entry_model)
30
+ stub_const('Legion::Data::Model::Apollo::Expertise', expertise_model)
11
31
  end
12
32
 
33
+ after { database.disconnect }
34
+
13
35
  describe '#get_expertise' do
14
- it 'returns an expertise query payload' do
15
- result = runner.get_expertise(domain: 'vault')
16
- expect(result[:action]).to eq(:expertise_query)
17
- expect(result[:domain]).to eq('vault')
18
- expect(result[:min_proficiency]).to eq(0.0)
36
+ it 'returns persisted expertise ordered by proficiency' do
37
+ expertise_model.create(agent_id: 'worker-1', domain: 'vault', proficiency: 0.8, entry_count: 2)
38
+ expertise_model.create(agent_id: 'worker-2', domain: 'vault', proficiency: 0.6, entry_count: 1)
39
+
40
+ result = runner.get_expertise(domain: 'vault', min_proficiency: 0.0)
41
+
42
+ expect(result).to include(success: true, domain: 'vault', count: 2)
43
+ expect(result[:entries].map { |entry| entry[:agent_id] }).to eq(%w[worker-1 worker-2])
19
44
  end
20
45
  end
21
46
 
22
47
  describe '#domains_at_risk' do
23
- it 'returns an at-risk query payload' do
24
- result = runner.domains_at_risk(min_agents: 2)
25
- expect(result[:action]).to eq(:domains_at_risk)
26
- expect(result[:min_agents]).to eq(2)
48
+ it 'counts distinct agents per domain using SQL aggregation' do
49
+ expertise_model.create(agent_id: 'worker-1', domain: 'vault', proficiency: 0.8, entry_count: 2)
50
+ expertise_model.create(agent_id: 'worker-2', domain: 'vault', proficiency: 0.7, entry_count: 1)
51
+ expertise_model.create(agent_id: 'worker-1', domain: 'claims', proficiency: 0.7, entry_count: 1)
52
+
53
+ result = runner.domains_at_risk(min_agents: 3)
54
+
55
+ expect(result).to include(success: true, min_agents: 3, count: 2)
56
+ expect(result[:domains]).to contain_exactly(
57
+ include(domain: 'claims', agent_count: 1), include(domain: 'vault', agent_count: 2)
58
+ )
27
59
  end
28
60
  end
29
61
 
30
62
  describe '#agent_profile' do
31
- it 'returns a profile query payload' do
63
+ it 'returns one agent profile ordered by domain' do
64
+ expertise_model.create(agent_id: 'worker-1', domain: 'vault', proficiency: 0.8, entry_count: 2)
65
+ expertise_model.create(agent_id: 'worker-1', domain: 'claims', proficiency: 0.7, entry_count: 1)
66
+ expertise_model.create(agent_id: 'worker-2', domain: 'vault', proficiency: 0.6, entry_count: 1)
67
+
32
68
  result = runner.agent_profile(agent_id: 'worker-1')
33
- expect(result[:action]).to eq(:agent_profile)
34
- expect(result[:agent_id]).to eq('worker-1')
69
+
70
+ expect(result).to include(success: true, agent_id: 'worker-1', count: 2)
71
+ expect(result[:entries].map { |entry| entry[:domain] }).to eq(%w[claims vault])
35
72
  end
36
73
  end
37
74
 
38
75
  describe '#aggregate' do
39
- let(:host) { Object.new.extend(described_class) }
40
-
41
- context 'when Apollo data is not available' do
42
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
76
+ it 'returns an explicit error when canonical Apollo models are unavailable' do
77
+ hide_const('Legion::Data::Model::Apollo')
43
78
 
44
- it 'returns a structured error' do
45
- result = host.aggregate
46
- expect(result[:success]).to be false
47
- expect(result[:error]).to eq('apollo_data_not_available')
48
- end
79
+ expect(runner.aggregate).to include(success: false, error: 'apollo_data_not_available')
49
80
  end
50
81
 
51
- context 'when entries exist' do
52
- let(:mock_entry_class) { double('ApolloEntry') }
53
- let(:mock_expertise_class) { double('ApolloExpertise') }
54
- let(:entries) do
55
- [
56
- double('e1', source_agent: 'agent-1', tags: ['ruby'], confidence: 0.8),
57
- double('e2', source_agent: 'agent-1', tags: ['ruby'], confidence: 0.6),
58
- double('e3', source_agent: 'agent-2', tags: ['python'], confidence: 0.9)
59
- ]
60
- end
61
-
62
- before do
63
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
64
- stub_const('Legion::Data::Model::ApolloExpertise', mock_expertise_class)
65
- allow(mock_entry_class).to receive(:select).and_return(double(exclude: double(all: entries)))
66
- allow(mock_expertise_class).to receive(:where).and_return(double(first: nil))
67
- allow(mock_expertise_class).to receive(:create)
68
- end
69
-
70
- it 'returns agent and domain counts' do
71
- result = host.aggregate
72
- expect(result[:success]).to be true
73
- expect(result[:agents]).to eq(2)
74
- expect(result[:domains]).to eq(2)
75
- end
76
-
77
- it 'creates expertise records' do
78
- expect(mock_expertise_class).to receive(:create).twice
79
- host.aggregate
80
- end
81
-
82
- it 'computes proficiency using log2 formula' do
83
- # agent-1 ruby: avg=0.7, count=2, proficiency = 0.7 * log2(3) = 0.7 * 1.585 = 1.109 -> capped at 1.0
84
- expect(mock_expertise_class).to receive(:create).with(
85
- hash_including(agent_id: 'agent-1', domain: 'ruby', proficiency: 1.0)
86
- )
87
- # agent-2 python: avg=0.9, count=1, proficiency = 0.9 * log2(2) = 0.9 * 1.0 = 0.9
88
- expect(mock_expertise_class).to receive(:create).with(
89
- hash_including(agent_id: 'agent-2', domain: 'python', proficiency: 0.9)
90
- )
91
- host.aggregate
92
- end
82
+ it 'groups by agent and domain without collapsing domain collisions' do
83
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'ruby', confidence: 0.8)
84
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'ruby', confidence: 0.6)
85
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'python', confidence: 0.9)
86
+ entry_model.create(source_agent: 'agent-2', knowledge_domain: 'ruby', confidence: 0.7)
87
+
88
+ result = runner.aggregate
89
+
90
+ expect(result).to include(success: true, agents: 2, domains: 2)
91
+ rows = expertise_model.order(:agent_id, :domain).all.map { |row| [row.agent_id, row.domain, row.entry_count] }
92
+ expect(rows).to eq([['agent-1', 'python', 1], ['agent-1', 'ruby', 2], ['agent-2', 'ruby', 1]])
93
+ expect(expertise_model.where(agent_id: 'agent-1', domain: 'ruby').count).to eq(1)
93
94
  end
94
95
 
95
- context 'when no entries exist' do
96
- let(:mock_entry_class) { double('ApolloEntry') }
96
+ it 'derives a missing domain from the first serialized tag' do
97
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: nil, tags: '["vault"]', confidence: 0.8)
97
98
 
98
- before do
99
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
100
- allow(mock_entry_class).to receive(:select).and_return(double(exclude: double(all: [])))
101
- end
99
+ expect(runner.aggregate).to include(success: true, agents: 1, domains: 1)
100
+ expect(expertise_model.first.values).to include(agent_id: 'agent-1', domain: 'vault', entry_count: 1)
101
+ end
102
102
 
103
- it 'returns zero counts' do
104
- result = host.aggregate
105
- expect(result[:success]).to be true
106
- expect(result[:agents]).to eq(0)
107
- expect(result[:domains]).to eq(0)
108
- end
103
+ it 'returns zero counts for an empty canonical entry table' do
104
+ expect(runner.aggregate).to include(success: true, agents: 0, domains: 0)
109
105
  end
110
106
  end
111
107
  end
@@ -3,96 +3,19 @@
3
3
  require 'spec_helper'
4
4
  require 'legion/extensions/apollo/runners/gas'
5
5
 
6
- RSpec.describe Legion::Extensions::Apollo::Runners::Gas, '.phase_anticipate' do
7
- let(:facts) do
8
- [
9
- { content: 'pgvector uses HNSW indexes', content_type: :fact },
10
- { content: 'cosine distance measures similarity', content_type: :concept }
11
- ]
12
- end
13
-
14
- let(:synthesis) do
15
- [
16
- { content: 'pgvector achieves fast search via HNSW', content_type: :inference, status: :candidate }
17
- ]
18
- end
19
-
20
- context 'when GaiaCaller is unavailable' do
21
- it 'returns empty array' do
22
- result = described_class.phase_anticipate(facts, synthesis)
23
- expect(result).to eq([])
24
- end
25
- end
26
-
27
- context 'when GaiaCaller is available' do
28
- let(:gaia_caller) { double('GaiaCaller') }
29
- let(:mock_response) do
30
- double(
31
- 'Response',
32
- message: {
33
- content: '{"questions":["How fast is pgvector HNSW search?","What distance metrics does pgvector support?"]}'
34
- }
35
- )
36
- end
37
-
38
- before do
39
- stub_const('Legion::LLM::Pipeline::GaiaCaller', gaia_caller)
40
- allow(gaia_caller).to receive(:structured).and_return(mock_response)
41
- end
42
-
43
- it 'generates anticipated questions' do
44
- result = described_class.phase_anticipate(facts, synthesis)
45
- expect(result).not_to be_empty
46
- expect(result.length).to be <= 3
47
- end
48
-
49
- it 'returns question strings' do
50
- result = described_class.phase_anticipate(facts, synthesis)
51
- result.each do |item|
52
- expect(item[:question]).to be_a(String)
53
- end
54
- end
55
-
56
- context 'when PatternStore is available' do
57
- let(:pattern_store) { double('PatternStore') }
58
-
59
- before do
60
- stub_const('Legion::Extensions::Agentic::TBI::PatternStore', pattern_store)
61
- allow(pattern_store).to receive(:promote_candidate)
62
- end
63
-
64
- it 'promotes candidates to PatternStore' do
65
- described_class.phase_anticipate(facts, synthesis)
66
- expect(pattern_store).to have_received(:promote_candidate).at_least(:once)
67
- end
68
- end
69
-
70
- context 'when PatternStore is not available' do
71
- it 'still returns questions without error' do
72
- result = described_class.phase_anticipate(facts, synthesis)
73
- expect(result).not_to be_empty
74
- end
75
- end
76
- end
77
-
78
- context 'when LLM call fails' do
79
- let(:gaia_caller) { double('GaiaCaller') }
80
-
81
- before do
82
- stub_const('Legion::LLM::Pipeline::GaiaCaller', gaia_caller)
83
- allow(gaia_caller).to receive(:structured).and_raise(StandardError, 'timeout')
84
- end
85
-
86
- it 'returns empty array on error' do
87
- result = described_class.phase_anticipate(facts, synthesis)
88
- expect(result).to eq([])
89
- end
90
- end
91
-
92
- context 'with empty facts' do
93
- it 'returns empty array' do
94
- result = described_class.phase_anticipate([], [])
95
- expect(result).to eq([])
96
- end
6
+ RSpec.describe Legion::Extensions::Apollo::Runners::Gas, 'anticipation phase' do
7
+ it 'does not promote private audit content when the LLM is unavailable' do
8
+ allow(Legion::LLM).to receive(:started?).and_return(false)
9
+ allow(described_class).to receive(:settings).and_return(
10
+ Legion::Extensions::Apollo.default_settings.merge(gas: Legion::Extensions::Apollo.default_settings[:gas].merge(enabled: true))
11
+ )
12
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
13
+
14
+ result = described_class.process(
15
+ request_id: 'req-anticipate', messages: [{ content: 'question' }], response_content: 'observation',
16
+ access_scope: 'private', identity_principal_id: 42, content_sanitized: true
17
+ )
18
+
19
+ expect(result).to include(success: true, phases_completed: 0, reason: 'llm_unavailable')
97
20
  end
98
21
  end
@@ -18,13 +18,24 @@ RSpec.describe 'Apollo GAS relation persistence' do
18
18
  db.create_table(:apollo_entries) do
19
19
  primary_key :id
20
20
  String :content
21
- String :content_hash, unique: true
21
+ String :content_hash
22
22
  String :content_type
23
23
  String :status
24
24
  String :access_scope
25
25
  Integer :identity_principal_id
26
26
  Float :confidence
27
+ String :embedding
28
+ String :embedding_space_id
29
+ Integer :embedding_dimensions
30
+ String :embedding_provenance
31
+ DateTime :updated_at
27
32
  end
33
+ db.run <<~SQL
34
+ CREATE UNIQUE INDEX idx_apollo_content_hash_owner ON apollo_entries (
35
+ content_hash, access_scope,
36
+ (CASE WHEN access_scope = 'global' THEN 0 ELSE COALESCE(identity_principal_id, 0) END)
37
+ ) WHERE status != 'archived' AND content_hash IS NOT NULL
38
+ SQL
28
39
  db.create_table(:apollo_relations) do
29
40
  primary_key :id
30
41
  foreign_key :from_entry_id, :apollo_entries, null: false
@@ -44,31 +55,37 @@ RSpec.describe 'Apollo GAS relation persistence' do
44
55
  end
45
56
  input = ::JSON.parse($stdin.read, symbolize_names: true)
46
57
  input[:entries].each do |entry|
47
- db[:apollo_entries].insert(entry.merge(content_hash: Legion::Extensions::Apollo::Helpers::Writeback.content_hash(entry[:content])))
58
+ embedding = ApolloSpecEmbedding.result
59
+ db[:apollo_entries].insert(entry.merge(
60
+ content_hash: Legion::Extensions::Apollo::Helpers::Writeback.content_hash(content: entry[:content]),
61
+ embedding: ::JSON.generate(embedding[:vector]), embedding_dimensions: embedding[:dimensions],
62
+ embedding_space_id: embedding[:embedding_provenance][:space_id],
63
+ embedding_provenance: ::JSON.generate(embedding[:embedding_provenance])
64
+ ))
48
65
  end
49
- knowledge = Legion::Extensions::Apollo::Runners::Knowledge
50
- knowledge.extend(knowledge)
51
- result = Legion::Extensions::Apollo::Runners::Gas.phase_deposit(
52
- input[:facts], [], input[:relations], [], { request_id: 'gas-regression' }
66
+ result = Legion::Extensions::Apollo::Runners::Gas.send(
67
+ :gas_phase_deposit, facts: input[:facts], relations: input[:relations], synthesis: [],
68
+ audit_event: { request_id: 'gas-regression', identity_principal_id: 42 }
53
69
  )
54
70
  puts "APOLLO_RESULT=#{::JSON.generate(result: result, relations: db[:apollo_relations].all)}"
55
71
  RUBY
56
72
  end
57
73
 
58
- def gas_deposit_state(entries:, facts:, relations:)
74
+ def gas_deposit_state(entries:, facts:, relations:, **)
59
75
  stdout, stderr, status = Open3.capture3(
60
76
  RbConfig.ruby, '-Ilib', '-Ispec', '-e', deposit_script,
61
77
  chdir: File.expand_path('../../../../..', __dir__),
62
78
  stdin_data: JSON.generate(entries: entries, facts: facts, relations: relations)
63
79
  )
64
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
65
- raise "GAS deposit process failed: #{stderr}\n#{stdout}" unless status.success? && line
80
+ marker = 'APOLLO_RESULT='
81
+ raise "GAS deposit process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
66
82
 
67
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
83
+ ApolloSpecOutput.parse(stdout)
68
84
  end
69
85
 
70
86
  it 'links successful deduplicated facts safely and continues after an independent relation write fails' do
71
- entry = { content_type: 'fact', status: 'candidate', access_scope: 'global', confidence: 0.5 }
87
+ entry = { content_type: 'fact', status: 'candidate', access_scope: 'private', identity_principal_id: 42,
88
+ confidence: 0.5 }
72
89
  entries = [entry.merge(id: 1, content: 'stored fact'), entry.merge(id: 2, content: 'target evidence'),
73
90
  entry.merge(id: 3, content: 'private evidence', access_scope: 'private', identity_principal_id: 99),
74
91
  entry.merge(id: 4, content: 'second fact')]