lex-apollo 0.4.45 → 0.4.50

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 (29) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -0
  3. data/README.md +4 -0
  4. data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +12 -0
  5. data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +52 -16
  6. data/lib/legion/extensions/apollo/runners/expertise.rb +19 -19
  7. data/lib/legion/extensions/apollo/runners/gas.rb +43 -16
  8. data/lib/legion/extensions/apollo/runners/maintenance.rb +6 -4
  9. data/lib/legion/extensions/apollo/transport.rb +8 -5
  10. data/lib/legion/extensions/apollo/version.rb +1 -1
  11. data/lib/legion/extensions/apollo.rb +2 -0
  12. data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +24 -0
  13. data/spec/legion/extensions/apollo/api_spec.rb +3 -3
  14. data/spec/legion/extensions/apollo/gaia_integration_spec.rb +7 -1
  15. data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +3 -3
  16. data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +83 -2
  17. data/spec/legion/extensions/apollo/runners/expertise_spec.rb +20 -0
  18. data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +8 -15
  19. data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +6 -5
  20. data/spec/legion/extensions/apollo/runners/gas_spec.rb +65 -29
  21. data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +8 -16
  22. data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +3 -3
  23. data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +3 -3
  24. data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +3 -3
  25. data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +16 -0
  26. data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +3 -3
  27. data/spec/legion/extensions/apollo/transport_spec.rb +33 -0
  28. data/spec/spec_helper.rb +31 -0
  29. metadata +3 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 86765125810bd126d5043a809268ed63bfac8f0653f3c443254c9351b8ad3e08
4
- data.tar.gz: b841162c108cd4ca7e77a32a54735d7dc3e24d2826b3efe65f63ca2edef0f0d0
3
+ metadata.gz: 0fe398ea1e539ac9bc8986b617de7d5b350b16034c6b0aa03e4d21aa306f4831
4
+ data.tar.gz: cf6f6dc19f9eddf7e791b3a964ea14e3f5ee3eab2ab5901af63005bda791bf30
5
5
  SHA512:
