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
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'open3'
5
+ require 'rbconfig'
6
+ require 'json'
7
+
8
+ RSpec.describe 'Apollo service lifecycle mutations' do
9
+ let(:lifecycle_script) do
10
+ <<~'RUBY'
11
+ require 'sequel'
12
+ require 'sinatra/base'
13
+ require 'rack/mock'
14
+ require 'rspec'
15
+ require 'spec_helper'
16
+ require 'json'
17
+ require 'legion/extensions/apollo/api'
18
+ db = Sequel.sqlite
19
+ db.create_table(:apollo_entries) do
20
+ primary_key :id
21
+ String :content
22
+ String :content_type
23
+ String :status
24
+ String :access_scope, default: 'global'
25
+ Float :confidence
26
+ String :source_context
27
+ String :embedding
28
+ String :embedding_space_id
29
+ Integer :embedding_dimensions
30
+ String :embedding_provenance
31
+ DateTime :created_at
32
+ DateTime :updated_at
33
+ DateTime :confirmed_at
34
+ check(Sequel.lit("content != 'protected' OR status != 'archived'"))
35
+ end
36
+ Legion::Data.const_set(:Model, Module.new) unless defined?(Legion::Data::Model)
37
+ Legion::Data::Model.const_set(:Apollo, Module.new)
38
+ entry_model = Class.new(Sequel::Model(db[:apollo_entries]))
39
+ Legion::Data::Model::Apollo.const_set(:Entry, entry_model)
40
+ now = Time.now
41
+ old = now - (100 * 86_400)
42
+ attributes = { content_type: 'fact', status: 'candidate', confidence: 0.8,
43
+ source_context: ::JSON.generate(origin: 'preserve'), created_at: now, updated_at: nil }
44
+ embedding = ApolloSpecEmbedding.result
45
+ attributes.merge!(embedding: ::JSON.generate(embedding[:vector]), embedding_dimensions: embedding[:dimensions],
46
+ embedding_space_id: embedding[:embedding_provenance][:space_id],
47
+ embedding_provenance: ::JSON.generate(embedding[:embedding_provenance]))
48
+ db[:apollo_entries].insert(attributes.merge(id: 1, content: 'target'))
49
+ db[:apollo_entries].insert(attributes.merge(id: 2, content: 'protected'))
50
+ db[:apollo_entries].insert(attributes.merge(id: 3, content: 'stale', confidence: 0.04, created_at: old))
51
+ db[:apollo_entries].insert(attributes.merge(id: 4, content: 'touched', status: 'confirmed', confidence: 0.6,
52
+ created_at: old, updated_at: now))
53
+ db[:apollo_entries].insert(attributes.merge(id: 5, content: 'already archived', status: 'archived', confidence: 0.7,
54
+ created_at: old))
55
+ input = ::JSON.parse($stdin.read, symbolize_names: true)
56
+ maintenance = Legion::Extensions::Apollo::Runners::Maintenance
57
+ case input[:operation]
58
+ when 'deprecate'
59
+ api = Rack::MockRequest.new(Legion::Extensions::Apollo::Api)
60
+ payload = ::JSON.generate(reason: 'Verified replacement exists.')
61
+ first = api.post('/api/apollo/entries/1/deprecate', 'CONTENT_TYPE' => 'application/json', input: payload)
62
+ first_updated_at = entry_model[1].updated_at
63
+ repeated = api.post('/api/apollo/entries/1/deprecate', 'CONTENT_TYPE' => 'application/json', input: payload)
64
+ repeat_preserved_time = entry_model[1].updated_at == first_updated_at
65
+ missing = api.post('/api/apollo/entries/999/deprecate')
66
+ failed = api.post('/api/apollo/entries/2/deprecate', 'CONTENT_TYPE' => 'application/json', input: payload)
67
+ malformed = api.post('/api/apollo/entries/1/deprecate', 'CONTENT_TYPE' => 'application/json', input: '{')
68
+ Legion::Data::Model::Apollo.send(:remove_const, :Entry)
69
+ unavailable = api.post('/api/apollo/entries/1/deprecate')
70
+ Legion::Data::Model::Apollo.const_set(:Entry, entry_model)
71
+ responses = { first: first, repeated: repeated, missing: missing, failed: failed,
72
+ malformed: malformed, unavailable: unavailable }.transform_values do |response|
73
+ { status: response.status, body: ::JSON.parse(response.body) }
74
+ end
75
+ result = { responses: responses, repeat_preserved_time: repeat_preserved_time }
76
+ when 'maintenance'
77
+ decay = maintenance.force_decay(factor: 0.5)
78
+ after_decay = db[:apollo_entries].order(:id).all
79
+ invalid_factor = maintenance.force_decay(factor: -0.1)
80
+ invalid_factor_unchanged = after_decay == db[:apollo_entries].order(:id).all
81
+ archive = maintenance.archive_stale(days: 90)
82
+ repeated = maintenance.archive_stale(days: 90)
83
+ before_invalid_days = db[:apollo_entries].order(:id).all
84
+ invalid_days = maintenance.archive_stale(days: -1)
85
+ result = { decay: decay, after_decay: after_decay, invalid_factor: invalid_factor,
86
+ invalid_factor_unchanged: invalid_factor_unchanged, archive: archive, repeated: repeated,
87
+ invalid_days: invalid_days, invalid_days_unchanged: before_invalid_days == db[:apollo_entries].order(:id).all }
88
+ when 'dispute'
89
+ db[:apollo_entries].where(id: [1, 2, 3]).update(status: 'disputed')
90
+ db[:apollo_entries].insert(attributes.merge(id: 6, content: 'kept dispute', status: 'disputed'))
91
+ before_unknown = entry_model[6].values
92
+ unknown = maintenance.resolve_dispute(entry_id: 6, resolution: :unexpected)
93
+ unknown_unchanged = before_unknown == entry_model[6].values
94
+ accepted = maintenance.resolve_dispute(entry_id: 1, resolution: :accept)
95
+ rejected = maintenance.resolve_dispute(entry_id: 3, resolution: :reject)
96
+ kept = maintenance.resolve_dispute(entry_id: 6, resolution: :keep)
97
+ failed = maintenance.resolve_dispute(entry_id: 2, resolution: :reject)
98
+ missing = maintenance.resolve_dispute(entry_id: 999, resolution: :accept)
99
+ not_disputed = maintenance.resolve_dispute(entry_id: 4, resolution: :reject)
100
+ repeated = maintenance.resolve_dispute(entry_id: 1, resolution: :accept)
101
+ result = { accepted: accepted, rejected: rejected, kept: kept, failed: failed, missing: missing,
102
+ not_disputed: not_disputed, repeated: repeated, unknown: unknown, unknown_unchanged: unknown_unchanged }
103
+ end
104
+ puts "APOLLO_RESULT=#{::JSON.generate(result.merge(entries: db[:apollo_entries].order(:id).all))}"
105
+ RUBY
106
+ end
107
+
108
+ def lifecycle_state(operation:, **)
109
+ stdout, stderr, status = Open3.capture3(
110
+ RbConfig.ruby, '-Ilib', '-Ispec', '-e', lifecycle_script,
111
+ chdir: File.expand_path('../../../../..', __dir__),
112
+ stdin_data: JSON.generate(operation: operation)
113
+ )
114
+ line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
115
+ raise "Lifecycle process failed: #{stderr}\n#{stdout}" unless status.success? && line
116
+
117
+ JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
118
+ end
119
+
120
+ it 'archives through HTTP with retained metadata and truthful repeat, missing, unavailable, and rollback outcomes' do
121
+ state = lifecycle_state(operation: 'deprecate')
122
+ responses = state[:responses]
123
+
124
+ expect(responses[:first]).to include(status: 200, body: hash_including(success: true, updated: true, status: 'archived'))
125
+ expect(responses[:repeated]).to include(status: 200, body: hash_including(success: true, updated: false))
126
+ expect(state[:repeat_preserved_time]).to be true
127
+ expect(responses[:missing]).to include(status: 404, body: hash_including(error: 'entry_not_found'))
128
+ expect(responses[:unavailable]).to include(status: 503, body: hash_including(error: 'apollo_data_not_available'))
129
+ expect(responses[:failed]).to include(status: 500, body: hash_including(success: false))
130
+ expect(responses[:malformed][:status]).to eq(400)
131
+ expect(state[:entries].first[:status]).to eq('archived')
132
+ expect(JSON.parse(state[:entries].first[:source_context], symbolize_names: true))
133
+ .to include(origin: 'preserve', deprecation_reason: 'Verified replacement exists.')
134
+ expect(state[:entries][1]).to include(status: 'candidate', source_context: JSON.generate(origin: 'preserve'))
135
+ end
136
+
137
+ it 'multiplies active confidence without implicit archival and archives only stale, untouched entries' do
138
+ state = lifecycle_state(operation: 'maintenance')
139
+
140
+ expect(state[:decay]).to include(success: true, decayed: 4)
141
+ expect(state[:after_decay].map { |entry| entry[:confidence] }).to eq([0.4, 0.4, 0.02, 0.3, 0.7])
142
+ expect(state[:after_decay][2][:status]).to eq('candidate')
143
+ expect(state[:invalid_factor]).to include(success: false, error: 'invalid_factor')
144
+ expect(state[:invalid_factor_unchanged]).to be true
145
+ expect(state[:archive]).to include(success: true, archived: 1)
146
+ expect(state[:repeated]).to include(success: true, archived: 0)
147
+ expect(state[:entries][2][:status]).to eq('archived')
148
+ expect(state[:entries][3][:status]).to eq('confirmed')
149
+ expect(state[:invalid_days]).to include(success: false, error: 'invalid_days')
150
+ expect(state[:invalid_days_unchanged]).to be true
151
+ end
152
+
153
+ it 'applies the approved dispute transitions and preserves state for invalid, ineligible, or failed decisions' do
154
+ state = lifecycle_state(operation: 'dispute')
155
+
156
+ expect(state[:accepted]).to include(success: true, status: 'confirmed')
157
+ expect(state[:kept]).to include(success: true, status: 'confirmed')
158
+ expect(state[:rejected]).to include(success: true, status: 'archived')
159
+ expect(state[:failed]).to include(success: false)
160
+ expect(state[:missing]).to include(success: false, error: 'entry_not_found')
161
+ expect(state[:not_disputed]).to include(success: false, error: 'entry_not_disputed')
162
+ expect(state[:repeated]).to include(success: false, error: 'entry_not_disputed')
163
+ expect(state[:unknown]).to include(success: false, error: 'invalid_resolution')
164
+ expect(state[:unknown_unchanged]).to be true
165
+ expect(state[:entries].first).to include(status: 'confirmed', confidence: 0.8)
166
+ expect(state[:entries].first[:confirmed_at]).not_to be_nil
167
+ expect(JSON.parse(state[:entries].first[:source_context], symbolize_names: true))
168
+ .to include(origin: 'preserve', dispute_resolution: 'accept')
169
+ expect(state[:entries][1]).to include(status: 'disputed', source_context: JSON.generate(origin: 'preserve'))
170
+ expect(state[:entries][2][:status]).to eq('archived')
171
+ expect(state[:entries][3][:status]).to eq('confirmed')
172
+ expect(state[:entries].last[:status]).to eq('confirmed')
173
+ end
174
+ end
@@ -6,93 +6,68 @@ require 'legion/extensions/apollo/helpers/similarity'
6
6
  require 'legion/extensions/apollo/runners/maintenance'
