lex-apollo 0.4.30 → 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.
Files changed (92) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +125 -0
  3. data/README.md +113 -18
  4. data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -38
  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 +5 -19
  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 +116 -51
  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 -63
  18. data/lib/legion/extensions/apollo/helpers/confidence.rb +9 -53
  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 +107 -67
  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 +67 -109
  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 +110 -0
  30. data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
  31. data/lib/legion/extensions/apollo/runners/gas.rb +165 -144
  32. data/lib/legion/extensions/apollo/runners/knowledge.rb +349 -371
  33. data/lib/legion/extensions/apollo/runners/maintenance.rb +242 -56
  34. data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
  35. data/lib/legion/extensions/apollo/runners/request.rb +51 -47
  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 +20 -0
  43. data/lib/legion/extensions/apollo/version.rb +1 -1
  44. data/lib/legion/extensions/apollo.rb +26 -24
  45. data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
  46. data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
  47. data/spec/legion/extensions/apollo/api_spec.rb +250 -28
  48. data/spec/legion/extensions/apollo/contradiction_spec.rb +23 -54
  49. data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
  50. data/spec/legion/extensions/apollo/helpers/capability_spec.rb +26 -29
  51. data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
  52. data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
  53. data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +88 -80
  54. data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
  55. data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
  56. data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
  57. data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +98 -71
  58. data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +220 -0
  59. data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
  60. data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
  61. data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
  62. data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +124 -0
  63. data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
  64. data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
  65. data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +108 -0
  66. data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
  67. data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -83
  68. data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
  69. data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +246 -0
  70. data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
  71. data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +332 -683
  72. data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +174 -0
  73. data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +42 -160
  74. data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
  75. data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
  76. data/spec/legion/extensions/apollo/runners/request_spec.rb +146 -107
  77. data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
  78. data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
  79. data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
  80. data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
  81. data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
  82. data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
  83. data/spec/spec_helper.rb +13 -15
  84. metadata +71 -13
  85. data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
  86. data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
  87. data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
  88. data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
  89. data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +0 -49
  90. data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
  91. data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
  92. data/spec/legion/extensions/apollo/helpers/entity_watchdog_spec.rb +0 -64
@@ -9,19 +9,92 @@ require 'legion/extensions/apollo/helpers/writeback'
9
9
  require 'legion/extensions/apollo/runners/knowledge'
10
10
 
11
11
  RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
12
- let(:runner) do
13
- obj = Object.new
14
- obj.extend(described_class)
15
- obj
16
- end
12
+ let(:runner) { described_class }
17
13
 
18
14
  before do
19
- embeddings_mod = Module.new do
20
- def self.generate(*, **)
21
- { vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 }
22
- end
15
+ hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo)
16
+ allow(Legion::Data).to receive(:connection).and_return(nil)
17
+ hide_const('Legion::Identity::Process') if defined?(Legion::Identity::Process)
18
+ stub_const('Legion::LLM::Call::Embeddings', Module.new)
19
+ allow(Legion::LLM::Call::Embeddings).to receive(:generate) do |task: :document, **|
20
+ ApolloSpecEmbedding.result(task: task)
21
+ end
22
+ allow(Legion::Extensions::Apollo).to receive(:settings).and_return(Legion::Extensions::Apollo.default_settings)
23
+ allow(runner).to receive(:settings).and_return(Legion::Extensions::Apollo.settings)
24
+ end
25
+
26
+ shared_context 'persisted knowledge' do
27
+ let(:database) { Sequel.sqlite }
28
+ let(:entry_model) { Class.new(Sequel::Model(database[:apollo_entries])) }
29
+
30
+ before do
31
+ database.create_table(:apollo_entries) do
32
+ primary_key :id
33
+ String :content
34
+ String :content_type
35
+ String :content_hash
36
+ String :status
37
+ String :source_agent
38
+ String :source_provider
39
+ String :source_channel
40
+ String :source_context
41
+ String :tags
42
+ String :knowledge_domain
43
+ String :submitted_by
44
+ String :submitted_from
45
+ String :access_scope
46
+ Integer :identity_principal_id
47
+ Integer :identity_id
48
+ String :identity_canonical_name
49
+ String :embedding
50
+ String :embedding_provenance
51
+ String :embedding_space_id
52
+ Integer :embedding_dimensions
53
+ Float :confidence
54
+ Integer :access_count, default: 0
55
+ DateTime :created_at, default: Sequel::CURRENT_TIMESTAMP
56
+ DateTime :updated_at
57
+ end
58
+ database.create_table(:apollo_expertise) do
59
+ primary_key :id
60
+ String :agent_id
61
+ String :domain
62
+ Float :proficiency
63
+ Integer :entry_count
64
+ DateTime :last_active_at
65
+ end
66
+ database.create_table(:apollo_access_logs) do
67
+ primary_key :id
68
+ Integer :entry_id
69
+ String :agent_id
70
+ String :action
71
+ end
72
+ database.create_table(:identities) do
73
+ primary_key :id
74
+ Integer :principal_id
75
+ end
76
+ database.create_table(:identity_group_memberships) do
77
+ Integer :principal_id
78
+ Integer :group_id
79
+ end
80
+ stub_const('Legion::Data::Model::Apollo::Entry', entry_model)
81
+ stub_const('Legion::Data::Model::Apollo::Expertise', Class.new(Sequel::Model(database[:apollo_expertise])))
82
+ stub_const('Legion::Data::Model::Apollo::AccessLog', Class.new(Sequel::Model(database[:apollo_access_logs])))
83
+ end
84
+
85
+ after { database.disconnect }
86
+
87
+ def persisted_entry(content: 'Ruby is interpreted', **attributes)
88
+ embedding = ApolloSpecEmbedding.result
89
+ entry_model.create(
90
+ { content: content, content_type: 'fact', content_hash: Digest::SHA256.hexdigest(content),
91
+ status: 'confirmed', source_agent: 'worker', tags: Legion::JSON.dump(['ruby']),
92
+ knowledge_domain: 'general', access_scope: 'global', confidence: 0.8,
93
+ embedding: Legion::JSON.dump(embedding[:vector]),
94
+ embedding_provenance: Legion::JSON.dump(embedding[:embedding_provenance]),
95
+ embedding_space_id: embedding[:embedding_provenance][:space_id], embedding_dimensions: 2 }.merge(attributes)
96
+ )
23
97
  end
24
- stub_const('Legion::LLM::Call::Embeddings', embeddings_mod)
25
98
  end
26
99
 
27
100
  describe '#store_knowledge' do
@@ -88,8 +161,6 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
88
161
  result = runner.query_knowledge(query: 'PKI configuration')
89
162
  expect(result[:action]).to eq(:query)
90
163
  expect(result[:query]).to eq('PKI configuration')
91
- expect(result[:limit]).to eq(10)
92
- expect(result[:min_confidence]).to eq(0.3)
93
164
  end
94
165
 
95
166
  it 'accepts custom limit and filters' do
@@ -109,7 +180,6 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
109
180
  result = runner.related_entries(entry_id: 'uuid-123')
110
181
  expect(result[:action]).to eq(:traverse)
111
182
  expect(result[:entry_id]).to eq('uuid-123')
112
- expect(result[:depth]).to eq(2)
113
183
  end
114
184
 
115
185
  it 'accepts relation_types filter' do
@@ -122,19 +192,18 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
122
192
  end
123
193
 
124
194
  describe '#deprecate_entry' do
125
- it 'returns a deprecate payload' do
195
+ it 'retains the client action envelope without claiming a completed service mutation' do
126
196
  result = runner.deprecate_entry(entry_id: 'uuid-123', reason: 'outdated')
127
197
  expect(result[:action]).to eq(:deprecate)
128
- expect(result[:entry_id]).to eq('uuid-123')
129
- expect(result[:reason]).to eq('outdated')
198
+ expect(result).not_to have_key(:success)
130
199
  end
131
200
  end
132
201
 
133
202
  describe '#handle_ingest' do
134
- let(:host) { Object.new.extend(described_class) }
203
+ let(:host) { runner }
135
204
 
136
205
  context 'when Apollo data is not available' do
137
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
206
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
138
207
 
139
208
  it 'returns a structured error' do
140
209
  result = host.handle_ingest(content: 'test', content_type: 'fact')