6
- metadata.gz: 7cde23c3ada440beadb9ff1db3e31906b8c50d7599416be0cfb289aad48a57b748a054919da2885c44120432085cea6ff5f62700b6c6c07932e44fb16f06f1a2
7
- data.tar.gz: 1cf0063385d073236388353e46d1d0be72cd6fa4f6cc0b2236d7f019008e1715ebfdbe8d8680b9acaa89650c0358949f4e35f6900c90642dbe1d1526d78cd5b3
6
+ metadata.gz: f5c7952ee9f32f6b7bd0c459a5d5a2362934d9ef92577f5d24a67a00083aa69919fcd323e00694f2c893566a9561d5f083ee84c2247f7a5d1c6c82701f7673c0
7
+ data.tar.gz: 2af58f15246c91f8a4aae48d97eb16e8ab76fca7fd9f2228efa015ee4aedb34cff2ec5f9e770ffd0a7acb2021e3f8452c5f30c5d9e0e04e8f8816f5818e32a54
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.50] - 2026-11-19
4
+
5
+ ### Fixed
6
+ - Aggregate expertise counts and average confidence in the database, returning one row per agent and domain instead of loading every knowledge entry into Ruby. Preserve first-tag and general-domain fallbacks on PostgreSQL and SQLite.
7
+
8
+ ## [0.4.49] - 2026-11-18
9
+
10
+ ### Fixed
11
+ - Filter opt-in entity-watchdog task-log reads in SQL to global/public rows or private/team rows matching the running process principal or identity before log content leaves the database. Preserve restricted scope and principal through entity lookup and publication.
12
+ - Avoid delivering raw LLM audit events to disabled GAS subscribers; omit the audit queue binding on new disabled setups.
13
+
14
+ ## [0.4.48] - 2026-11-18
15
+
16
+ ### Fixed
17
+ - Disable GAS audit-event ingestion by default. Require explicit private principal scope and sanitized content before processing, reject sensitive-looking source and derived text, never deposit raw responses in mechanical mode, and restrict semantic relation lookup to the same principal (#47).
18
+
19
+ ## [0.4.47] - 2026-11-18
20
+
21
+ ### Fixed
22
+ - Scale the power-law decay exponent by the configured actor interval so hourly runs apply approximately one daily decay step instead of compounding 24 daily steps (#45).
23
+
24
+ ## [0.4.46] - 2026-11-18
25
+
26
+ ### Fixed
27
+ - Disable the entity watchdog's task-log scan by default. Opt in with `apollo.entity_watchdog.enabled: true` only where reading and publishing entities from recent task logs is intended and permitted; disabled scans never query `task_logs`.
28
+
3
29
  ## [0.4.45] - 2026-10-30
4
30
 
5
31
  ### Fixed
data/README.md CHANGED
@@ -160,6 +160,10 @@ Service actors include:
160
160
  | `ContradictionScanner` | Interval | 600s | Scan queued entries and retain failures for retry |
161
161
  | `EntityWatchdog` | Interval | 120s | Extract entities from recent `TaskLog.entry` values and publish missing knowledge |
162
162
 
163
+ GAS ingestion is disabled by default (`apollo.gas.enabled: false`). When enabled, it processes only audit events explicitly marked `content_sanitized: true` with `access_scope: private` and a positive `identity_principal_id`. It rejects source text containing recognized PII or PHI patterns, skips sensitive-looking derived entries, and stores accepted entries under that principal. The current `legion-llm` audit publisher does not supply those scope and sanitization fields, so its events remain non-persisting until that producer contract is added. GAS does not deposit a raw response when its LLM is unavailable, and it does not promote private audit content into the unscoped anticipation store.
164
+
165
+ The entity watchdog is disabled by default (`apollo.entity_watchdog.enabled: false`). When enabled, its database query reads only global/public task logs or private/team logs matching the process principal or identity. It preserves each log's scope and principal when checking or publishing entities. Task-log producers must set the correct scope and identity: logs incorrectly marked global remain visible and produce global knowledge, so keep the watchdog disabled until those producers are fixed.
166
+
163
167
  Actors own scheduling and delivery management; runner modules own workflows. Call public runner methods on their modules rather than extending arbitrary objects. Helpers provide private, concern-prefixed utilities. The existing `Helpers::Writeback.evaluate_and_route` and `content_hash(content:)` APIs remain unchanged pending their separate caller migration.
164
168
 
165
169
  Semantic embedding or lookup failure returns an explicit failure, not browse results or an empty successful search. Expertise queries require local models, return plain hashes, and count distinct agents for domain coverage. The watchdog counts accepted publications, remembers only successfully processed log texts, and retries failed texts.
@@ -11,6 +11,18 @@ module Legion
11
11
  class GasSubscriber < Legion::Extensions::Actors::Subscription
12
12
  include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
13
13
 
14
+ def prepare
15
+ return unless settings[:gas][:enabled] == true
16
+
17
+ super
18
+ end
19
+
20
+ def activate
21
+ return unless settings[:gas][:enabled] == true
22
+
23
+ super
24
+ end
25
+
14
26
  def runner_class = Legion::Extensions::Apollo::Runners::Gas
15
27
  def runner_function = 'process'
16
28
  def check_subtask? = false
@@ -19,20 +19,23 @@ module Legion
19
19
  extend self
20
20
 
21
21
  def scan_and_ingest(**)
22
+ return { success: true, ingested: 0, reason: :disabled } unless settings[:entity_watchdog][:enabled] == true
23
+
22
24
  return { success: false, error: 'task_log_not_available', ingested: 0 } if data_model_task_log.nil?
23
25
 
24
- texts = entity_watchdog_recent_task_log_texts
25
- return { success: true, ingested: 0, reason: :no_logs } if texts.empty?
26
+ task_logs = entity_watchdog_recent_task_logs
27
+ return { success: true, ingested: 0, reason: :no_logs } if task_logs.empty?
26
28
 
27
29
  @entity_watchdog_processed_hashes ||= {}
28
30
  hash_limit = [settings[:entity_watchdog][:log_limit] * 4, 100].max
29
31
  ingested = 0
30
32
  failed = 0
31
- texts.each do |text|
32
- text_hash = Digest::SHA256.hexdigest(text)
33
+ task_logs.each do |task_log|
34
+ text_hash = Digest::SHA256.hexdigest([task_log[:access_scope], task_log[:identity_principal_id],
35
+ task_log[:text]].join("\0"))
33
36
  next if @entity_watchdog_processed_hashes.key?(text_hash)
34
37
 
35
- result = entity_watchdog_ingest_text(text: text)
38
+ result = entity_watchdog_ingest_text(task_log: task_log)
36
39
  ingested += result[:ingested]
37
40
  unless result[:success]
38
41
  failed += 1
@@ -43,8 +46,8 @@ module Legion
43
46
  @entity_watchdog_processed_hashes.shift while @entity_watchdog_processed_hashes.size > hash_limit
44
47
  end
45
48
 
46
- log.info("EntityWatchdog ingested=#{ingested} logs_scanned=#{texts.size} failed=#{failed}")
47
- { success: failed.zero?, ingested: ingested, logs_scanned: texts.size, failed: failed }
49
+ log.info("EntityWatchdog ingested=#{ingested} logs_scanned=#{task_logs.size} failed=#{failed}")
50
+ { success: failed.zero?, ingested: ingested, logs_scanned: task_logs.size, failed: failed }
48
51
  rescue StandardError => e
49
52
  handle_exception(e, level: :error, operation: 'apollo.entity_watchdog.scan_and_ingest')
50
53
  { success: false, error: e.message, ingested: ingested || 0 }
@@ -52,26 +55,58 @@ module Legion
52
55
 
53
56
  private
54
57
 
55
- def entity_watchdog_recent_task_log_texts
58
+ def entity_watchdog_recent_task_logs
56
59
  cutoff = Time.now - settings[:entity_watchdog][:lookback_seconds]
60
+ public_scopes = %w[global public]
61
+ visibility = [{ access_scope: public_scopes }]
62
+ identity = entity_watchdog_process_identity
63
+ if identity[:principal_id]
64
+ visibility << { access_scope: %w[private team], identity_principal_id: identity[:principal_id] }
65
+ if identity[:identity_id]
66
+ visibility << { access_scope: %w[private team], identity_principal_id: nil,
67
+ identity_id: identity[:identity_id] }
68
+ end
69
+ end
57
70
  Legion::Data::Model::TaskLog.where { created_at >= cutoff }
71
+ .where(Sequel.|(*visibility))
58
72
  .order(Sequel.desc(:created_at))
59
73
  .limit(settings[:entity_watchdog][:log_limit])
60
- .select_map(:entry).map(&:to_s).reject(&:empty?).uniq
74
+ .select(:entry, :access_scope, :identity_principal_id).all.filter_map do |row|
75
+ text = row[:entry].to_s
76
+ next if text.empty?
77
+
78
+ scope = public_scopes.include?(row[:access_scope]) ? 'global' : row[:access_scope]
79
+ { text: text, access_scope: scope,
80
+ identity_principal_id: scope == 'global' ? nil : (row[:identity_principal_id] || identity[:principal_id]) }
81
+ end.uniq
82
+ end
83
+
84
+ def entity_watchdog_process_identity
85
+ return {} unless defined?(Legion::Identity::Process)
86
+
87
+ principal_id = Legion::Identity::Process.db_principal_id
88
+ identity_id = Legion::Identity::Process.db_identity_id
89
+ identity = {}
90
+ identity[:principal_id] = principal_id if principal_id.is_a?(Integer) && principal_id.positive?
91
+ identity[:identity_id] = identity_id if identity_id.is_a?(Integer) && identity_id.positive?
92
+ identity
93
+ rescue StandardError => e
94
+ handle_exception(e, level: :warn, operation: 'apollo.entity_watchdog.process_identity')
95
+ {}
61
96
  end
62
97
 
63
- def entity_watchdog_ingest_text(text:)
98
+ def entity_watchdog_ingest_text(task_log:)
64
99
  ingested = 0
65
100
  result = Legion::Extensions::Apollo::Runners::EntityExtractor.extract_entities(
66
- text: text, entity_types: settings[:entity_watchdog][:types],
101
+ text: task_log[:text], entity_types: settings[:entity_watchdog][:types],
67
102
  min_confidence: settings[:entity_watchdog][:min_confidence]
68
103
  )
69
104
  return { success: false, ingested: 0 } unless result[:success] && result[:source] != :unavailable
70
105
 
71
106
  result[:entities].each do |entity|
72
- next if entity_watchdog_entity_exists?(entity: entity)
107
+ next if entity_watchdog_entity_exists?(entity: entity, task_log: task_log)
73
108
 
74
- entity_watchdog_publish(entity: entity)
109
+ entity_watchdog_publish(entity: entity, task_log: task_log)
75
110
  ingested += 1
76
111
  end
77
112
  { success: true, ingested: ingested }
@@ -80,11 +115,11 @@ module Legion
80
115
  { success: false, ingested: ingested, error: e.message }
81
116
  end
82
117
 
83
- def entity_watchdog_entity_exists?(entity:)
118
+ def entity_watchdog_entity_exists?(entity:, task_log:)
84
119
  result = Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(
85
120
  query: entity[:name].to_s, limit: 1,
86
121
  min_confidence: settings[:entity_watchdog][:exists_min_confidence],
87
- tags: [entity[:type].to_s]
122
+ tags: [entity[:type].to_s], requesting_principal_id: task_log[:identity_principal_id] || 0
88
123
  )
89
124
  raise "Apollo entity lookup failed: #{result[:error]}" unless result[:success]
90
125
 
@@ -94,11 +129,12 @@ module Legion
94
129
  closest.fetch(:distance) <= (1.0 - settings[:entity_watchdog][:dedup_threshold])
95
130
  end
96
131
 
97
- def entity_watchdog_publish(entity:)
132
+ def entity_watchdog_publish(entity:, task_log:)
98
133
  Legion::Extensions::Apollo::Transport::Messages::Ingest.new(
99
134
  content: "#{entity[:type].to_s.capitalize}: #{entity[:name]}",
100
135
  content_type: 'concept', tags: [entity[:type].to_s, 'entity_watchdog'],
101
136
  source_agent: 'lex-apollo:entity_watchdog',
137
+ access_scope: task_log[:access_scope], identity_principal_id: task_log[:identity_principal_id],
102
138
  context: { entity_type: entity[:type], original_name: entity[:name] }
103
139
  ).publish!
104
140
  log.info("EntityWatchdog published entity type=#{entity[:type]} name=#{entity[:name]}")
@@ -3,7 +3,6 @@
3
3
  require 'legion/logging/helper'
4
4
  require 'legion/settings/helper'
5
5
  require 'legion/extensions/apollo/helpers/data_models'
6
- require 'legion/extensions/apollo/helpers/storage'
7
6
 
8
7
  module Legion
9
8
  module Extensions
@@ -13,7 +12,6 @@ module Legion
13
12
  include Legion::Logging::Helper
14
13
  include Legion::Settings::Helper
15
14
  extend Legion::Extensions::Apollo::Helpers::DataModels
16
- extend Legion::Extensions::Apollo::Helpers::Storage
17
15
  extend self
18
16
 
19
17
  def get_expertise(domain:, min_proficiency: settings[:expertise][:initial_proficiency], **)
@@ -60,12 +58,12 @@ module Legion
60
58
  return { success: false, error: 'apollo_data_not_available' }
61
59
  end
62
60
 
63
- entries = model.select(:source_agent, :knowledge_domain, :tags, :confidence).exclude(source_agent: nil).all
64
- log.debug("Apollo Expertise.aggregate entries=#{entries.size}")
61
+ groups = expertise_groups(model: model)
62
+ log.debug("Apollo Expertise.aggregate groups=#{groups.size}")
65
63
 
66
64
  agent_set = Set.new
67
65
  domain_set = Set.new
68
- expertise_groups(entries: entries).each_value do |group|
66
+ groups.each do |group|
69
67
  expertise_upsert_group(model: expertise_model, group: group)
70
68
  agent_set << group[:agent_id]
71
69
  domain_set << group[:domain]
@@ -80,20 +78,23 @@ module Legion
80
78
 
81
79
  private
82
80
 
83
- def expertise_groups(entries:, **)
84
- entries.each_with_object({}) do |entry, groups|
85
- agent = entry.source_agent
86
- domain = entry.knowledge_domain ||
87
- storage_deserialize_tags(tags: entry.tags).first || 'general'
88
- key = [agent, domain]
89
- groups[key] ||= { agent_id: agent, domain: domain, confidences: [] }
90
- groups[key][:confidences] << entry.confidence.to_f
91
- end
81
+ def expertise_groups(model:, **)
82
+ domain = case model.db.database_type
83
+ when :postgres then Sequel.lit("COALESCE(knowledge_domain, tags[1], 'general')")
84
+ when :sqlite then Sequel.lit("COALESCE(knowledge_domain, json_extract(tags, '$[0]'), 'general')")
85
+ else raise ArgumentError, "unsupported Apollo adapter: #{model.db.database_type}"
86
+ end
87
+
88
+ model.dataset.exclude(source_agent: nil)
89
+ .select(Sequel[:source_agent].as(:agent_id), domain.as(:domain),
90
+ Sequel.function(:count, Sequel.lit('*')).as(:entry_count),
91
+ Sequel.function(:avg, Sequel.function(:coalesce, :confidence, 0.0)).as(:average_confidence))
92
+ .group(:source_agent, domain).naked.all
92
93
  end
93
94
 
94
95
  def expertise_upsert_group(model:, group:, **)
95
- count = group[:confidences].size
96
- proficiency = expertise_proficiency(confidences: group[:confidences])
96
+ count = group[:entry_count]
97
+ proficiency = expertise_proficiency(average_confidence: group[:average_confidence], entry_count: count)
97
98
  existing = model.first(agent_id: group[:agent_id], domain: group[:domain])
98
99
 
99
100
  if existing
@@ -104,10 +105,9 @@ module Legion
104
105
  end
105
106
  end
106
107
 
107
- def expertise_proficiency(confidences:, **)
108
- avg = confidences.sum / confidences.size
108
+ def expertise_proficiency(average_confidence:, entry_count:, **)
109
109
  cap = settings[:expertise][:proficiency_cap]
110
- [avg * Math.log2(confidences.size + 1), cap].min
110
+ [average_confidence.to_f * Math.log2(entry_count + 1), cap].min
111
111
  end
112
112
  end
113
113
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/llm/inference'
4
+ require 'legion/llm/inference/steps/classification'
4
5
  require 'legion/logging/helper'
5
6
  require 'legion/settings/helper'
6
7
  require 'legion/json'
@@ -30,15 +31,18 @@ module Legion
30
31
  log.debug('GAS process skipped reason=no_content')
31
32
  return { success: true, phases_completed: 0, reason: 'no content' }
32
33
  end
34
+ return { success: true, phases_completed: 0, reason: 'disabled' } unless settings[:gas][:enabled] == true
35
+ return { success: true, phases_completed: 0, reason: 'unsafe_audit_event' } unless gas_persistable_event?(audit_event)
36
+ return { success: true, phases_completed: 0, reason: 'llm_unavailable' } unless Legion::LLM.started?
33
37
 
34
38
  log.debug("GAS process start request_id=#{audit_event[:request_id] || 'nil'} messages=#{Array(audit_event[:messages]).size} response_length=#{audit_event[:response_content].to_s.length}") # rubocop:disable Layout/LineLength
35
39
 
36
- facts = gas_phase_comprehend(audit_event)
40
+ facts = gas_phase_comprehend(audit_event).reject { |fact| gas_sensitive_content?(fact[:content]) }
37
41
  entities = gas_phase_extract(audit_event, facts)
38
- relations = gas_phase_relate(facts: facts)
42
+ relations = gas_phase_relate(facts: facts, requesting_principal_id: audit_event[:identity_principal_id])
39
43
  synthesis = gas_phase_synthesize(facts, relations)
40
44
  deposit_result = gas_phase_deposit(facts: facts, relations: relations, synthesis: synthesis, audit_event: audit_event)
41
- anticipations = gas_phase_anticipate(facts, synthesis)
45
+ anticipations = []
42
46
 
43
47
  result = {
44
48
  success: deposit_result[:failed].zero? && deposit_result[:relations_failed].zero?,
@@ -63,14 +67,30 @@ module Legion
63
67
  event[:messages]&.any? == true && !event[:response_content].nil?
64
68
  end
65
69
 
70
+ def gas_persistable_event?(event)
71
+ return false unless event[:access_scope].to_s == 'private'
72
+ return false unless event[:identity_principal_id].is_a?(Integer) && event[:identity_principal_id].positive?
73
+ return false unless event[:content_sanitized] == true
74
+
75
+ !gas_sensitive_content?(Legion::JSON.dump([event[:messages], event[:response_content]]))
76
+ end
77
+
78
+ def gas_sensitive_content?(content)
79
+ text = content.to_s
80
+ classification = Legion::LLM::Inference::Steps::Classification
81
+ classification::PII_PATTERNS.each_value do |pattern|
82
+ return true if text.match?(pattern)
83
+ end
84
+ classification::PHI_KEYWORDS.any? { |keyword| text.downcase.include?(keyword) }
85
+ end
86
+
66
87
  # Phase 1: Comprehend - extract typed facts from the exchange
67
88
  def gas_phase_comprehend(audit_event)
68
89
  messages = audit_event[:messages]
69
90
  response = audit_event[:response_content]
70
91
 
71
- mode = Legion::LLM.started? ? :llm : :mechanical
72
- log.debug("GAS phase_comprehend mode=#{mode} messages=#{Array(messages).size} response_length=#{response.to_s.length}")
73
- facts = mode == :llm ? gas_llm_comprehend(messages, response) : gas_mechanical_comprehend(messages, response)
92
+ log.debug("GAS phase_comprehend mode=llm messages=#{Array(messages).size} response_length=#{response.to_s.length}")
93
+ facts = gas_llm_comprehend(messages, response)
74
94
  log.debug("GAS phase_comprehend facts=#{facts.size}")
75
95
  facts
76
96
  end
@@ -86,8 +106,8 @@ module Legion
86
106
  end
87
107
 
88
108
  # Phase 3: Relate - classify relationships between new and existing entries
89
- def gas_phase_relate(facts:, **)
90
- existing = gas_fetch_similar_entries(facts: facts)
109
+ def gas_phase_relate(facts:, requesting_principal_id: nil, **)
110
+ existing = gas_fetch_similar_entries(facts: facts, requesting_principal_id: requesting_principal_id)
91
111
  if existing.empty?
92
112
  log.debug("GAS phase_relate skipped reason=no_existing_entries facts=#{facts.size}")
93
113
  return []
@@ -127,6 +147,10 @@ module Legion
127
147
  source_ids = {}
128
148
  { facts: facts, synthesis: synthesis }.each do |kind, entries|
129
149
  entries.each_with_index do |item, index|
150
+ if gas_sensitive_content?(item[:content])
151
+ counts[:skipped_sensitive] = counts.fetch(:skipped_sensitive, 0) + 1
152
+ next
153
+ end
130
154
  context = { source_request_id: audit_event[:request_id] }
131
155
  if kind == :synthesis
132
156
  context[:source_indices] = Array(item[:source_indices])
@@ -138,7 +162,8 @@ module Legion
138
162
  content: item[:content], content_type: item[:content_type].to_s,
139
163
  tags: %w[gas auto_extracted], source_agent: 'gas_pipeline',
140
164
  source_provider: audit_event.dig(:routing, :provider),
141
- knowledge_domain: 'general', context: context
165
+ knowledge_domain: 'general', context: context,
166
+ access_scope: 'private', identity_principal_id: audit_event[:identity_principal_id]
142
167
  )
143
168
  unless result.is_a?(Hash) && result[:success] == true && result[:entry_id]
144
169
  counts[:failed] += 1
@@ -189,7 +214,7 @@ module Legion
189
214
  end
190
215
 
191
216
  key = [source.id, target.id, type]
192
- if source.id == target.id || source[:access_scope] != target[:access_scope] || seen[key]
217
+ if source.id == target.id || gas_relation_crosses_scope?(source: source, target: target) || seen[key]
193
218
  counts[:relations_skipped] += 1
194
219
  next
195
220
  end
@@ -210,6 +235,11 @@ module Legion
210
235
  confidence.between?(settings[:gas][:relate_confidence_gate], 1.0)
211
236
  end
212
237
 
238
+ def gas_relation_crosses_scope?(source:, target:)
239
+ source[:access_scope] != target[:access_scope] ||
240
+ source[:identity_principal_id] != target[:identity_principal_id]
241
+ end
242
+
213
243
  # Phase 6: Anticipate - pre-cache likely follow-up questions
214
244
  def gas_phase_anticipate(facts, _synthesis)
215
245
  if facts.empty?
@@ -226,13 +256,14 @@ module Legion
226
256
  anticipations
227
257
  end
228
258
 
229
- def gas_fetch_similar_entries(facts:, **)
259
+ def gas_fetch_similar_entries(facts:, requesting_principal_id: nil, **)
230
260
  lim = settings[:gas][:similar_entries_limit]
231
261
  min_conf = settings[:query][:default_min_confidence]
232
262
  entries = []
233
263
  facts.each do |fact|
234
264
  result = Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(
235
- query: fact[:content], limit: lim, min_confidence: min_conf
265
+ query: fact[:content], limit: lim, min_confidence: min_conf,
266
+ requesting_principal_id: requesting_principal_id
236
267
  )
237
268
  raise IOError, "Apollo semantic retrieval failed: #{result[:error]}" unless result[:success]
238
269
 
@@ -428,10 +459,6 @@ module Legion
428
459
  nil
429
460
  end
430
461
 
431
- def gas_mechanical_comprehend(_messages, response)
432
- [{ content: response, content_type: :observation }]
433
- end
434
-
435
462
  def gas_llm_comprehend(messages, response)
436
463
  prompt = <<~PROMPT
437
464
  Extract distinct facts from this exchange. Return JSON array of {content:, content_type:} where content_type is one of: fact, concept, procedure, association.
@@ -93,6 +93,7 @@ module Legion
93
93
  alpha ||= Legion::Extensions::Apollo.settings[:power_law_alpha]
94
94
  min_confidence ||= Legion::Extensions::Apollo.settings[:decay_threshold]
95
95
  min_age_hours = Legion::Extensions::Apollo.settings[:decay_min_age_hours]
96
+ cycle_alpha = alpha * (Legion::Extensions::Apollo.settings[:actors][:decay_interval].to_f / 86_400.0)
96
97
 
97
98
  log.debug("Apollo Maintenance.run_decay_cycle alpha=#{alpha} min_confidence=#{min_confidence} min_age_hours=#{min_age_hours}")
98
99
  unless Legion::Data.connection
@@ -102,7 +103,8 @@ module Legion
102
103
 
103
104
  conn = Legion::Data.connection
104
105
  if conn.database_type == :sqlite
105
- return maintenance_decay_sqlite_entries(db: conn, alpha: alpha, min_confidence: min_confidence,
106
+ return maintenance_decay_sqlite_entries(db: conn, alpha: alpha, cycle_alpha: cycle_alpha,
107
+ min_confidence: min_confidence,
106
108
  min_age_hours: min_age_hours)
107
109
  end
108
110
 
@@ -111,7 +113,7 @@ module Legion
111
113
  )
112
114
  decay_factor = Sequel.lit(
113
115
  'POWER(CAST(? AS double precision) / (CAST(? AS double precision) + 1.0), ?)',
114
- age_days_expr, age_days_expr, alpha
116
+ age_days_expr, age_days_expr, cycle_alpha
115
117
  )
116
118
 
117
119
  min_age_filter = Sequel.lit(
@@ -225,7 +227,7 @@ module Legion
225
227
 
226
228
  private
227
229
 
228
- def maintenance_decay_sqlite_entries(db:, alpha:, min_confidence:, min_age_hours:, **)
230
+ def maintenance_decay_sqlite_entries(db:, alpha:, cycle_alpha:, min_confidence:, min_age_hours:, **)
229
231
  now = Time.now
230
232
  cutoff = now - (min_age_hours * 3600)
231
233
  entries = db[:apollo_entries].exclude(status: 'archived')
@@ -236,7 +238,7 @@ module Legion
236
238
  entries.order(:id).paged_each(rows_per_fetch: 500, strategy: :filter) do |entry|
237
239
  timestamp = entry[:updated_at] || entry[:created_at]
238
240
  age_days = [(now - timestamp.to_time) / 86_400.0, 1.0].max
239
- confidence = entry[:confidence].to_f * ((age_days / (age_days + 1.0))**alpha)
241
+ confidence = entry[:confidence].to_f * ((age_days / (age_days + 1.0))**cycle_alpha)
240
242
  updates = { confidence: confidence }
241
243
  if confidence < min_confidence
242
244
  updates[:status] = 'archived'
@@ -7,7 +7,7 @@ module Legion
7
7
  extend Legion::Extensions::Transport
8
8
 
9
9
  def self.additional_e_to_q
10
- [
10
+ bindings = [
11
11
  { from: Legion::Extensions::Apollo::Transport::Exchanges::Apollo,
12
12
  to: Legion::Extensions::Apollo::Transport::Queues::Ingest,
13
13
  routing_key: 'legion.apollo.ingest' },
@@ -19,11 +19,14 @@ module Legion
19
19
  routing_key: 'legion.apollo.writeback.store' },
20
20
  { from: Legion::Extensions::Apollo::Transport::Exchanges::Apollo,
21
21
  to: Legion::Extensions::Apollo::Transport::Queues::WritebackVectorize,
22
- routing_key: 'legion.apollo.writeback.vectorize' },
23
- { from: Legion::Extensions::Apollo::Transport::Exchanges::LlmAudit,
24
- to: Legion::Extensions::Apollo::Transport::Queues::GasSubscriber,
25
- routing_key: 'llm.audit.complete' }
22
+ routing_key: 'legion.apollo.writeback.vectorize' }
26
23
  ]
24
+ if Legion::Extensions::Apollo.settings[:gas][:enabled] == true
25
+ bindings << { from: Legion::Extensions::Apollo::Transport::Exchanges::LlmAudit,
26
+ to: Legion::Extensions::Apollo::Transport::Queues::GasSubscriber,
27
+ routing_key: 'llm.audit.complete' }
28
+ end
29
+ bindings
27
30
  end
28
31
  end
29
32
  end
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module Extensions
5
5
  module Apollo
6
- VERSION = '0.4.45'
6
+ VERSION = '0.4.50'
7
7
  end
8
8
  end
9
9
  end
@@ -78,6 +78,7 @@ module Legion
78
78
  mesh_export_limit: 100
79
79
  },
80
80
  gas: {
81
+ enabled: false,
81
82
  relate_confidence_gate: 0.7,
82
83
  synthesis_confidence_cap: 0.7,
83
84
  max_anticipations: 3,
@@ -109,6 +110,7 @@ module Legion
109
110
  types: %w[person service repository concept]
110
111
  },
111
112
  entity_watchdog: {
113
+ enabled: false,
112
114
  concept_keywords: [],
113
115
  types: %w[person service repository concept],
114
116
  detect_confidence: 0.5,
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ $LOADED_FEATURES << 'legion/extensions/actors/subscription' unless $LOADED_FEATURES.include?('legion/extensions/actors/subscription')
6
+ require 'legion/extensions/apollo/actors/gas_subscriber'
7
+
8
+ RSpec.describe Legion::Extensions::Apollo::Actor::GasSubscriber do
9
+ subject(:actor) { described_class.allocate }
10
+
11
+ before { allow(actor).to receive(:settings).and_return(gas: { enabled: false }) }
12
+
13
+ it 'does not prepare a consumer when GAS is disabled' do
14
+ expect(actor).not_to receive(:create_dedicated_channel)
15
+
16
+ expect(actor.prepare).to be_nil
17
+ end
18
+
19
+ it 'does not activate a consumer when GAS is disabled' do
20
+ expect(actor).not_to receive(:subscribe)
21
+
22
+ expect(actor.activate).to be_nil
23
+ end
24
+ end
@@ -239,10 +239,10 @@ RSpec.describe Legion::Extensions::Apollo::Api do
239
239
  RbConfig.ruby, '-Ilib', '-Ispec', '-e', http_script,
240
240
  chdir: File.expand_path('../../../..', __dir__), stdin_data: JSON.generate(requests: requests)
241
241
  )
242
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
243
- raise "HTTP identity process failed: #{stderr}\n#{stdout}" unless status.success? && line
242
+ marker = 'APOLLO_RESULT='
243
+ raise "HTTP identity process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
244
244
 
245
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
245
+ ApolloSpecOutput.parse(stdout)
246
246
  end
247
247
 
248
248
  it 'keeps anonymous, synthesized-system, and unmapped callers global-only despite forged ownership' do
@@ -65,9 +65,15 @@ RSpec.describe Legion::Extensions::Apollo::GaiaIntegration do
65
65
 
66
66
  describe 'entity watchdog workflow' do
67
67
  it 'reports missing canonical TaskLog instead of claiming a scan completed' do
68
+ watchdog = Legion::Extensions::Apollo::Runners::EntityWatchdog
69
+ allow(watchdog).to receive(:settings).and_return(
70
+ Legion::Extensions::Apollo.default_settings.merge(
71
+ entity_watchdog: Legion::Extensions::Apollo.default_settings[:entity_watchdog].merge(enabled: true)
72
+ )
73
+ )
68
74
  hide_const('Legion::Data::Model::TaskLog') if defined?(Legion::Data::Model::TaskLog)
69
75
 
70
- expect(Legion::Extensions::Apollo::Runners::EntityWatchdog.scan_and_ingest).to include(
76
+ expect(watchdog.scan_and_ingest).to include(
71
77
  success: false, error: 'task_log_not_available', ingested: 0
72
78
  )
73
79
  end
@@ -86,10 +86,10 @@ RSpec.describe 'Apollo corroboration persistence' do
86
86
  chdir: File.expand_path('../../../../..', __dir__),
87
87
  stdin_data: JSON.generate(entries: entries, memberships: memberships, identities: identities, runs: runs)
88
88
  )
89
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
90
- raise "Corroboration process failed: #{stderr}\n#{stdout}" unless status.success? && line
89
+ marker = 'APOLLO_RESULT='
90
+ raise "Corroboration process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
91
91
 
92
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
92
+ ApolloSpecOutput.parse(stdout)
93
93
  end
94
94
 
95
95
  it 'rejects other domains, inactive states, other content types, and dependent sources' do
@@ -2,6 +2,8 @@
2
2
 
3
3
  require 'spec_helper'
4
4
  require 'sequel'
5
+ require 'stringio'
6
+ require 'logger'
5
7
  require 'legion/extensions/apollo/runners/entity_watchdog'
6
8
 
7
9
  RSpec.describe Legion::Extensions::Apollo::Runners::EntityWatchdog do
@@ -9,9 +11,17 @@ RSpec.describe Legion::Extensions::Apollo::Runners::EntityWatchdog do
9
11
  let(:published) { [] }
10
12
 
11
13
  before do
14
+ allow(described_class).to receive(:settings).and_return(
15
+ Legion::Extensions::Apollo.default_settings.merge(
16
+ entity_watchdog: Legion::Extensions::Apollo.default_settings[:entity_watchdog].merge(enabled: true)
17
+ )
18
+ )
12
19
  db.create_table(:task_logs) do
13
20
  primary_key :id
14
21
  String :entry
22
+ String :access_scope, default: 'global'
23
+ Integer :identity_principal_id
24
+ Integer :identity_id
15
25
  DateTime :created_at
16
26
  end
17
27
  stub_const('Legion::Data::Model::TaskLog', Class.new(Sequel::Model(db[:task_logs])))
@@ -35,8 +45,79 @@ RSpec.describe Legion::Extensions::Apollo::Runners::EntityWatchdog do
35
45
  described_class.instance_variable_defined?(:@entity_watchdog_processed_hashes)
36
46
  end
37
47
 
38
- def log_entry(text, offset: 0)
39
- Legion::Data::Model::TaskLog.create(entry: text, created_at: Time.now - offset)
48
+ def log_entry(text, offset: 0, access_scope: 'global', identity_principal_id: nil, identity_id: nil)
49
+ Legion::Data::Model::TaskLog.create(entry: text, created_at: Time.now - offset,
50
+ access_scope: access_scope, identity_principal_id: identity_principal_id,
51
+ identity_id: identity_id)
52
+ end
53
+
54
+ def stub_process_identity(principal_id: 42, identity_id: 9)
55
+ stub_const('Legion::Identity', Module.new) unless defined?(Legion::Identity)
56
+ stub_const('Legion::Identity::Process', Class.new do
57
+ define_singleton_method(:db_principal_id) { principal_id }
58
+ define_singleton_method(:db_identity_id) { identity_id }
59
+ end)
60
+ end
61
+
62
+ it 'does not query task logs unless explicitly enabled' do
63
+ allow(described_class).to receive(:settings).and_return(Legion::Extensions::Apollo.default_settings)
64
+ log_entry('private task text')
65
+ expect(Legion::Data::Model::TaskLog).not_to receive(:where)
66
+
67
+ expect(described_class.scan_and_ingest).to include(success: true, ingested: 0, reason: :disabled)
68
+ expect(published).to be_empty
69
+ end
70
+
71
+ it 'filters task logs in SQL before fetching their text' do
72
+ stub_process_identity
73
+ log_entry('global entry')
74
+ log_entry('public entry', access_scope: 'public')
75
+ log_entry('owned by principal', access_scope: 'private', identity_principal_id: 42)
76
+ log_entry('owned by identity', access_scope: 'private', identity_id: 9)
77
+ log_entry('other user private', access_scope: 'private', identity_principal_id: 99)
78
+ log_entry('conflicting owner', access_scope: 'private', identity_principal_id: 99, identity_id: 9)
79
+ log_entry('other team', access_scope: 'team', identity_principal_id: 99)
80
+ sql_output = StringIO.new
81
+ db.loggers << Logger.new(sql_output)
82
+
83
+ task_logs = described_class.send(:entity_watchdog_recent_task_logs)
84
+
85
+ expect(task_logs).to match_array([
86
+ { text: 'global entry', access_scope: 'global', identity_principal_id: nil },
87
+ { text: 'public entry', access_scope: 'global', identity_principal_id: nil },
88
+ { text: 'owned by principal', access_scope: 'private', identity_principal_id: 42 },
89
+ { text: 'owned by identity', access_scope: 'private', identity_principal_id: 42 }
90
+ ])
91
+ query = sql_output.string.lines.find { |line| line.include?('SELECT') && line.include?('task_logs') }
92
+ expect(query).to match(/WHERE.*access_scope.*identity_principal_id.*identity_id/)
93
+ end
94
+
95
+ it 'queries only global and public logs when no process identity is available' do
96
+ hide_const('Legion::Identity::Process') if defined?(Legion::Identity::Process)
97
+ log_entry('global entry')
98
+ log_entry('private entry', access_scope: 'private', identity_principal_id: 42)
99
+
100
+ expect(described_class.send(:entity_watchdog_recent_task_logs)).to eq(
101
+ [{ text: 'global entry', access_scope: 'global', identity_principal_id: nil }]
102
+ )
103
+ end
104
+
105
+ it 'keeps entities from an owned private log private on lookup and publication' do
106
+ stub_process_identity
107
+ log_entry('private service note', access_scope: 'private', identity_principal_id: 42)
108
+ allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
109
+ .and_return(success: true, source: :llm,
110
+ entities: [{ name: 'private service', type: 'service', confidence: 0.95 }])
111
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
112
+ .and_return(success: true, entries: [], count: 0)
113
+
114
+ expect(described_class.scan_and_ingest).to include(success: true, ingested: 1)
115
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).to have_received(:retrieve_relevant)
116
+ .with(hash_including(requesting_principal_id: 42))
117
+ expect(published).to contain_exactly(hash_including(
118
+ content: 'Service: private service', access_scope: 'private',
119
+ identity_principal_id: 42
120
+ ))
40
121
  end