7
7
 
8
8
  RSpec.describe Legion::Extensions::Apollo::Runners::Maintenance do
9
- let(:runner) do
10
- obj = Object.new
11
- obj.extend(described_class)
12
- obj
13
- end
9
+ let(:runner) { described_class }
14
10
 
15
- describe '#force_decay' do
16
- it 'returns a force_decay payload' do
17
- result = runner.force_decay(factor: 0.5)
18
- expect(result[:action]).to eq(:force_decay)
19
- expect(result[:factor]).to eq(0.5)
20
- end
11
+ before do
12
+ hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo)
13
+ allow(runner).to receive(:settings).and_return(Legion::Extensions::Apollo.settings)
21
14
  end
22
15
 
23
- describe '#archive_stale' do
24
- it 'returns an archive payload with default days' do
25
- result = runner.archive_stale
26
- expect(result[:action]).to eq(:archive_stale)
27
- expect(result[:days]).to eq(90)
28
- end
29
- end
16
+ it 'retains client action envelopes without claiming completed service mutations when data is unavailable' do
17
+ results = [runner.force_decay(factor: 0.5), runner.archive_stale(days: 90),
18
+ runner.resolve_dispute(entry_id: 'uuid-123', resolution: :keep)]
30
19
 
31
- describe '#resolve_dispute' do
32
- it 'returns a resolve payload' do
33
- result = runner.resolve_dispute(entry_id: 'uuid-123', resolution: :keep)
34
- expect(result[:action]).to eq(:resolve_dispute)
35
- expect(result[:resolution]).to eq(:keep)
36
- end
20
+ expect(results.map { |result| result[:action] }).to eq(%i[force_decay archive_stale resolve_dispute])
21
+ expect(results).to all(satisfy { |result| !result.key?(:success) })
37
22
  end