@@ -144,216 +213,123 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
144
213
  end
145
214
 
146
215
  context 'when Apollo data is available' do
147
- let(:mock_entry_class) { double('ApolloEntry') }
148
- let(:mock_relation_class) { double('ApolloRelation') }
149
- let(:mock_expertise_class) { double('ApolloExpertise') }
150
- let(:mock_access_log_class) { double('ApolloAccessLog') }
151
- let(:mock_entry) { double('entry', id: 'uuid-123', embedding: nil) }
152
- let(:empty_dataset) { double('dataset', each: nil) }
216
+ include_context 'persisted knowledge'
153
217
 
154
- let(:mock_db) { double('db') }
218
+ it 'persists a novel candidate that can be retrieved in the generated embedding space' do
219
+ result = host.handle_ingest(content: 'Ruby is great', content_type: 'fact',
220
+ tags: ['Ruby'], source_agent: 'agent-1')
155
221
 
156
- before do
157
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
158
- stub_const('Legion::Data::Model::ApolloRelation', mock_relation_class)
159
- stub_const('Legion::Data::Model::ApolloExpertise', mock_expertise_class)
160
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class)
161
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
162
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
163
-
164
- # Corroboration lookup chain
165
- allow(mock_entry_class).to receive(:where).and_return(double(exclude: double(limit: empty_dataset)))
166
- # Content hash dedup chain — no match by default
167
- dedup_chain = double('dedup_chain')
168
- allow(mock_entry_class).to receive(:where).with(content_hash: anything).and_return(dedup_chain)
169
- allow(dedup_chain).to receive(:exclude).with(status: 'archived').and_return(double(first: nil))
170
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
171
- allow(mock_db).to receive(:fetch).and_return(double(all: []))
172
- allow(mock_entry_class).to receive(:create).and_return(mock_entry)
173
- allow(mock_expertise_class).to receive(:where).and_return(double(first: nil))
174
- allow(mock_expertise_class).to receive(:create)
175
- allow(mock_access_log_class).to receive(:create)
222
+ expect(result).to include(success: true, status: 'candidate', corroborated: false)
223
+ retrieved = host.retrieve_relevant(query: 'Ruby', min_confidence: 0.0)
224
+ expect(retrieved).to include(success: true, entries: [include(id: result[:entry_id], content: 'Ruby is great', tags: ['ruby'])])
225
+ expect(database[:apollo_access_logs].all).to contain_exactly(
226
+ include(entry_id: result[:entry_id], agent_id: 'agent-1', action: 'ingest')
227
+ )
176
228
  end
177
229
 
178
- it 'creates a new candidate entry when novel' do
179
- result = host.handle_ingest(content: 'Ruby is great', content_type: 'fact',
180
- tags: ['ruby'], source_agent: 'agent-1')
181
- expect(result[:success]).to be true
182
- expect(result[:status]).to eq('candidate')
183
- expect(result[:corroborated]).to be false
184
- end
230
+ it 'sanitizes null bytes and invalid UTF-8 before content becomes queryable' do
231
+ content = "hello\x00\xC3(world".dup.force_encoding(Encoding::UTF_8)
232
+ result = host.handle_ingest(content: content, content_type: 'fact')
185
233
 
186
- it 'defaults content_type to :observation when nil' do
187
- expect(mock_entry_class).to receive(:create).with(
188
- hash_including(content_type: 'observation')
189
- ).and_return(mock_entry)
190
- result = host.handle_ingest(content: 'gaia tick result', content_type: nil,
191
- source_agent: 'gaia')
192
234
  expect(result[:success]).to be true
235
+ expect(host.handle_query(query: '', min_confidence: 0.0)[:entries]).to contain_exactly(include(content: 'hello(world'))
193
236
  end
194
237
 
195
- it 'creates expertise record for source agent' do
196
- expect(mock_expertise_class).to receive(:create).with(
197
- hash_including(agent_id: 'agent-1', domain: 'ruby')
198
- )
199
- host.handle_ingest(content: 'Ruby is great', content_type: 'fact',
200
- tags: ['ruby'], source_agent: 'agent-1')
201
- end
238
+ context 'content hash dedup' do
239
+ let!(:existing_entry) { persisted_entry(content: 'test', content_hash: 'same-hash') }
202
240
 
203
- it 'logs access' do
204
- expect(mock_access_log_class).to receive(:create).with(
205
- hash_including(agent_id: 'agent-1', action: 'ingest')
206
- )
207
- host.handle_ingest(content: 'Ruby is great', content_type: 'fact',
208
- tags: ['ruby'], source_agent: 'agent-1')
209
- end
241
+ it 'reuses a provenanced active entry without requiring an embedding provider' do
242
+ expect(Legion::LLM::Call::Embeddings).not_to receive(:generate)
210
243
 
211
- it 'defaults domain to general when no tags' do
212
- expect(mock_expertise_class).to receive(:create).with(
213
- hash_including(domain: 'general')
214
- )
215
- host.handle_ingest(content: 'test', content_type: 'fact', source_agent: 'agent-1')
216
- end
244
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash')
217
245
 
218
- it 'passes source_channel to create' do
219
- expect(mock_entry_class).to receive(:create).with(
220
- hash_including(source_channel: 'slack-alerts')
221
- ).and_return(mock_entry)
222
- host.handle_ingest(content: 'test', content_type: 'fact',
223
- source_agent: 'agent-1', source_channel: 'slack-alerts')
224
- end
246
+ expect(result).to include(success: true, deduped: true, entry_id: existing_entry.id)
247
+ expect(entry_model.count).to eq(1)
248
+ expect(existing_entry.refresh.confidence).to be > 0.8
249
+ end
225
250
 
226
- it 'passes knowledge_domain to create from explicit param' do
227
- expect(mock_entry_class).to receive(:create).with(
228
- hash_including(knowledge_domain: 'clinical')
229
- ).and_return(mock_entry)
230
- host.handle_ingest(content: 'test', content_type: 'fact',
231
- source_agent: 'agent-1', knowledge_domain: 'clinical')
232
- end
251
+ it 'regenerates legacy embeddings before reporting a duplicate as reusable' do
252
+ existing_entry.update(embedding_provenance: nil, embedding_space_id: nil, embedding_dimensions: nil)
233
253
 
234
- it 'defaults knowledge_domain to first tag' do
235
- expect(mock_entry_class).to receive(:create).with(
236
- hash_including(knowledge_domain: 'cardiology')
237
- ).and_return(mock_entry)
238
- host.handle_ingest(content: 'test', content_type: 'fact',
239
- tags: %w[cardiology treatment], source_agent: 'agent-1')
240
- end
254
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash')
241
255
 
242
- it 'defaults knowledge_domain to general when no tags and no explicit domain' do
243
- expect(mock_entry_class).to receive(:create).with(
244
- hash_including(knowledge_domain: 'general')
245
- ).and_return(mock_entry)
246
- host.handle_ingest(content: 'test', content_type: 'fact', source_agent: 'agent-1')
247
- end
256
+ expect(result).to include(success: true, deduped: true, entry_id: existing_entry.id)
257
+ expect(host.retrieve_relevant(query: 'test')[:entries]).to contain_exactly(include(id: existing_entry.id))
258
+ expect(entry_model.count).to eq(1)
259
+ end
248
260
 
249
- it 'passes submitted_by and submitted_from to create' do
250
- expect(mock_entry_class).to receive(:create).with(
251
- hash_including(submitted_by: 'user@example.com', submitted_from: 'node-1')
252
- ).and_return(mock_entry)
253
- host.handle_ingest(content: 'test', content_type: 'fact',
254
- source_agent: 'agent-1',
255
- submitted_by: 'user@example.com',
256
- submitted_from: 'node-1')
257
- end
261
+ it 'does not report dedup success or boost confidence when legacy regeneration fails' do
262
+ existing_entry.update(embedding_provenance: nil, embedding_space_id: nil)
263
+ allow(Legion::LLM::Call::Embeddings).to receive(:generate).and_raise(Legion::LLM::LLMError, 'provider unavailable')
258
264
 
259
- it 'passes content_hash to create' do
260
- expect(mock_entry_class).to receive(:create).with(
261
- hash_including(content_hash: 'abc123')
262
- ).and_return(mock_entry)
263
- host.handle_ingest(content: 'test', content_type: 'fact',
264
- source_agent: 'agent-1', content_hash: 'abc123')
265
- end
265
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash')
266
266
 