41
122
 
42
123
  it 'reports missing TaskLog storage instead of treating it as an empty scan' do
@@ -100,6 +100,26 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Expertise do
100
100
  expect(expertise_model.first.values).to include(agent_id: 'agent-1', domain: 'vault', entry_count: 1)
101
101
  end
102
102
 
103
+ it 'aggregates confidence and counts while preserving missing-domain and nil-confidence behavior' do
104
+ sql = []
105
+ logger = Object.new
106
+ logger.define_singleton_method(:info) { |statement| sql << statement }
107
+ database.loggers << logger
108
+
109
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'ruby', confidence: 0.8)
110
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'ruby', confidence: 0.6)
111
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: 'ruby', confidence: nil)
112
+ entry_model.create(source_agent: 'agent-1', knowledge_domain: nil, tags: '[]', confidence: 0.5)
113
+ entry_model.create(source_agent: nil, knowledge_domain: 'ruby', confidence: 1.0)
114
+
115
+ expect(runner.aggregate).to include(success: true, agents: 1, domains: 2)
116
+ ruby = expertise_model.first(agent_id: 'agent-1', domain: 'ruby')
117
+ expect(ruby.entry_count).to eq(3)
118
+ expect(ruby.proficiency).to be_within(0.000001).of(((0.8 + 0.6) / 3) * Math.log2(4))
119
+ expect(expertise_model.first(agent_id: 'agent-1', domain: 'general').entry_count).to eq(1)
120
+ expect(sql).to include(a_string_matching(/SELECT .*avg.*FROM .*apollo_entries.*GROUP BY/i))
121
+ end
122
+
103
123
  it 'returns zero counts for an empty canonical entry table' do