38
23
 
39
24
  describe '#run_decay_cycle' do
40
- let(:host) { Object.new.extend(described_class) }
25
+ let(:host) { runner }
41
26
 
42
27
  context 'when Legion::Data is not available' do
43
- before { hide_const('Legion::Data') if defined?(Legion::Data) }
28
+ before { allow(Legion::Data).to receive(:connection).and_return(nil) }
44
29
 
45
- it 'returns zero counts' do
46
- result = host.run_decay_cycle
47
- expect(result[:decayed]).to eq(0)
48
- expect(result[:archived]).to eq(0)
30
+ it 'returns an explicit unavailable error' do
31
+ expect(host.run_decay_cycle).to include(success: false, decayed: 0, archived: 0,
32
+ error: 'apollo_data_not_available')
49
33
  end
50
34
  end
51
35
 
52
- context 'when data is available' do
53
- let(:mock_conn) { double('connection') }
54
- let(:mock_dataset) { double('dataset') }
36
+ context 'with SQLite records spanning a batch boundary' do
37
+ let(:db) { Sequel.sqlite }
55
38
 
56
39
  before do
57
- data_mod = Module.new do
58
- def self.connection; end
59
-
60
- def self.respond_to?(method, *args)
61
- method == :connection || super
62
- end
40
+ db.create_table(:apollo_entries) do
41
+ primary_key :id
42
+ String :status
43
+ Float :confidence
44
+ DateTime :created_at
45
+ DateTime :updated_at
63
46
  end