267
- it 'normalizes tags before storage' do
268
- expect(mock_entry_class).to receive(:create).with(
269
- hash_including(tags: Sequel.pg_array(%w[rabbitmq]))
270
- ).and_return(mock_entry)
271
- host.handle_ingest(content: 'test', content_type: 'fact',
272
- tags: ['RabbitMQ'], source_agent: 'agent-1')
273
- end
267
+ expect(result).to include(success: false, error: include('provider unavailable'))
268
+ expect(existing_entry.refresh.confidence).to eq(0.8)
269
+ expect(existing_entry.embedding_provenance).to be_nil
270
+ end
274
271
 
275
- it 'sanitizes null bytes before storing content' do
276
- expect(mock_entry_class).to receive(:create).with(
277
- hash_including(content: 'helloworld')
278
- ).and_return(mock_entry)
279
- host.handle_ingest(content: "hello\x00world", content_type: 'fact', source_agent: 'agent-1')
280
- end
272
+ it 'does not reuse another principal or scope with the same hash' do
273
+ existing_entry.update(access_scope: 'private', identity_principal_id: 7)
281
274
 
282
- it 'truncates short varchar metadata fields at the database boundary' do
283
- expect(mock_entry_class).to receive(:create).with(
284
- hash_including(
285
- source_agent: 'a' * 50,
286
- source_provider: 'p' * 50,
287
- source_channel: 'c' * 100,
288
- knowledge_domain: 'd' * 50,
289
- submitted_by: 'u' * 255,
290
- submitted_from: 'n' * 255
291
- )
292
- ).and_return(mock_entry)
293
- host.handle_ingest(
294
- content: 'test',
295
- content_type: 'fact',
296
- source_agent: 'a' * 60,
297
- source_provider: 'p' * 60,
298
- source_channel: 'c' * 120,
299
- knowledge_domain: 'd' * 60,
300
- submitted_by: 'u' * 300,
301
- submitted_from: 'n' * 300
302
- )
303
- end
275
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash',
276
+ access_scope: 'private', identity_principal_id: 8)
304
277
 
305
- context 'content hash dedup' do
306
- let(:existing_entry) do
307
- double('existing', id: 'uuid-existing', confidence: 0.6,
308
- update: true)
278
+ expect(result).to include(success: true, corroborated: false)
279
+ expect(result[:entry_id]).not_to eq(existing_entry.id)
280
+ expect(host.retrieve_relevant(query: 'test', min_confidence: 0.0,
281
+ requesting_principal_id: 8)[:entries]).to contain_exactly(include(id: result[:entry_id]))
309
282
  end
310
283
 
311
- it 'returns deduped result on hash collision with active entry' do
312
- dedup_dataset = double('dataset')
313
- allow(mock_entry_class).to receive(:where).with(content_hash: anything).and_return(dedup_dataset)
314
- allow(dedup_dataset).to receive(:exclude).with(status: 'archived').and_return(dedup_dataset)
315
- allow(dedup_dataset).to receive(:first).and_return(existing_entry)
316
-
317
- result = host.handle_ingest(content: 'test', content_type: 'fact',
318
- source_agent: 'agent-1',
319
- content_hash: 'deadbeef12345678deadbeef12345678')
320
- expect(result[:success]).to be true
321
- expect(result[:deduped]).to be true
322
- expect(result[:entry_id]).to eq('uuid-existing')
284
+ it 'does not deduplicate against an archived entry' do
285
+ existing_entry.update(status: 'archived')
286
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash')
287
+
288
+ expect(result).to include(success: true, status: 'candidate')
289
+ expect(result[:entry_id]).not_to eq(existing_entry.id)
290
+ end
291
+
292
+ it 'returns the concurrent winner after an insert uniqueness conflict' do
293
+ winner_values = existing_entry.values.except(:id)
294
+ existing_entry.destroy
295
+ winner_id = nil
296
+ allow(entry_model).to receive(:create).and_raise(Sequel::UniqueConstraintViolation, 'duplicate hash')
297
+ # Make the competing row visible after the pre-check but before the insert savepoint.
298
+ allow(database).to receive(:transaction).and_wrap_original do |original, **options, &block|
299
+ winner_id = database[:apollo_entries].insert(winner_values) if options[:savepoint]
300
+ original.call(**options, &block)
301
+ end
302
+
303
+ result = host.handle_ingest(content: 'test', content_hash: 'same-hash')
304
+
305
+ expect(result).to include(success: true, entry_id: winner_id)
323
306
  end
324
307
 
325
- it 'recovers gracefully when a concurrent ingest wins the content_hash unique constraint race' do
326
- # Simulate: dedup check passes (nil — no existing entry yet), then .create
327
- # raises UniqueConstraintViolation (another thread inserted between check and insert).
328
- # create_candidate_entry must rescue and return the existing entry's id so the
329
- # caller succeeds rather than propagating a database error.
330
- race_entry = double('race_entry', id: 'uuid-race-winner')
331
-
332
- allow(mock_entry_class).to receive(:create)
333
- .and_raise(Sequel::UniqueConstraintViolation, 'duplicate key value violates unique constraint "idx_apollo_content_hash"')
334
-
335
- collision_dataset = double('collision_dataset')
336
- allow(mock_entry_class).to receive(:where).with(content_hash: anything).and_return(collision_dataset)
337
- allow(collision_dataset).to receive(:exclude).with(status: 'archived').and_return(collision_dataset)
338
- # First call: dedup pre-check returns nil (not yet in DB).
339
- # Second call: post-collision lookup returns the winner inserted by the other thread.
340
- allow(collision_dataset).to receive(:first).and_return(nil, race_entry)
341
-
342
- result = host.handle_ingest(content: 'concurrent content', content_type: 'fact',
343
- source_agent: 'agent-1',
344
- content_hash: 'd3861b2862454c5a6a9e480829333841')
345
- expect(result[:success]).to be true
346
- expect(result[:entry_id]).to eq('uuid-race-winner')
308
+ it 'returns failure when a uniqueness conflict has no visible winner' do
309
+ existing_entry.destroy
310
+ allow(entry_model).to receive(:create).and_raise(Sequel::UniqueConstraintViolation, 'duplicate hash')
311
+
312
+ expect(host.handle_ingest(content: 'test', content_hash: 'same-hash')).to include(
313
+ success: false, error: 'duplicate hash'
314
+ )
315
+ expect(entry_model.count).to eq(0)
347
316
  end
348
317
  end
318
+
319
+ it 'rejects private writes without an explicit usable owner' do
320
+ result = host.handle_ingest(content: 'private fact', access_scope: 'private', identity_principal_id: nil)
321
+
322
+ expect(result).to include(success: false, error: 'identity_required')
323
+ expect(entry_model.count).to eq(0)
324
+ end
349
325
  end
350
326
 
351
327
  context 'when Sequel raises an error' do
352
328
  before do
353
- stub_const('Legion::Data::Model::ApolloEntry', Class.new)
354
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
355
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
356
- allow(Legion::Data::Model::ApolloEntry).to receive(:where)
329
+ stub_const('Legion::Data::Model::Apollo::Entry', Class.new)
330
+ stub_const('Legion::Data::Model::Apollo::Expertise', Class.new)
331
+ stub_const('Legion::Data::Model::Apollo::AccessLog', Class.new)
332
+ allow(Legion::Data::Model::Apollo::Entry).to receive(:where)
357
333
  .and_raise(Sequel::Error, 'connection lost')
358
334
  end
359
335
 
@@ -363,224 +339,62 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
363
339
  result = host.handle_ingest(content: 'test', content_type: 'fact', source_agent: 'a')
364
340
  expect(result[:success]).to be false
365
341
  expect(result[:error]).to eq('connection lost')
366
- expect(host).to have_received(:handle_exception).with(
367
- instance_of(Sequel::Error),
368
- level: :error,
369
- operation: 'apollo.knowledge.handle_ingest'
370
- )
371
342
  end
372
343
  end
373
344
 