104
124
  expect(runner.aggregate).to include(success: true, agents: 0, domains: 0)
105
125
  end
@@ -4,25 +4,18 @@ require 'spec_helper'
4
4
  require 'legion/extensions/apollo/runners/gas'
5
5
 
6
6
  RSpec.describe Legion::Extensions::Apollo::Runners::Gas, 'anticipation phase' do
7
- it 'reports a completed mechanical process without fabricated anticipations when LLM is unavailable' do
7
+ it 'does not promote private audit content when the LLM is unavailable' do
8
8
  allow(Legion::LLM).to receive(:started?).and_return(false)
9
- allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
10
- .and_return(success: true, entities: [])
11
- knowledge = Module.new do
12
- def self.retrieve_relevant(**)
13
- { success: true, entries: [], count: 0 }
14
- end
15
-
16
- def self.handle_ingest(**)
17
- { success: true, entry_id: 7 }
18
- end
19
- end
20
- stub_const('Legion::Extensions::Apollo::Runners::Knowledge', knowledge)
9
+ allow(described_class).to receive(:settings).and_return(
10
+ Legion::Extensions::Apollo.default_settings.merge(gas: Legion::Extensions::Apollo.default_settings[:gas].merge(enabled: true))
11
+ )
12
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
21
13
 
22
14
  result = described_class.process(
23
- request_id: 'req-anticipate', messages: [{ content: 'question' }], response_content: 'observation'
15
+ request_id: 'req-anticipate', messages: [{ content: 'question' }], response_content: 'observation',
16
+ access_scope: 'private', identity_principal_id: 42, content_sanitized: true
24
17
  )