64
- stub_const('Legion::Data', data_mod)
65
- allow(Legion::Data).to receive(:connection).and_return(mock_conn)
66
- allow(mock_conn).to receive(:[]).with(:apollo_entries).and_return(mock_dataset)
67
- allow(mock_dataset).to receive(:exclude).and_return(mock_dataset)
68
- allow(mock_dataset).to receive(:where).and_return(mock_dataset)
69
- allow(mock_dataset).to receive(:update).and_return(5)
47
+ allow(Legion::Data).to receive(:connection).and_return(db)
70
48
  end
71
49
 
72
- it 'returns alpha in result hash' do
73
- result = host.run_decay_cycle
74
- expect(result[:alpha]).to eq(0.05)
75
- expect(result).not_to have_key(:rate)
76
- end
50
+ after { db.disconnect }
77
51
 
78
- it 'returns decayed and archived counts' do
79
- result = host.run_decay_cycle
80
- expect(result[:decayed]).to eq(5)
81
- expect(result[:archived]).to eq(5)
82
- end
52
+ it 'decays all eligible rows without skipping records as archived rows leave the batch scope' do
53
+ old = Time.now - (30 * 86_400)
54
+ 501.times { db[:apollo_entries].insert(status: 'candidate', confidence: 0.01, created_at: old) }
55
+ retained = db[:apollo_entries].insert(status: 'confirmed', confidence: 1.0, created_at: old)
56
+ young = db[:apollo_entries].insert(status: 'candidate', confidence: 0.01, created_at: Time.now)
83
57
 