374
- context 'identity from Legion::Identity::Process' do
375
- let(:mock_entry_class2) { double('ApolloEntry2') }
376
- let(:mock_expertise_class2) { double('ApolloExpertise2') }
377
- let(:mock_access_log_class2) { double('ApolloAccessLog2') }
378
- let(:mock_entry2) { double('entry2', id: 99, embedding: nil) }
379
-
380
- before do
381
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class2)
382
- stub_const('Legion::Data::Model::ApolloExpertise', mock_expertise_class2)
383
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class2)
384
- scoped_ds = double('scoped_ds2', first: nil, where: double('scoped_ds2b', first: nil))
385
- allow(mock_entry_class2).to receive(:where).and_return(scoped_ds)
386
- allow(scoped_ds).to receive(:exclude).and_return(scoped_ds)
387
- allow(mock_expertise_class2).to receive(:where).and_return(double(first: nil))
388
- allow(mock_expertise_class2).to receive(:create)
389
- allow(mock_access_log_class2).to receive(:create)
390
- allow(host).to receive(:embed_text).and_return(nil)
391
- allow(host).to receive(:find_corroboration).and_return([false, nil])
392
- allow(host).to receive(:detect_contradictions).and_return([])
393
- stub_const('Legion::Identity::Process', double(
394
- db_principal_id: 42,
395
- db_identity_id: 7,
396
- canonical_name: 'alice'
397
- ))
398
- end
399
-
400
- it 'derives identity from Legion::Identity::Process and persists it' do
401
- expect(mock_entry_class2).to receive(:create).with(
402
- hash_including(identity_principal_id: 42, identity_id: 7, identity_canonical_name: 'alice',
403
- access_scope: 'private')
404
- ).and_return(mock_entry2)
405
-
406
- host.handle_ingest(content: 'test fact', tags: [], access_scope: 'private')
407
- end
408
-
409
- it 'defaults access_scope to global when not provided' do
410
- expect(mock_entry_class2).to receive(:create).with(
411
- hash_including(access_scope: 'global')
412
- ).and_return(mock_entry2)
413
-
414
- host.handle_ingest(content: 'test fact', tags: [])
415
- end
416
-
417
- it 'ignores identity kwargs passed by callers' do
418
- expect(mock_entry_class2).to receive(:create).with(
419
- hash_including(identity_principal_id: 42, identity_id: 7, identity_canonical_name: 'alice')
420
- ).and_return(mock_entry2)
421
-
422
- host.handle_ingest(
423
- content: 'test fact', tags: [],
424
- identity_principal_id: 999, identity_id: 888, identity_canonical_name: 'mallory',
425
- access_scope: 'private'
426
- )
427
- end
428
- end
429
-
430
- context 'dedup: private entries from different principals are not deduplicated' do
431
- let(:mock_entry_class3) { double('ApolloEntry3') }
432
- let(:mock_expertise_class3) { double('ApolloExpertise3') }
433
- let(:mock_access_log_class3) { double('ApolloAccessLog3') }
434
- let(:mock_entry_a) { double('entry_a', id: 7, embedding: nil) }
435
- let(:mock_entry_b) { double('entry_b', id: 8, embedding: nil) }
436
-
437
- before do
438
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class3)
439
- stub_const('Legion::Data::Model::ApolloExpertise', mock_expertise_class3)
440
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class3)
441
- allow(mock_expertise_class3).to receive(:where).and_return(double(first: nil))
442
- allow(mock_expertise_class3).to receive(:create)
443
- allow(mock_access_log_class3).to receive(:create)
444
- allow(host).to receive(:embed_text).and_return(nil)
445
- allow(host).to receive(:find_corroboration).and_return([false, nil])
446
- allow(host).to receive(:detect_contradictions).and_return([])
447
- # default dedup returns nil (no duplicate) — supports chained .where for private scope
448
- scoped_ds3 = double('dedup_chain3', first: nil)
449
- allow(scoped_ds3).to receive(:where).and_return(double('scoped_ds3b', first: nil))
450
- allow(scoped_ds3).to receive(:exclude).and_return(scoped_ds3)
451
- allow(mock_entry_class3).to receive(:where).and_return(scoped_ds3)
452
- # two different principals each get their own entry
453
- allow(mock_entry_class3).to receive(:create).and_return(mock_entry_a, mock_entry_b)
454
- end
455
-
456
- it 'does not deduplicate private entries from different principals' do
457
- result1 = host.handle_ingest(content: 'same fact', content_type: :observation,
458
- access_scope: 'private', identity_principal_id: 1)
459
- result2 = host.handle_ingest(content: 'same fact', content_type: :observation,
460
- access_scope: 'private', identity_principal_id: 2)
461
- expect(result1[:entry_id]).not_to eq(result2[:entry_id])
462
- end
463
- end
464
-
465
- context 'early-return warn logs' do
466
- let(:logger) { instance_double('Logger', debug: nil, info: nil, warn: nil) }
467
-
468
- before { allow(host).to receive(:log).and_return(logger) }
469
-
470
- it 'emits a warn log when content is nil' do
471
- host.handle_ingest(content: nil, content_type: 'fact')
472
- expect(logger).to have_received(:warn).with(/early-return: content is required/)
345
+ context 'invalid content' do
346
+ it 'returns an actionable failure for missing content' do
347
+ expect(host.handle_ingest(content: nil)).to include(success: false, error: 'content is required')
473
348
  end
474
349
 
475
- it 'does not emit a content_type warn when content_type is nil (defaults to :observation)' do
476
- hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry)
477
- host.handle_ingest(content: 'something', content_type: nil)
478
- expect(logger).not_to have_received(:warn).with(/content_type is required/)
479
- end
350
+ it 'does not allow newline-bearing tags to forge warning log lines' do
351
+ logger = double('logger', debug: nil, warn: nil)
352
+ allow(host).to receive(:log).and_return(logger)
480
353
 
481
- it 'emits a warn log when apollo_data_not_available' do
482
- hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry)
483
- host.handle_ingest(content: 'something', content_type: 'fact')
484
- expect(logger).to have_received(:warn).with(/early-return: apollo_data_not_available/)
485
- end
354
+ host.handle_ingest(content: nil, tags: ["evil\nFAKE LOG LINE", 'normal'])
486
355
 
487
- it 'sanitizes newline-bearing tags in the warn log' do
488
- host.handle_ingest(content: nil, content_type: 'fact', tags: ["evil\nFAKE LOG LINE", 'normal'])
489
- expect(logger).to have_received(:warn) do |msg|
490
- expect(msg).to include('evil FAKE LOG LINE')
491
- expect(msg).not_to include("\n")
356
+ expect(logger).to have_received(:warn) do |message|
357
+ expect(message).to include('evil FAKE LOG LINE')
358
+ expect(message).not_to include("\n")
492
359
  end
493
360
  end
494
361
  end
495
362
 
496
- context 'contradiction detection flag' do
497
- let(:mock_entry_class) { double('ApolloEntry') }
498
- let(:mock_relation_class) { double('ApolloRelation') }
499
- let(:mock_expertise_class) { double('ApolloExpertise') }
500
- let(:mock_access_log_class) { double('ApolloAccessLog') }
501
- let(:mock_entry) { double('entry', id: 'uuid-new', embedding: nil) }
502
- let(:empty_dataset) { double('dataset', each: nil) }
503
- let(:mock_db) { double('db') }
504
-
505
- before do
506
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
507
- stub_const('Legion::Data::Model::ApolloRelation', mock_relation_class)
508
- stub_const('Legion::Data::Model::ApolloExpertise', mock_expertise_class)
509
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class)
510
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
511
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
512
- allow(mock_entry_class).to receive(:where).and_return(double(exclude: double(limit: empty_dataset)))
513
- dedup_chain = double('dedup_chain')
514
- allow(mock_entry_class).to receive(:where).with(content_hash: anything).and_return(dedup_chain)
515
- allow(dedup_chain).to receive(:exclude).with(status: 'archived').and_return(double(first: nil))
516
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
517
- allow(mock_db).to receive(:fetch).and_return(double(all: []))
518
- allow(mock_entry_class).to receive(:create).and_return(mock_entry)
519
- allow(mock_expertise_class).to receive(:where).and_return(double(first: nil))
520
- allow(mock_expertise_class).to receive(:create)
521
- allow(mock_access_log_class).to receive(:create)
522
- end
523
-
524
- it 'defaults contradiction detection to disabled' do
525
- expect(Legion::Extensions::Apollo.settings[:contradiction][:enabled]).to be false
526
- end
363
+ context 'contradiction detection' do
364
+ include_context 'persisted knowledge'
527
365
 