25
18
 
26
- expect(result).to include(success: true, phases_completed: 6, anticipations: 0)
19
+ expect(result).to include(success: true, phases_completed: 0, reason: 'llm_unavailable')
27
20
  end
28
21
  end
@@ -65,7 +65,7 @@ RSpec.describe 'Apollo GAS relation persistence' do
65
65
  end
66
66
  result = Legion::Extensions::Apollo::Runners::Gas.send(
67
67
  :gas_phase_deposit, facts: input[:facts], relations: input[:relations], synthesis: [],
68
- audit_event: { request_id: 'gas-regression' }
68
+ audit_event: { request_id: 'gas-regression', identity_principal_id: 42 }
69
69
  )
70
70
  puts "APOLLO_RESULT=#{::JSON.generate(result: result, relations: db[:apollo_relations].all)}"
71
71
  RUBY
@@ -77,14 +77,15 @@ RSpec.describe 'Apollo GAS relation persistence' do
77
77
  chdir: File.expand_path('../../../../..', __dir__),
78
78
  stdin_data: JSON.generate(entries: entries, facts: facts, relations: relations)
79
79
  )
80
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
81
- raise "GAS deposit process failed: #{stderr}\n#{stdout}" unless status.success? && line
80
+ marker = 'APOLLO_RESULT='
81
+ raise "GAS deposit process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
82
82
 