84
- it 'accepts custom alpha parameter' do
85
- result = host.run_decay_cycle(alpha: 0.3)
86
- expect(result[:alpha]).to eq(0.3)
58
+ expect(host.run_decay_cycle(alpha: 0.3, min_confidence: 0.05)).to include(decayed: 502, archived: 501)
59
+ expect(db[:apollo_entries].where(status: 'archived').count).to eq(501)
60
+ expect(db[:apollo_entries][id: retained][:confidence]).to be_between(0.9, 1.0).exclusive
61
+ expect(db[:apollo_entries][id: young]).to include(status: 'candidate', confidence: 0.01)
87
62
  end
88
63
  end
89
64
  end
90
65
 
91
66
  describe '#check_corroboration' do
92
- let(:host) { Object.new.extend(described_class) }
67
+ let(:host) { runner }
93
68
 
94
69
  context 'when Apollo data is not available' do
95
- before { hide_const('Legion::Data::Model::ApolloEntry') if defined?(Legion::Data::Model::ApolloEntry) }
70
+ before { hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo) }
96
71
 
97
72
  it 'returns a structured error' do
98
73
  result = host.check_corroboration
@@ -101,111 +76,18 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Maintenance do
101
76
  end
102
77
  end
103
78
 
104
- context 'when no candidates exist' do
105
- let(:mock_entry_class) { double('ApolloEntry') }
106
-
107
- before do
108
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
109
- allow(mock_entry_class).to receive(:where).with(status: 'candidate')
110
- .and_return(double(exclude: double(limit: double(all: []))))
111
- allow(mock_entry_class).to receive(:where).with(status: 'confirmed')
112
- .and_return(double(exclude: double(limit: double(all: []))))
113
- end
114
-
115
- it 'returns zero promoted and scanned' do
116
- result = host.check_corroboration
117
- expect(result[:success]).to be true
118
- expect(result[:promoted]).to eq(0)
119
- expect(result[:scanned]).to eq(0)
120
- end
121
- end
122
-
123
- context 'when a candidate matches a confirmed entry' do
124
- let(:mock_entry_class) { double('ApolloEntry') }
125
- let(:mock_relation_class) { double('ApolloRelation') }
126
- let(:embedding) { Array.new(1536, 0.5) }
127
- let(:candidate) do
128
- double('candidate', id: 'c-1', content_type: 'fact', embedding: embedding,
129
- confidence: 0.5, update: true)
130
- end
131
- let(:confirmed_entry) do
132
- double('confirmed', id: 'f-1', content_type: 'fact', embedding: embedding)
133
- end
134
-
135
- before do
136
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
137
- stub_const('Legion::Data::Model::ApolloRelation', mock_relation_class)
138
- allow(mock_entry_class).to receive(:where).with(status: 'candidate')
139
- .and_return(double(exclude: double(limit: double(all: [candidate]))))
140
- allow(mock_entry_class).to receive(:where).with(status: 'confirmed')
141
- .and_return(double(exclude: double(limit: double(all: [confirmed_entry]))))
142
- allow(mock_relation_class).to receive(:create)
143
- end
144
-
145
- it 'promotes the candidate' do
146
- expect(candidate).to receive(:update).with(hash_including(status: 'confirmed'))
147
- result = host.check_corroboration
148
- expect(result[:promoted]).to eq(1)
149
- expect(result[:scanned]).to eq(1)
150
- end
151
-
152
- it 'creates a similar_to relation' do
153
- expect(mock_relation_class).to receive(:create).with(
154
- hash_including(from_entry_id: 'c-1', to_entry_id: 'f-1', relation_type: 'similar_to')
155
- )
156
- host.check_corroboration
157
- end
158
- end
159
-
160
- context 'when candidate and confirmed share the same source_channel' do
161
- let(:mock_entry_class) { double('ApolloEntry') }
162
- let(:mock_relation_class) { double('ApolloRelation') }
163
- let(:embedding) { Array.new(1536, 0.5) }
164
- let(:candidate) do
165
- double('candidate', id: 'c-1', content_type: 'fact', embedding: embedding,
166
- confidence: 0.5, source_provider: 'openai', source_channel: 'slack-alerts')
167
- end
168
- let(:confirmed_entry) do
169
- double('confirmed', id: 'f-1', content_type: 'fact', embedding: embedding,
170
- source_provider: 'claude', source_channel: 'slack-alerts')
171
- end
79
+ context 'when relation persistence is unavailable' do
80
+ let(:mock_entry_class) { double('Apollo::Entry') }
172
81
 