528
- it 'does not call detect_contradictions when flag is false' do
529
- expect(host).not_to receive(:detect_contradictions)
530
- result = host.handle_ingest(content: 'test fact', content_type: 'fact', source_agent: 'agent-1')
531
- expect(result[:success]).to be true
532
- expect(result[:contradictions]).to eq([])
366
+ around do |example|
367
+ scanner = Legion::Extensions::Apollo::Runners::Contradictions
368
+ previous_queue = scanner.instance_variable_get(:@contradictions_queue)
369
+ scanner.instance_variable_set(:@contradictions_queue, Queue.new)
370
+ example.run
371
+ ensure
372
+ scanner.instance_variable_set(:@contradictions_queue, previous_queue)
533
373
  end
534
374
 
535
- it 'returns stable contradictions key as empty array when disabled' do
536
- result = host.handle_ingest(content: 'test content', content_type: 'fact', source_agent: 'agent-1')
537
- expect(result).to have_key(:contradictions)
538
- expect(result[:contradictions]).to eq([])
375
+ it 'returns accepted ingestion without synchronous contradiction results when disabled' do
376
+ expect(host.handle_ingest(content: 'test fact')).to include(success: true, contradictions: [])
539
377
  end
540
378
 
541
- context 'when enabled' do
542
- before do
543
- Legion::Settings[:extensions][:apollo][:contradiction][:enabled] = true
544
- stub_const('Legion::Extensions::Apollo::Actor::ContradictionScanner',
545
- Class.new do
546
- @queue = Queue.new
547
- class << self
548
- attr_reader :queue
549
-
550
- def enqueue(entry_id:, embedding:, content:)
551
- queue.push({ entry_id: entry_id, embedding: embedding, content: content })
552
- end
553
-
554
- def pending_count = queue.size
555
-
556
- def drain
557
- items = []
558
- items << queue.pop until queue.empty?
559
- items
560
- end
561
- end
562
- end)
563
- end
564
-
565
- after do
566
- Legion::Settings[:extensions][:apollo][:contradiction][:enabled] = false
567
- end
379
+ it 'makes enabled ingestion available to the asynchronous contradiction scan' do
380
+ scanner = Legion::Extensions::Apollo::Runners::Contradictions
381
+ allow(scanner).to receive(:settings).and_return(Legion::Extensions::Apollo.settings)
382
+ Legion::Extensions::Apollo.settings[:contradiction][:enabled] = true
383
+ result = host.handle_ingest(content: 'enabled test')
568
384
 
569
- it 'enqueues contradiction work to the actor instead of running inline' do
570
- result = host.handle_ingest(content: 'enabled test', content_type: 'fact', source_agent: 'agent-1')
571
- expect(result[:success]).to be true
572
- expect(result[:contradictions]).to eq([])
573
- expect(Legion::Extensions::Apollo::Actor::ContradictionScanner.pending_count).to eq(1)
574
- end
385
+ expect(result).to include(success: true, contradictions: [])
386
+ expect(entry_model[result[:entry_id]].content).to eq('enabled test')
387
+ expect(scanner.scan_pending_contradictions).to include(success: true, processed: 1, failed: 0)
388
+ expect(scanner.scan_pending_contradictions).to include(success: true, processed: 0)
575
389
  end
576
390
  end
577
391
  end
578
392
 
579
393
  describe '#handle_query' do
580
- let(:host) { Object.new.extend(described_class) }
394
+ let(:host) { runner }
581
395
 
582
396
  context 'when Apollo data is not available' do
583
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
397
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
584
398
 
585
399
  it 'returns a structured error' do
586
400
  result = host.handle_query(query: 'test')
@@ -589,59 +403,39 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
589
403
  end
590
404
  end
591
405
 
592
- context 'when Apollo data is available' do
593
- let(:mock_entry_class) { double('ApolloEntry') }
594
- let(:mock_access_log_class) { double('ApolloAccessLog') }
595
- let(:mock_db) { double('db') }
596
- let(:sample_entries) do
597
- [{ id: 'uuid-1', content: 'Ruby is interpreted', content_type: 'fact',
598
- confidence: 0.8, distance: 0.15, tags: ['ruby'], source_agent: 'agent-1',
599
- access_count: 3 }]
600
- end
406
+ context 'when semantic query access logging is unavailable' do
407
+ let(:mock_entry_class) { double('Apollo::Entry') }
601
408
 
602
409
  before do
603
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
604
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class)
605
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
606
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
607
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
608
- allow(mock_db).to receive(:fetch).and_return(double(all: sample_entries))
609
- allow(mock_entry_class).to receive(:where).and_return(double(update: true))
610
- allow(mock_access_log_class).to receive(:create)
410
+ stub_const('Legion::Data::Model::Apollo::Entry', mock_entry_class)
411
+ hide_const('Legion::Data::Model::Apollo::AccessLog') if defined?(Legion::Data::Model::Apollo::AccessLog)
611
412
  end
612
413
 
414
+ it 'fails before embedding, lookup, or confidence mutation' do
415
+ expect(mock_entry_class).not_to receive(:db)
416
+ expect(Legion::LLM::Call::Embeddings).not_to receive(:generate)
417
+
418
+ expect(host.handle_query(query: 'semantic query')).to include(
419
+ success: false, error: 'apollo_data_not_available'
420
+ )
421
+ end
422
+ end
423
+
424
+ context 'when Apollo data is available' do
425
+ include_context 'persisted knowledge'
426
+
427
+ before { persisted_entry }
428
+
613
429
  it 'returns matching entries' do
614
430
  result = host.handle_query(query: 'Ruby', agent_id: 'agent-2')
615
431
  expect(result[:success]).to be true
616
432
  expect(result[:count]).to eq(1)
617
433
  expect(result[:entries].first[:content]).to eq('Ruby is interpreted')
618
434
  end
619
-
620
- it 'boosts access count on matched entries' do
621
- expect(mock_entry_class).to receive(:where).with(id: 'uuid-1')
622
- .and_return(double(update: true))
623
- host.handle_query(query: 'Ruby', agent_id: 'agent-2')
624
- end
625
-
626
- it 'logs query access' do
627
- expect(mock_access_log_class).to receive(:create).with(
628
- hash_including(agent_id: 'agent-2', action: 'query')
629
- )
630
- host.handle_query(query: 'Ruby', agent_id: 'agent-2')
631
- end
632
435
  end
633
436
 
634
437
  context 'when no results found' do
635
- let(:mock_entry_class) { double('ApolloEntry') }
636
- let(:mock_db) { double('db') }
637
-
638
- before do
639
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
640
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
641
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
642
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
643
- allow(mock_db).to receive(:fetch).and_return(double(all: []))
644
- end
438
+ include_context 'persisted knowledge'
645
439
 
646
440
  it 'returns empty entries array' do
647
441
  result = host.handle_query(query: 'nonexistent')
@@ -652,97 +446,51 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
652
446
  end
653
447
 
654
448
  context 'when query is browse-shaped' do
655
- let(:mock_entry_class) { double('ApolloEntry') }
656
- let(:dataset) { double('dataset') }
657
- let(:entries) do
658
- [{ id: 'uuid-1', content: 'Candidate fact', content_type: 'fact',
659
- confidence: 0.7, tags: ['ruby'], source_agent: 'agent-1',
660
- knowledge_domain: 'general' }]
661
- end
449
+ include_context 'persisted knowledge'
662
450
 
663
- before do
664
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
665
- allow(mock_entry_class).to receive(:exclude).with(status: 'archived').and_return(dataset)
666
- allow(dataset).to receive(:where).and_return(dataset)
667
- allow(dataset).to receive(:order).with(:created_at).and_return(dataset)
668
- allow(dataset).to receive(:limit).with(50).and_return(dataset)
669
- allow(dataset).to receive(:all).and_return(entries)
670
- end
451
+ let!(:candidate) { persisted_entry(content: 'Candidate fact', status: 'candidate') }
452
+ let!(:confirmed) { persisted_entry(content: 'Confirmed fact', tags: '["clinical"]', knowledge_domain: 'clinical') }
671
453
 