83
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
83
+ ApolloSpecOutput.parse(stdout)
84
84
  end
85
85
 
86
86
  it 'links successful deduplicated facts safely and continues after an independent relation write fails' do
87
- entry = { content_type: 'fact', status: 'candidate', access_scope: 'global', confidence: 0.5 }
87
+ entry = { content_type: 'fact', status: 'candidate', access_scope: 'private', identity_principal_id: 42,
88
+ confidence: 0.5 }
88
89
  entries = [entry.merge(id: 1, content: 'stored fact'), entry.merge(id: 2, content: 'target evidence'),
89
90
  entry.merge(id: 3, content: 'private evidence', access_scope: 'private', identity_principal_id: 99),
90
91
  entry.merge(id: 4, content: 'second fact')]
@@ -6,14 +6,20 @@ require 'legion/extensions/apollo/runners/gas'
6
6
  RSpec.describe Legion::Extensions::Apollo::Runners::Gas do
7
7
  let(:audit_event) do
8
8
  {
9
- request_id: 'req-1',
10
- messages: [{ role: :user, content: 'What is pgvector?' }],
11
- response_content: 'pgvector uses HNSW indexes.',
12
- routing: { provider: :test }
9
+ request_id: 'req-1',
10
+ messages: [{ role: :user, content: 'What is pgvector?' }],
11
+ response_content: 'pgvector uses HNSW indexes.',
12
+ routing: { provider: :test },
13
+ access_scope: 'private',
14
+ identity_principal_id: 42,
15
+ content_sanitized: true
13
16
  }
14
17
  end
15
18
 
16
19
  before do