173
82
  before do
174
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
175
- stub_const('Legion::Data::Model::ApolloRelation', mock_relation_class)
176
- allow(mock_entry_class).to receive(:where).with(status: 'candidate')
177
- .and_return(double(exclude: double(limit: double(all: [candidate]))))
178
- allow(mock_entry_class).to receive(:where).with(status: 'confirmed')
179
- .and_return(double(exclude: double(limit: double(all: [confirmed_entry]))))
83
+ stub_const('Legion::Data::Model::Apollo::Entry', mock_entry_class)
84
+ hide_const('Legion::Data::Model::Apollo::Relation') if defined?(Legion::Data::Model::Apollo::Relation)
180
85
  end
181
86
 
182
- it 'does not promote even with different providers' do
183
- result = host.check_corroboration
184
- expect(result[:promoted]).to eq(0)
185
- end
186
- end
187
-
188
- context 'when candidate has different content_type than confirmed' do
189
- let(:mock_entry_class) { double('ApolloEntry') }
190
- let(:embedding) { Array.new(1536, 0.5) }
191
- let(:candidate) do
192
- double('candidate', id: 'c-1', content_type: 'fact', embedding: embedding, confidence: 0.5)
193
- end
194
- let(:confirmed_entry) do
195
- double('confirmed', id: 'f-1', content_type: 'concept', embedding: embedding)
196
- end
87
+ it 'fails before scanning or promoting candidates' do
88
+ expect(mock_entry_class).not_to receive(:where)
197
89
 
198
- before do
199
- stub_const('Legion::Data::Model::ApolloEntry', mock_entry_class)
200
- allow(mock_entry_class).to receive(:where).with(status: 'candidate')
201
- .and_return(double(exclude: double(limit: double(all: [candidate]))))
202
- allow(mock_entry_class).to receive(:where).with(status: 'confirmed')
203
- .and_return(double(exclude: double(limit: double(all: [confirmed_entry]))))
204
- end
205
-
206
- it 'does not promote' do
207
- result = host.check_corroboration
208
- expect(result[:promoted]).to eq(0)
90
+ expect(host.check_corroboration).to include(success: false, error: 'apollo_data_not_available')
209
91
  end
210
92
  end
211
93
  end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'legion/extensions/apollo/runners/query_response'