672
- it 'lists recent non-archived entries without generating an embedding' do
454
+ it 'includes candidates without generating an embedding' do
673
455
  expect(Legion::LLM::Call::Embeddings).not_to receive(:generate)
674
456
 
675
- result = host.handle_query(query: 'x', limit: 50)
457
+ result = host.handle_query(query: 'x')
676
458
 
677
- expect(result[:success]).to be true
678
- expect(result[:mode]).to eq(:browse)
679
- expect(result[:count]).to eq(1)
680
- expect(result[:entries].first[:content]).to eq('Candidate fact')
681
- expect(dataset).not_to have_received(:where).with(status: ['confirmed'])
682
- end
683
-
684
- it 'respects an explicit confirmed status filter' do
685
- host.handle_query(query: 'x', limit: 50, status: [:confirmed])
686
-
687
- expect(dataset).to have_received(:where).with(status: ['confirmed'])
459
+ expect(result).to include(success: true, mode: :browse)
460
+ expect(result[:entries].map { |entry| entry[:id] }).to contain_exactly(candidate.id, confirmed.id)
688
461
  end
689
462
 
690
- it 'applies tags and domain filters when provided' do
691
- host.handle_query(query: 'x', limit: 50, tags: ['ruby'], domain: 'general')
463
+ it 'honors an explicit confirmed status filter' do
464
+ result = host.handle_query(query: 'x', status: [:confirmed])
692
465
 
693
- expect(dataset).to have_received(:where).with('tags && ?')
694
- expect(dataset).to have_received(:where).with(knowledge_domain: 'general')
466
+ expect(result[:entries]).to contain_exactly(include(id: confirmed.id))
695
467
  end
696
- end
697
468
 
698
- context 'access scope forwarding' do
699
- let(:mock_entry_class) { double('ApolloEntry') }
700
- let(:mock_db) { double('db') }
701
-
702
- before do
703
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
704
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
705
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
706
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
707
- allow(mock_db).to receive(:fetch).and_return(double(all: []))
708
- allow(mock_entry_class).to receive(:where).and_return(double(update: true))
469
+ it 'intersects tags and domain filters' do
470
+ expect(host.handle_query(query: 'x', tags: ['clinical'], domain: 'clinical')[:entries])
471
+ .to contain_exactly(include(id: confirmed.id))
472
+ expect(host.handle_query(query: 'x', tags: ['ruby'], domain: 'clinical')[:entries]).to eq([])
709
473
  end
710
474
 
711
- it 'forwards requesting_principal_id to build_semantic_search_sql' do
712
- expect(Legion::Extensions::Apollo::Helpers::GraphQuery).to receive(:build_semantic_search_sql).with(
713
- hash_including(requesting_principal_id: 42)
714
- ).and_return('SELECT 1')
715
- allow(mock_db).to receive(:fetch).and_return(double(all: []))
475
+ it 'does not disguise provider failure as browse results' do
476
+ allow(Legion::LLM::Call::Embeddings).to receive(:generate).and_raise(Legion::LLM::LLMError, 'provider unavailable')
716
477
 
717
- host.handle_query(query: 'test', requesting_principal_id: 42)
478
+ expect(host.handle_query(query: 'clinical evidence')).to include(success: false, error: 'provider unavailable')
479
+ expect(candidate.refresh.confidence).to eq(0.8)
480
+ expect(confirmed.refresh.confidence).to eq(0.8)
481
+ expect(database[:apollo_access_logs].count).to eq(0)
718
482
  end
719
483
 
720
- it 'passes nil requesting_principal_id when not provided (no filter)' do
721
- expect(Legion::Extensions::Apollo::Helpers::GraphQuery).to receive(:build_semantic_search_sql).with(
722
- hash_including(requesting_principal_id: nil)
723
- ).and_return('SELECT 1')
484
+ it 'propagates programming errors instead of presenting empty search results' do
485
+ allow(Legion::LLM::Call::Embeddings).to receive(:generate).and_raise(NoMethodError, 'provider bug')
724
486
 
725
- host.handle_query(query: 'test')
487
+ expect { host.handle_query(query: 'clinical evidence') }.to raise_error(NoMethodError, 'provider bug')
726
488
  end
727
489
  end
728
490
  end
729
491
 
730
- describe '#normalize_text_input' do
731
- let(:host) { Object.new.extend(described_class) }
732
-
733
- it 'strips null bytes in the local fallback path' do
734
- expect(host.send(:normalize_text_input, "hello\x00world")).to eq('helloworld')
735
- end
736
-
737
- it 'scrubs invalid UTF-8 in the local fallback path' do
738
- invalid = "hello\xC3(world".dup.force_encoding(Encoding::UTF_8)
739
-
740
- expect(host.send(:normalize_text_input, invalid)).to eq('hello(world')
741
- end
742
- end
743
-
744
492
  describe '#retrieve_relevant' do
745
- let(:host) { Object.new.extend(described_class) }
493
+ let(:host) { runner }
746
494
 
747
495
  it 'returns skipped when skip is true' do
748
496
  result = host.retrieve_relevant(skip: true)
@@ -750,7 +498,7 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
750
498
  end
751
499
 
752
500
  context 'when Apollo data is not available' do
753
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
501
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
754
502
 
755
503
  it 'returns a structured error' do
756
504
  result = host.retrieve_relevant(query: 'test')
@@ -758,65 +506,45 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
758
506
  end
759
507
  end
760
508
 
761
- it 'returns empty when query is nil' do
762
- stub_const('Legion::Data::Model::ApolloEntry', Class.new)
763
- result = host.retrieve_relevant(query: nil)
764
- expect(result[:success]).to be true
765
- expect(result[:entries]).to eq([])
766
- end
509
+ context 'with a canonical database' do
510
+ include_context 'persisted knowledge'
767
511
 
768
- it 'returns empty when query is blank' do
769
- stub_const('Legion::Data::Model::ApolloEntry', Class.new)
770
- result = host.retrieve_relevant(query: ' ')
771
- expect(result[:success]).to be true
772
- expect(result[:entries]).to eq([])
773
- end
512
+ it 'returns empty when query is nil' do
513
+ result = host.retrieve_relevant(query: nil)
774
514
 
775
- context 'with valid query and data available' do
776
- let(:mock_entry_class) { double('ApolloEntry') }
777
- let(:mock_db) { double('db') }
778
- let(:sample_entries) do
779
- [{ id: 'uuid-1', content: 'fact', content_type: 'fact',
780
- confidence: 0.7, distance: 0.2, tags: ['ruby'], source_agent: 'agent-1' }]
515
+ expect(result[:success]).to be true
516
+ expect(result[:entries]).to eq([])
781
517
  end
782
518
 
783
- before do
784
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
785
- allow(Legion::LLM::Call::Embeddings).to receive(:generate)
786
- .and_return({ vector: Array.new(1024, 0.1), model: 'test', provider: :ollama, dimensions: 1024, tokens: 0 })
787
- allow(mock_entry_class).to receive(:db).and_return(mock_db)
788
- allow(mock_db).to receive(:fetch).and_return(double(all: sample_entries))
789
- allow(mock_entry_class).to receive(:where).and_return(double(update: true))
790
- end
519
+ it 'returns empty when query is blank' do
520
+ result = host.retrieve_relevant(query: ' ')
791
521
 
792
- it 'returns entries without access logging' do
793
- result = host.retrieve_relevant(query: 'Ruby facts')
794
522
  expect(result[:success]).to be true
795
- expect(result[:count]).to eq(1)
523
+ expect(result[:entries]).to eq([])
796
524
  end
525
+ end
797
526
 
798
- it 'passes domain to graph query builder' do
799
- expect(Legion::Extensions::Apollo::Helpers::GraphQuery).to receive(:build_semantic_search_sql).with(
800
- hash_including(domain: 'clinical')
801
- ).and_call_original
802
- host.retrieve_relevant(query: 'treatment', domain: 'clinical')
803
- end
527
+ context 'with valid query and data available' do
528
+ include_context 'persisted knowledge'
804
529
 
805
- it 'forwards requesting_principal_id to build_semantic_search_sql' do
806
- expect(Legion::Extensions::Apollo::Helpers::GraphQuery).to receive(:build_semantic_search_sql).with(
807
- hash_including(requesting_principal_id: 7)
808
- ).and_return('SELECT 1')
530
+ let!(:entry) { persisted_entry }
809
531
 