20
+ allow(described_class).to receive(:settings).and_return(
21
+ Legion::Extensions::Apollo.default_settings.merge(gas: Legion::Extensions::Apollo.default_settings[:gas].merge(enabled: true))
22
+ )
17
23
  allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
18
24
  .and_return(success: true, entities: [{ name: 'pgvector', type: 'repository' }])
19
25
  end
@@ -24,50 +30,80 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Gas do
24
30
  expect(result).to include(success: true, phases_completed: 0, reason: 'no content')
25
31
  end
26
32
 
27
- it 'runs the mechanical pipeline and counts a successful deposit' do
28
- knowledge = Module.new do
29
- def self.retrieve_relevant(**)
30
- { success: true, entries: [], count: 0 }
31
- end
33
+ it 'does not process audit events by default' do
34
+ allow(described_class).to receive(:settings).and_return(Legion::Extensions::Apollo.default_settings)
35
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
32
36
 
33
- def self.handle_ingest(content:, **)
34
- { success: true, entry_id: content.hash }
35
- end
37
+ expect(described_class.process(**audit_event)).to include(success: true, phases_completed: 0, reason: 'disabled')
38
+ end
39
+
40
+ it 'rejects audit events without explicit private ownership and sanitized content' do
41
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
42
+
43
+ [audit_event.except(:identity_principal_id), audit_event.merge(access_scope: 'global'),
44
+ audit_event.except(:content_sanitized), audit_event.merge(response_content: 'Contact alice@example.com')].each do |event|
45
+ expect(described_class.process(**event)).to include(success: true, phases_completed: 0, reason: 'unsafe_audit_event')
36
46
  end
37
- stub_const('Legion::Extensions::Apollo::Runners::Knowledge', knowledge)
47
+ end
48
+
49
+ it 'does not deposit the raw response when the LLM is unavailable' do
38
50
  allow(Legion::LLM).to receive(:started?).and_return(false)
51
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
52
+
53
+ expect(described_class.process(**audit_event)).to include(success: true, phases_completed: 0, reason: 'llm_unavailable')
54
+ end
55
+
56
+ it 'stores clean derived facts privately and scopes semantic lookup to the caller' do
57
+ allow(Legion::LLM).to receive(:started?).and_return(true)
58
+ allow(described_class).to receive(:gas_llm_comprehend)
59
+ .and_return([{ content: 'HNSW is an approximate search index', content_type: :fact }])
60
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
61
+ .and_return(success: true, entries: [], count: 0)
62
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:handle_ingest)
63
+ .and_return(success: true, entry_id: 7)
39
64
 
40
65
  result = described_class.process(**audit_event)
41
66
 
42
- expect(result).to include(success: true, phases_completed: 6, facts: 1, entities: 1,
43
- relations: 0, synthesis: 0, anticipations: 0)
67
+ expect(result).to include(success: true, phases_completed: 6, facts: 1, anticipations: 0)
44
68
  expect(result[:deposited]).to include(deposited: 1, failed: 0, facts: 1)
69
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).to have_received(:retrieve_relevant)
70
+ .with(hash_including(requesting_principal_id: 42))
71
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).to have_received(:handle_ingest)
72
+ .with(hash_including(access_scope: 'private', identity_principal_id: 42,
73
+ content: 'HNSW is an approximate search index'))
74
+ end
75
+
76
+ it 'skips sensitive generated facts before lookup or deposit' do
77
+ allow(Legion::LLM).to receive(:started?).and_return(true)
78
+ allow(described_class).to receive(:gas_llm_comprehend)
79
+ .and_return([{ content: 'alice@example.com', content_type: :fact }])
80
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:retrieve_relevant)
81
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
82
+
83
+ expect(described_class.process(**audit_event)).to include(success: true, facts: 0)
45
84
  end
46
85
 
47
86
  it 'reports partial deposit failure without claiming success' do
48
- knowledge = Module.new do
49
- def self.retrieve_relevant(**)
50
- { success: true, entries: [], count: 0 }
51
- end
52
-
53
- def self.handle_ingest(**)
54
- { success: false, error: 'write rejected' }
55
- end
56
- end
57
- stub_const('Legion::Extensions::Apollo::Runners::Knowledge', knowledge)
58
- allow(Legion::LLM).to receive(:started?).and_return(false)
87
+ allow(Legion::LLM).to receive(:started?).and_return(true)
88
+ allow(described_class).to receive(:gas_llm_comprehend)
89
+ .and_return([{ content: 'HNSW is an approximate search index', content_type: :fact }])
90
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
91
+ .and_return(success: true, entries: [], count: 0)
92
+ allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:handle_ingest)
93
+ .and_return(success: false, error: 'write rejected')
59
94
 
60
95
  result = described_class.process(**audit_event)
61
96
 
62
- expect(result[:success]).to be false
63
- expect(result[:phases_completed]).to eq(6)
97
+ expect(result).to include(success: false, phases_completed: 6)
64
98
  expect(result[:deposited]).to include(deposited: 0, failed: 1)
65
99
  end
66
100
 
67
101
  it 'returns a structured failure when a dependency raises' do
68
102
  allow(Legion::Extensions::Apollo::Runners::Knowledge).to receive(:retrieve_relevant)
69
103
  .and_raise(IOError, 'retrieval unavailable')
70
- allow(Legion::LLM).to receive(:started?).and_return(false)
104
+ allow(Legion::LLM).to receive(:started?).and_return(true)
105
+ allow(described_class).to receive(:gas_llm_comprehend)
106
+ .and_return([{ content: 'HNSW is an approximate search index', content_type: :fact }])
71
107
 
72
108
  result = described_class.process(**audit_event)
73
109
 
@@ -4,26 +4,18 @@ require 'spec_helper'
4
4
  require 'legion/extensions/apollo/runners/gas'
5
5
 
6
6
  RSpec.describe Legion::Extensions::Apollo::Runners::Gas, 'synthesis phase' do
7
- it 'does not fabricate derivative entries from a single mechanical observation' do
7
+ it 'does not synthesize or deposit a mechanical observation' do
8
8
  allow(Legion::LLM).to receive(:started?).and_return(false)
9
- allow(Legion::Extensions::Apollo::Runners::EntityExtractor).to receive(:extract_entities)
10
- .and_return(success: true, entities: [])
11
- knowledge = Module.new do
12
- def self.retrieve_relevant(**)
13
- { success: true, entries: [], count: 0 }
14
- end
15
-
16
- def self.handle_ingest(**)
17
- { success: true, entry_id: 8 }
18
- end
19
- end
20
- stub_const('Legion::Extensions::Apollo::Runners::Knowledge', knowledge)
9
+ allow(described_class).to receive(:settings).and_return(
10
+ Legion::Extensions::Apollo.default_settings.merge(gas: Legion::Extensions::Apollo.default_settings[:gas].merge(enabled: true))
11
+ )
12
+ expect(Legion::Extensions::Apollo::Runners::Knowledge).not_to receive(:handle_ingest)
21
13
 
22
14
  result = described_class.process(
23
- request_id: 'req-synthesize', messages: [{ content: 'question' }], response_content: 'observation'
15
+ request_id: 'req-synthesize', messages: [{ content: 'question' }], response_content: 'observation',
16
+ access_scope: 'private', identity_principal_id: 42, content_sanitized: true
24
17
  )
25
18
 
26
- expect(result).to include(success: true, phases_completed: 6, facts: 1, synthesis: 0)
27
- expect(result[:deposited]).to include(synthesis: 0)
19
+ expect(result).to include(success: true, phases_completed: 0, reason: 'llm_unavailable')
28
20
  end
29
21
  end
@@ -117,10 +117,10 @@ RSpec.describe 'Apollo ingest transaction' do
117
117
  chdir: File.expand_path('../../../../..', __dir__),
118
118
  stdin_data: JSON.generate({ content: content, source_agent: source_agent, missing: missing }.merge(options))