5
+
6
+ RSpec.describe Legion::Extensions::Apollo::Runners::QueryResponse do
7
+ let(:exchange) { double('default exchange') }
8
+ let(:channel) { double('channel', default_exchange: exchange, using_publisher_confirmations?: true, wait_for_confirms: true) }
9
+ let(:reply_queue) { double('reply queue', name: 'apollo-reply') }
10
+ let(:replies) { [] }
11
+ let(:dataset) { double('entries') }
12
+ let(:database) { double('database', database_type: :postgres) }
13
+ let(:entry_model) { double('ApolloEntry', db: database) }
14
+ let(:entry) do
15
+ { id: 'entry-1', content: 'A shared fact', content_type: 'fact', confidence: 0.8,
16
+ tags: ['ruby'], source_agent: 'worker', depth: 0, activation: 1.0 }
17
+ end
18
+
19
+ before do
20
+ hide_const('Legion::Data::Model::Apollo') if defined?(Legion::Data::Model::Apollo)
21
+ hide_const('Legion::Identity::Process') if defined?(Legion::Identity::Process)
22
+ stub_const('Legion::Data::Model::Apollo::Entry', entry_model)
23
+ allow(entry_model).to receive(:exclude).and_return(dataset)
24
+ allow(dataset).to receive_messages(where: dataset, order: dataset, limit: dataset, all: [entry])
25
+ allow(database).to receive(:fetch).and_return(dataset)
26
+ allow(Legion::Transport::Connection).to receive(:channel).and_return(channel)
27
+ allow(exchange).to receive(:on_return) { |&handler| @return_handler = handler }
28
+ allow(exchange).to receive(:publish) do |payload, **properties|
29
+ if properties[:routing_key].start_with?('missing-')
30
+ @return_handler.call(nil, Struct.new(:message_id).new(properties[:message_id]), payload)
31
+ else
32
+ replies << { properties: properties, result: Legion::JSON.load(payload) }
33
+ end
34
+ end
35
+ end
36
+
37
+ it 'publishes the actual browse result with the AMQP correlation on the default exchange' do
38
+ result = described_class.handle_request(query: '', reply_to: reply_queue.name, correlation_id: 'query-123')
39
+
40
+ expect(result).to include(success: true, mode: :browse, entries: [include(id: 'entry-1')])
41
+ expect(replies.one?).to be true
42
+ expect(replies.first[:result]).to eq(Legion::JSON.load(Legion::JSON.dump(result)))
43
+ expect(replies.first[:properties]).to include(routing_key: 'apollo-reply', correlation_id: 'query-123', content_type: 'application/json')
44
+ end
45
+
46
+ it 'uses empty-query retrieval semantics instead of returning browse entries' do
47
+ described_class.handle_request(action: 'retrieve', query: '', reply_to: reply_queue.name)
48
+
49
+ expect(replies.first[:result]).to eq(success: true, entries: [], count: 0)
50
+ end
51
+
52
+ it 'executes traversal and publishes graph depth and activation' do
53
+ described_class.handle_request(action: 'traverse', entry_id: 'entry-1', reply_to: reply_queue.name)
54
+
55
+ expect(replies.first[:result]).to include(success: true, entries: [include(id: 'entry-1', depth: 0, activation: 1.0)])
56
+ end
57
+
58
+ it 'keeps requests without a reply destination fire-and-forget' do
59
+ expect(exchange).not_to receive(:publish)
60
+
61
+ expect(described_class.handle_request(action: 'retrieve', query: '')).to eq(success: true, entries: [], count: 0)
62
+ end
63
+
64
+ it 'publishes a structured error instead of dispatching an unsupported action' do
65
+ described_class.handle_request(action: 'delete_all', query: '', reply_to: reply_queue.name)
66
+
67
+ expect(replies.first[:result]).to eq(success: false, error: 'invalid_action')
68
+ end
69
+
70
+ it 'publishes a structured error when a query body is missing' do
71
+ described_class.handle_request(action: 'query', reply_to: reply_queue.name)
72
+
73
+ expect(replies.first[:result]).to include(success: false, error: 'invalid_request')
74
+ end
75
+
76
+ it 'rejects nonpositive and malformed traversal identities rather than executing a graph lookup' do
77
+ expect(database).not_to receive(:fetch)
78
+
79
+ [0, -1, nil, '', [], {}, 1.5, true].each do |entry_id|
80
+ result = described_class.handle_request(action: 'traverse', entry_id: entry_id, reply_to: reply_queue.name)
81
+
82
+ expect(result).to include(success: false, error: :invalid_request)
83
+ expect(replies.last[:result]).to include(success: false, error: 'invalid_request')
84
+ end
85
+ end
86
+
87
+ context 'with native SQLite entry identities' do
88
+ let(:sqlite_database) { Sequel.sqlite }
89
+
90
+ before do
91
+ sqlite_database.create_table(:apollo_entries) do
92
+ primary_key :id
93
+ String :content
94
+ String :content_type
95
+ Float :confidence
96
+ String :tags
97
+ String :source_agent
98
+ String :status
99
+ String :access_scope
100
+ end
101
+ sqlite_database.create_table(:apollo_relations) do
102
+ primary_key :id
103
+ Integer :from_entry_id
104
+ Integer :to_entry_id
105
+ String :relation_type
106
+ Float :weight
107
+ end
108
+ sqlite_database[:apollo_entries].insert(id: 1, content: 'SQLite root', content_type: 'fact',
109
+ confidence: 0.8, tags: '[]', source_agent: 'worker',
110
+ status: 'confirmed', access_scope: 'global')
111
+ allow(entry_model).to receive(:db).and_return(sqlite_database)
112
+ end
113
+
114
+ after { sqlite_database.disconnect }
115
+
116
+ it 'traverses a positive integer and preserves its native type in the reply' do
117
+ result = described_class.handle_request(action: 'traverse', entry_id: 1, reply_to: reply_queue.name)
118
+
119
+ expect(result).to include(success: true, entries: [include(id: 1, content: 'SQLite root', depth: 0, activation: 1.0)])
120
+ expect(replies.first[:result]).to include(success: true, entries: [include(id: 1)])
121
+ end
122
+
123
+ it 'returns an empty successful graph for a valid identity that is not present' do
124
+ described_class.handle_request(action: 'traverse', entry_id: 2, reply_to: reply_queue.name)
125
+
126
+ expect(replies.first[:result]).to eq(success: true, entries: [], count: 0)
127
+ end
128
+ end
129
+
130
+ it 'raises when the broker cannot route the reply instead of acknowledging success' do
131
+ expect do
132
+ described_class.handle_request(action: 'retrieve', query: '', reply_to: "missing-#{SecureRandom.uuid}")
133
+ end.to raise_error(IOError, /reply publication failed/)
134
+ end
135
+
136
+ it 'propagates publication exceptions to the subscription retry boundary' do
137
+ allow(exchange).to receive(:publish).and_raise(IOError, 'connection lost')
138
+
139
+ expect do
140
+ described_class.handle_request(action: 'retrieve', query: '', reply_to: reply_queue.name)
141
+ end.to raise_error(IOError, 'connection lost')
142
+ end
143
+
144
+ it 'raises on a negative publisher confirmation so the request can retry' do
145
+ allow(channel).to receive(:wait_for_confirms).and_return(false)
146
+
147
+ expect do
148
+ described_class.handle_request(action: 'retrieve', query: '', reply_to: reply_queue.name)
149
+ end.to raise_error(IOError, /reply publication failed/)
150
+ end
151
+
152
+ it 'retires an ambiguously timed-out channel before propagating the failure' do
153
+ allow(channel).to receive(:wait_for_confirms).and_raise(Timeout::Error)
154
+ allow(channel).to receive(:open?).and_return(true)
155
+ expect(channel).to receive(:close)
156
+
157
+ expect do
158
+ described_class.handle_request(action: 'retrieve', query: '', reply_to: reply_queue.name)
159
+ end.to raise_error(Timeout::Error)
160
+ end
161
+ end