810
- host.retrieve_relevant(query: 'test', requesting_principal_id: 7)
532
+ it 'returns entries without access logging' do
533
+ result = host.retrieve_relevant(query: 'Ruby facts')
534
+ expect(result[:success]).to be true
535
+ expect(result[:count]).to eq(1)
536
+ expect(result[:entries]).to contain_exactly(include(id: entry.id, content: entry.content))
537
+ expect(database[:apollo_access_logs].count).to eq(0)
538
+ expect(entry.refresh.confidence).to be > 0.8
811
539
  end
812
540
  end
813
541
  end
814
542
 
815
543
  describe '#handle_traverse' do
816
- let(:host) { Object.new.extend(described_class) }
544
+ let(:host) { runner }
817
545
 
818
546
  context 'when Apollo data is not available' do
819
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
547
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
820
548
 
821
549
  it 'returns a structured error' do
822
550
  result = host.handle_traverse(entry_id: 'uuid-123')
@@ -826,8 +554,8 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
826
554
  end
827
555
 
828
556
  context 'when Apollo data is available' do
829
- let(:mock_entry_class) { double('ApolloEntry') }
830
- let(:mock_access_log_class) { double('ApolloAccessLog') }
557
+ let(:mock_entry_class) { double('Apollo::Entry') }
558
+ let(:mock_access_log_class) { double('Apollo::AccessLog') }
831
559
  let(:mock_db) { double('db') }
832
560
  let(:traversal_results) do
833
561
  [{ id: 'uuid-1', content: 'root', content_type: 'fact',
@@ -839,8 +567,8 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
839
567
  end
840
568
 
841
569
  before do
842
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
843
- stub_const('Legion::Data::Model::ApolloAccessLog', mock_access_log_class)
570
+ stub_const('Legion::Data::Model::Apollo::Entry', mock_entry_class)
571
+ stub_const('Legion::Data::Model::Apollo::AccessLog', mock_access_log_class)
844
572
  allow(mock_entry_class).to receive(:db).and_return(mock_db)
845
573
  allow(mock_db).to receive(:fetch).and_return(double(all: traversal_results))
846
574
  allow(mock_access_log_class).to receive(:create)
@@ -853,31 +581,12 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
853
581
  expect(result[:entries].first[:depth]).to eq(0)
854
582
  expect(result[:entries].last[:activation]).to eq(0.48)
855
583
  end
856
-
857
- it 'logs access for known agents' do
858
- expect(mock_access_log_class).to receive(:create).with(
859
- hash_including(agent_id: 'agent-x', action: 'query')
860
- )
861
- host.handle_traverse(entry_id: 'uuid-1', agent_id: 'agent-x')
862
- end
863
-
864
- it 'skips access logging for unknown agents' do
865
- expect(mock_access_log_class).not_to receive(:create)
866
- host.handle_traverse(entry_id: 'uuid-1')
867
- end
868
-
869
- it 'filters invalid relation_types' do
870
- expect(Legion::Extensions::Apollo::Helpers::GraphQuery).to receive(:build_traversal_sql).with(
871
- hash_including(relation_types: ['causes'])
872
- ).and_call_original
873
- host.handle_traverse(entry_id: 'uuid-1', relation_types: %w[causes invalid_type])
874
- end
875
584
  end
876
585
 
877
586
  context 'when Sequel raises an error' do
878
587
  before do
879
- stub_const('Legion::Data::Model::ApolloEntry', Class.new)
880
- allow(Legion::Data::Model::ApolloEntry).to receive(:db)
588
+ stub_const('Legion::Data::Model::Apollo::Entry', Class.new)
589
+ allow(Legion::Data::Model::Apollo::Entry).to receive(:db)
881
590
  .and_raise(Sequel::Error, 'connection lost')
882
591
  end
883
592
 
@@ -890,10 +599,10 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
890
599
  end
891
600
 
892
601
  describe '#redistribute_knowledge' do
893
- let(:host) { Object.new.extend(described_class) }
602
+ let(:host) { runner }
894
603
 
895
604
  context 'when Apollo data is not available' do
896
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
605
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
897
606
 
898
607
  it 'returns a structured error' do
899
608
  result = host.redistribute_knowledge(agent_id: 'agent-x')
@@ -903,14 +612,7 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
903
612
  end
904
613
 
905
614
  context 'when the departing agent has no confirmed entries' do
906
- let(:mock_entry_class) { double('ApolloEntry') }
907
-
908
- before do
909
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
910
- chain = double('chain')
911
- allow(mock_entry_class).to receive(:where).and_return(chain)
912
- allow(chain).to receive(:where).and_return(double(all: []))
913
- end
615
+ include_context 'persisted knowledge'
914
616
 
915
617
  it 'returns success with zero redistributed' do
916
618
  result = host.redistribute_knowledge(agent_id: 'departed-1')
@@ -920,17 +622,18 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
920
622
  end
921
623
 
922
624
  context 'when the departing agent has confirmed entries' do
923
- let(:mock_entry_class) { double('ApolloEntry') }
924
- let(:mock_entry) do
925
- double('entry', content: 'Ruby is fast', content_type: 'fact',
926
- confidence: 0.8, tags: ['ruby'])
927
- end
625
+ include_context 'persisted knowledge'
626
+
627
+ let(:stored_traces) { [] }
928
628
 
929
629
  before do
930
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
931
- chain = double('chain')
932
- allow(mock_entry_class).to receive(:where).and_return(chain)
933
- allow(chain).to receive(:where).and_return(double(all: [mock_entry]))
630
+ persisted_entry(source_agent: 'departed-2')
631
+ store = double('trace store')
632
+ allow(store).to receive(:store) { |trace| stored_traces << trace }
633
+ stub_const('Legion::Extensions::Agentic::Memory::Trace', Module.new)
634
+ allow(Legion::Extensions::Agentic::Memory::Trace).to receive(:shared_store).and_return(store)
635
+ stub_const('Legion::Extensions::Agentic::Memory::Trace::Helpers::Trace', Module.new)
636
+ allow(Legion::Extensions::Agentic::Memory::Trace::Helpers::Trace).to receive(:new_trace) { |**attributes| attributes }
934
637
  end
935
638
 
936
639
  it 'returns the count of redistributed entries' do
@@ -938,30 +641,22 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
938
641
  expect(result[:success]).to be true
939
642
  expect(result[:redistributed]).to eq(1)
940
643
  expect(result[:agent_id]).to eq('departed-2')
644
+ expect(stored_traces).to contain_exactly(include(content_payload: include(content: 'Ruby is interpreted', source_agent: 'departed-2')))
941
645
  end
942
646
 
943
- it 'stores into trace shared_store when Memory::Trace is available' do
944
- mock_store = double('store')
945
- mock_trace_helpers = Module.new do
946
- def self.new_trace(type:, content_payload: nil, **kwargs) # rubocop:disable Lint/UnusedMethodArgument
947
- { trace_id: 'trace-abc', trace_type: type, strength: kwargs[:strength] || 0.5 }
948
- end
949
- end
950
- stub_const('Legion::Extensions::Agentic::Memory::Trace', Module.new)
951
- stub_const('Legion::Extensions::Agentic::Memory::Trace::Helpers::Trace', mock_trace_helpers)
952
- allow(Legion::Extensions::Agentic::Memory::Trace).to receive(:shared_store).and_return(mock_store)
953
- allow(mock_store).to receive(:store)
647
+ it 'does not report redistribution when the memory sink is unavailable' do
648
+ allow(Legion::Extensions::Agentic::Memory::Trace).to receive(:shared_store).and_return(nil)
954
649
 
955
- result = host.redistribute_knowledge(agent_id: 'departed-3')
956
- expect(result[:redistributed]).to eq(1)
957
- expect(mock_store).to have_received(:store).once
650
+ expect(host.redistribute_knowledge(agent_id: 'departed-2')).to include(
651
+ success: false, error: 'memory_trace_not_available', redistributed: 0
652
+ )
958
653
  end
959
654
  end
960
655
 
961
656
  context 'when Sequel raises an error' do
962
657
  before do
963
- stub_const('Legion::Data::Model::ApolloEntry', Class.new)
964
- allow(Legion::Data::Model::ApolloEntry).to receive(:where)
658
+ stub_const('Legion::Data::Model::Apollo::Entry', Class.new)
659
+ allow(Legion::Data::Model::Apollo::Entry).to receive(:where)
965
660
  .and_raise(Sequel::Error, 'db error')
966
661
  end
967
662
 
@@ -974,10 +669,10 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
974
669
  end
975
670
 
976
671
  describe '#prepare_mesh_export' do
977
- let(:host) { Object.new.extend(described_class) }
672
+ let(:host) { runner }
978
673
 
979
674
  context 'when Legion::Data is not available' do
980
- before { hide_const('Legion::Data') if defined?(Legion::Data) }
675
+ before { allow(Legion::Data).to receive(:connection).and_return(nil) }
981
676
 
982
677
  it 'returns a structured error' do
983
678
  result = host.prepare_mesh_export(target_domain: 'clinical_care')
@@ -987,61 +682,43 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
987
682
  end
988
683
 
989
684
  context 'when data is available' do
990
- let(:mock_conn) { double('connection') }
991
- let(:mock_dataset) { double('dataset') }
992
- let(:clinical_entry) do
993
- { id: 'e1', content: 'treatment', content_type: 'fact',
994
- confidence: 0.8, knowledge_domain: 'clinical_care',
995
- tags: ['clinical'], source_agent: 'agent-1' }
996
- end
997
- let(:claims_entry) do
998
- { id: 'e2', content: 'denial', content_type: 'fact',
999
- confidence: 0.7, knowledge_domain: 'claims_optimization',
1000
- tags: ['claims'], source_agent: 'agent-2' }
1001
- end
685
+ include_context 'persisted knowledge'
1002
686
 
1003
- before do
1004
- data_mod = Module.new do
1005
- def self.connection; end
687
+ let!(:clinical_entry) { persisted_entry(content: 'treatment', knowledge_domain: 'clinical_care') }
688
+ let!(:claims_entry) { persisted_entry(content: 'denial', knowledge_domain: 'claims_optimization') }
1006
689
 
1007
- def self.respond_to?(method, *args)
1008
- method == :connection || super
1009
- end
1010
- end
1011
- stub_const('Legion::Data', data_mod)
1012
- allow(Legion::Data).to receive(:connection).and_return(mock_conn)
1013
- allow(mock_conn).to receive(:[]).with(:apollo_entries).and_return(mock_dataset)
1014
- allow(mock_dataset).to receive(:where).and_return(mock_dataset)
1015
- allow(mock_dataset).to receive(:limit).and_return(mock_dataset)
690
+ before do
691
+ allow(Legion::Data).to receive(:connection).and_return(database)
692
+ persisted_entry(content: 'private treatment', knowledge_domain: 'clinical_care',
693
+ access_scope: 'private', identity_principal_id: 7)
1016
694
  end
1017
695
 
1018
- it 'filters entries by domain compatibility for clinical_care' do
1019
- allow(mock_dataset).to receive(:all).and_return([clinical_entry])
696
+ it 'filters entries by domain compatibility and excludes private knowledge' do
1020
697
  result = host.prepare_mesh_export(target_domain: 'clinical_care')
1021
- expect(result[:success]).to be true
1022
- expect(result[:target_domain]).to eq('clinical_care')
698
+
699
+ expect(result).to include(success: true, target_domain: 'clinical_care')
700
+ expect(result[:entries]).to contain_exactly(include(id: clinical_entry.id))
1023
701
  end
1024
702
 
1025
- it 'allows all domains when target is general' do
1026
- allow(mock_dataset).to receive(:all).and_return([clinical_entry, claims_entry])
703
+ it 'allows all public domains when target is general' do
1027
704
  result = host.prepare_mesh_export(target_domain: 'general')
1028
- expect(result[:success]).to be true
1029
- expect(result[:count]).to eq(2)
705
+
706
+ expect(result[:entries].map { |entry| entry[:id] }).to contain_exactly(clinical_entry.id, claims_entry.id)
1030
707
  end
1031
708
 
1032
709
  it 'restricts claims_optimization to only claims entries' do
1033
- allow(mock_dataset).to receive(:all).and_return([claims_entry])
1034
710
  result = host.prepare_mesh_export(target_domain: 'claims_optimization')
1035
- expect(result[:success]).to be true
711
+
712
+ expect(result[:entries]).to contain_exactly(include(id: claims_entry.id))
1036
713
  end
1037
714
  end
1038
715
  end
1039
716
 
1040
717
  describe '#handle_erasure_request' do
1041
- let(:host) { Object.new.extend(described_class) }
718
+ let(:host) { runner }
1042
719
 
1043
720
  context 'when Legion::Data is not available' do
1044
- before { hide_const('Legion::Data') if defined?(Legion::Data) }
721
+ before { allow(Legion::Data).to receive(:connection).and_return(nil) }
1045
722
 
1046
723
  it 'returns zero counts with error' do
1047
724
  result = host.handle_erasure_request(agent_id: 'agent-dead')
@@ -1052,56 +729,28 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Knowledge do
1052
729
  end
1053
730
 
1054
731
  context 'when data is available' do
1055
- let(:mock_conn) { double('connection') }
1056
- let(:mock_dataset) { double('dataset') }
732
+ include_context 'persisted knowledge'
1057
733
 
1058
- before do
1059
- data_mod = Module.new do
1060
- def self.connection; end
734
+ before { allow(Legion::Data).to receive(:connection).and_return(database) }
1061
735
 
1062
- def self.respond_to?(method, *args)
1063
- method == :connection || super
1064
- end
1065
- end
1066
- stub_const('Legion::Data', data_mod)
1067
- allow(Legion::Data).to receive(:connection).and_return(mock_conn)
1068
- allow(mock_conn).to receive(:[]).with(:apollo_entries).and_return(mock_dataset)
1069
- allow(mock_dataset).to receive(:where).and_return(mock_dataset)
1070
- allow(mock_dataset).to receive(:exclude).and_return(mock_dataset)
1071
- allow(mock_dataset).to receive(:delete).and_return(3)
1072
- allow(mock_dataset).to receive(:update).and_return(2)
1073
- end
736
+ it 'deletes unconfirmed knowledge and redacts identity without erasing corroborated content or other agents' do
737
+ candidate = persisted_entry(content: 'unconfirmed', status: 'candidate', source_agent: 'agent-dead')
738
+ confirmed = persisted_entry(content: 'corroborated', source_agent: 'agent-dead',
739
+ identity_principal_id: 7, identity_id: 9, identity_canonical_name: 'private-name')
740
+ other = persisted_entry(content: 'other agent', source_agent: 'agent-alive')
1074
741
 
1075
- it 'deletes non-confirmed entries and redacts confirmed ones' do
1076
742
  result = host.handle_erasure_request(agent_id: 'agent-dead')
1077
- expect(result[:deleted]).to eq(3)
1078
- expect(result[:redacted]).to eq(2)
1079
- expect(result[:agent_id]).to eq('agent-dead')
1080
- end
1081
-
1082
- it 'clears identity columns on confirmed (redacted) entries' do
1083
- expect(mock_dataset).to receive(:update).with(
1084
- hash_including(
1085
- identity_principal_id: nil,
1086
- identity_id: nil,
1087
- identity_canonical_name: nil
1088
- )
1089
- ).and_return(2)
1090
743
 
1091
- host.handle_erasure_request(agent_id: 'agent-dead')
744
+ expect(result).to include(deleted: 1, redacted: 1, agent_id: 'agent-dead')
745
+ expect(entry_model[candidate.id]).to be_nil
746
+ expect(confirmed.refresh.values).to include(content: 'corroborated', source_agent: 'redacted',
747
+ identity_principal_id: nil, identity_id: nil, identity_canonical_name: nil)
748
+ expect(other.refresh.source_agent).to eq('agent-alive')
1092
749
  end
1093
750
  end
1094
751
 
1095
752
  context 'when Sequel raises an error' do
1096
753
  before do
1097
- data_mod = Module.new do
1098
- def self.connection; end
1099
-
1100
- def self.respond_to?(method, *args)
1101
- method == :connection || super
1102
- end
1103
- end
1104
- stub_const('Legion::Data', data_mod)
1105
754
  allow(Legion::Data).to receive(:connection).and_return(double('conn').tap do |c|
1106
755
  allow(c).to receive(:[]).and_raise(Sequel::Error, 'db gone')
1107
756
  end)