119
119
  )
120
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
121
- raise "Ingest transaction process failed: #{stderr}\n#{stdout}" unless status.success? && line
120
+ marker = 'APOLLO_RESULT='
121
+ raise "Ingest transaction process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
122
122
 
123
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
123
+ ApolloSpecOutput.parse(stdout)
124
124
  end
125
125
 
126
126
  it 'commits the entry, expertise bookkeeping, and access log as one successful ingest' do
@@ -87,10 +87,10 @@ RSpec.describe 'Apollo knowledge access boundaries' do
87
87
  RbConfig.ruby, '-Ilib', '-Ispec', '-e', scope_script,
88
88
  chdir: File.expand_path('../../../../..', __dir__), stdin_data: JSON.generate(action: action, principal: principal)
89
89
  )
90
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
91
- raise "Scoped knowledge process failed: #{stderr}\n#{stdout}" unless status.success? && line
90
+ marker = 'APOLLO_RESULT='
91
+ raise "Scoped knowledge process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
92
92
 
93
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
93
+ ApolloSpecOutput.parse(stdout)
94
94
  end
95
95
 
96
96
  it 'keeps anonymous browse global-only while applying confidence and source exclusions' do
@@ -111,10 +111,10 @@ RSpec.describe 'Apollo service lifecycle mutations' do
111
111
  chdir: File.expand_path('../../../../..', __dir__),
112
112
  stdin_data: JSON.generate(operation: operation)
113
113
  )
114
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
115
- raise "Lifecycle process failed: #{stderr}\n#{stdout}" unless status.success? && line
114
+ marker = 'APOLLO_RESULT='
115
+ raise "Lifecycle process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
116
116
 
117
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
117
+ ApolloSpecOutput.parse(stdout)
118
118
  end
119
119
 
120
120
  it 'archives through HTTP with retained metadata and truthful repeat, missing, unavailable, and rollback outcomes' do
@@ -60,6 +60,22 @@ RSpec.describe Legion::Extensions::Apollo::Runners::Maintenance do
60
60
  expect(db[:apollo_entries][id: retained][:confidence]).to be_between(0.9, 1.0).exclusive
61
61
  expect(db[:apollo_entries][id: young]).to include(status: 'candidate', confidence: 0.01)
62
62
  end
63
+
64
+ it 'applies approximately one day of power-law decay across 24 hourly cycles' do
65
+ start_time = Time.now
66
+ initial_confidence = 0.5
67
+ entry_id = db[:apollo_entries].insert(
68
+ status: 'confirmed', confidence: initial_confidence, created_at: start_time - (8 * 86_400)
69
+ )
70
+
71
+ 24.times do |hour|
72
+ allow(Time).to receive(:now).and_return(start_time + (hour * 3600))
73
+ expect(host.run_decay_cycle).to include(success: true, decayed: 1, archived: 0)
74
+ end
75
+
76
+ expected = initial_confidence * ((8.0 / 9.0)**Legion::Extensions::Apollo.settings[:power_law_alpha])
77
+ expect(db[:apollo_entries][id: entry_id][:confidence]).to be_within(0.001).of(expected)
78
+ end
63
79
  end
64
80
  end
65
81
 
@@ -115,10 +115,10 @@ RSpec.describe 'Apollo reembedding and space isolation' do
115
115
  chdir: File.expand_path('../../../../..', __dir__),
116
116
  stdin_data: JSON.generate(entries: entries, **)
117
117
  )
118
- line = stdout.lines.find { |output| output.start_with?('APOLLO_RESULT=') }
119
- raise "Reembedding process failed: #{stderr}\n#{stdout}" unless status.success? && line
118
+ marker = 'APOLLO_RESULT='
119
+ raise "Reembedding process failed: #{stderr}\n#{stdout}" unless status.success? && stdout.include?(marker)
120
120
 
121
- JSON.parse(line.delete_prefix('APOLLO_RESULT='), symbolize_names: true)
121
+ ApolloSpecOutput.parse(stdout)
122
122
  end
123
123
 
124
124
  it 'regenerates legacy documents in resumable bounded batches without changing archived or known-space entries' do
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ unless defined?(Legion::Extensions::Transport)
6
+ module Legion
7
+ module Extensions
8
+ module Transport; end
9
+ end
10
+ end
11
+ end
12
+
13
+ require 'legion/extensions/apollo/transport'
14
+
15
+ RSpec.describe Legion::Extensions::Apollo::Transport do
16
+ describe '.additional_e_to_q' do
17
+ it 'omits the raw audit binding when GAS is disabled' do
18
+ allow(Legion::Extensions::Apollo).to receive(:settings).and_return(gas: { enabled: false })
19
+
20
+ expect(described_class.additional_e_to_q.map { |binding| binding[:routing_key] }).not_to include('llm.audit.complete')
21
+ end
22
+
23
+ it 'binds the audit queue when GAS is enabled' do
24
+ allow(Legion::Extensions::Apollo).to receive(:settings).and_return(gas: { enabled: true })
25
+
26
+ expect(described_class.additional_e_to_q).to include(
27
+ from: Legion::Extensions::Apollo::Transport::Exchanges::LlmAudit,
28
+ to: Legion::Extensions::Apollo::Transport::Queues::GasSubscriber,
29
+ routing_key: 'llm.audit.complete'
30
+ )
31
+ end
32
+ end
33
+ end
data/spec/spec_helper.rb CHANGED
@@ -12,6 +12,37 @@ require 'legion/transport'
12
12
  require 'sequel'
13
13
  require 'sequel/extensions/pg_array'
14
14
  require 'digest'
15
+ require 'json'
16
+
17
+ module ApolloSpecOutput
18
+ def self.parse(stdout)
19
+ payload = stdout.split('APOLLO_RESULT=', 2).last
20
+ depth = 0
21
+ in_string = false
22
+ escaped = false
23
+
24
+ payload.each_char.with_index do |character, index|
25
+ if in_string
26
+ if escaped
27
+ escaped = false
28
+ elsif character == '\\'
29
+ escaped = true
30
+ elsif character == '"'
31
+ in_string = false
32
+ end
33
+ elsif character == '"'
34
+ in_string = true
35
+ elsif ['{', '['].include?(character)
36
+ depth += 1
37
+ elsif ['}', ']'].include?(character)
38
+ depth -= 1
39
+ return ::JSON.parse(payload[0..index], symbolize_names: true) if depth.zero?
40
+ end
41
+ end
42
+
43
+ ::JSON.parse(payload, symbolize_names: true)
44
+ end
45
+ end
15
46
 
16
47
  module ApolloSpecEmbedding
17
48
  def self.result(vector: [1.0, 0.0], task: :document, model: 'test', provider: 'test', instance: 'test', **)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lex-apollo
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.45
4
+ version: 0.4.50
5
5
  platform: ruby
6
6
  authors:
7
7
  - Esity
@@ -249,6 +249,7 @@ files:
249
249
  - lib/legion/extensions/apollo/transport/queues/writeback_vectorize.rb
250
250
  - lib/legion/extensions/apollo/transport/subscription_delivery.rb
251
251
  - lib/legion/extensions/apollo/version.rb
252
+ - spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb
252
253
  - spec/legion/extensions/apollo/actors/ingest_spec.rb
253
254
  - spec/legion/extensions/apollo/actors/query_responder_spec.rb
254
255
  - spec/legion/extensions/apollo/api_spec.rb
@@ -288,6 +289,7 @@ files:
288
289
  - spec/legion/extensions/apollo/transport/messages/query_spec.rb
289
290
  - spec/legion/extensions/apollo/transport/messages/writeback_spec.rb
290
291
  - spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb
292
+ - spec/legion/extensions/apollo/transport_spec.rb
291
293
  - spec/spec_helper.rb
292
294
  homepage: https://github.com/LegionIO/lex-apollo
293
295
  licenses: