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
@@ -1,69 +1,25 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/settings/helper'
4
+
3
5
  module Legion
4
6
  module Extensions
5
7
  module Apollo
6
8
  module Helpers
7
9
  module Confidence
8
- extend Legion::Logging::Helper
9
- extend Legion::Settings::Helper
10
+ include Legion::Settings::Helper
10
11
 
11
- INITIAL_CONFIDENCE = 0.5
12
- CORROBORATION_BOOST = 0.3
13
- RETRIEVAL_BOOST = 0.02
14
- POWER_LAW_ALPHA = 0.05
15
- DECAY_THRESHOLD = 0.05
16
- CORROBORATION_SIMILARITY_THRESHOLD = 0.9
17
- WRITE_CONFIDENCE_GATE = 0.6
18
- WRITE_NOVELTY_GATE = 0.3
19
- STALE_DAYS = 90
20
- DECAY_MIN_AGE_HOURS = 168
21
12
  CONTENT_TYPES = %i[fact concept procedure association observation].freeze
22
- STATUSES = %w[candidate confirmed disputed decayed archived].freeze
23
- RELATION_TYPES = %w[is_a has_a part_of causes similar_to contradicts supersedes depends_on].freeze
24
-
25
- module_function
26
-
27
- def initial_confidence = settings[:confidence][:initial]
28
- def corroboration_boost = settings[:confidence][:corroboration_boost]
29
- def retrieval_boost = settings[:confidence][:retrieval_boost]
30
- def power_law_alpha = settings[:power_law_alpha]
31
- def decay_threshold = settings[:decay_threshold]
32
- def write_confidence_gate = settings[:confidence][:write_gate]
33
- def write_novelty_gate = settings[:confidence][:novelty_gate]
34
- def stale_days = settings[:stale_days]
35
- def decay_min_age_hours = settings[:decay_min_age_hours]
36
-
37
- def corroboration_similarity_threshold
38
- settings[:confidence][:corroboration_similarity]
39
- end
40
-
41
- def apply_decay(confidence:, age_hours: nil, alpha: power_law_alpha, **)
42
- return confidence if age_hours && age_hours < decay_min_age_hours
13
+ RELATION_TYPES = %w[is_a has_a part_of causes similar_to contradicts supersedes depends_on supports_by extends].freeze
43
14
 
44
- if age_hours
45
- age_days = age_hours / 24.0
46
- [confidence * ((age_days.clamp(1, Float::INFINITY) + 1.0)**(-alpha)) / (age_days.clamp(1, Float::INFINITY)**(-alpha)), 0.0].max
47
- else
48
- factor = 1.0 / (1.0 + alpha)
49
- [confidence * factor, 0.0].max
50
- end
51
- end
52
-
53
- def apply_retrieval_boost(confidence:, **)
54
- [confidence + retrieval_boost, 1.0].min
55
- end
56
-
57
- def apply_corroboration_boost(confidence:, weight: 1.0, **)
58
- [confidence + (corroboration_boost * weight), 1.0].min
59
- end
15
+ private
60
16
 
61
- def decayed?(confidence:, **)
62
- confidence < decay_threshold
17
+ def confidence_apply_retrieval_boost(confidence:, **)
18
+ [confidence + settings[:confidence][:retrieval_boost], 1.0].min
63
19
  end
64
20
 
65
- def meets_write_gate?(confidence:, novelty:, **)
66
- confidence > write_confidence_gate && novelty > write_novelty_gate
21
+ def confidence_apply_corroboration_boost(confidence:, weight: 1.0, **)
22
+ [confidence + (settings[:confidence][:corroboration_boost] * weight), 1.0].min
67
23
  end
68
24
  end
69
25
  end
@@ -1,58 +1,42 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/data'
4
+
3
5
  module Legion
4
6
  module Extensions
5
7
  module Apollo
6
8
  module Helpers
7
9
  module DataModels
8
- class << self
9
- def apollo_entry
10
- namespaced_apollo_model(:Entry) || legacy_model(:ApolloEntry)
11
- end
12
-
13
- def apollo_relation
14
- namespaced_apollo_model(:Relation) || legacy_model(:ApolloRelation)
15
- end
10
+ private
16
11
 
17
- def apollo_access_log
18
- namespaced_apollo_model(:AccessLog) || legacy_model(:ApolloAccessLog)
19
- end
12
+ def data_model_entry
13
+ return unless defined?(Legion::Data::Model::Apollo::Entry)
20
14
 
21
- def apollo_expertise
22
- namespaced_apollo_model(:Expertise) || legacy_model(:ApolloExpertise)
23
- end
24
-
25
- def apollo_entry_available?
26
- !apollo_entry.nil?
27
- end
15
+ Legion::Data::Model::Apollo::Entry
16
+ end
28
17
 
29
- def apollo_relation_available?
30
- !apollo_relation.nil?
31
- end
18
+ def data_model_relation
19
+ return unless defined?(Legion::Data::Model::Apollo::Relation)
32
20
 
33
- def apollo_access_log_available?
34
- !apollo_access_log.nil?
35
- end
21
+ Legion::Data::Model::Apollo::Relation
22
+ end
36
23
 
37
- def apollo_expertise_available?
38
- !apollo_expertise.nil?
39
- end
24
+ def data_model_access_log
25
+ return unless defined?(Legion::Data::Model::Apollo::AccessLog)
40
26
 
41
- private
27
+ Legion::Data::Model::Apollo::AccessLog
28
+ end
42
29
 
43
- def namespaced_apollo_model(name)
44
- return nil unless defined?(Legion::Data::Model::Apollo)
45
- return nil unless Legion::Data::Model::Apollo.const_defined?(name, false)
30
+ def data_model_expertise
31
+ return unless defined?(Legion::Data::Model::Apollo::Expertise)
46
32
 
47
- Legion::Data::Model::Apollo.const_get(name, false)
48
- end
33
+ Legion::Data::Model::Apollo::Expertise
34
+ end
49
35
 
50
- def legacy_model(name)
51
- return nil unless defined?(Legion::Data::Model)
52
- return nil unless Legion::Data::Model.const_defined?(name, false)
36
+ def data_model_task_log
37
+ return unless defined?(Legion::Data::Model::TaskLog)
53
38
 
54
- Legion::Data::Model.const_get(name, false)
55
- end
39
+ Legion::Data::Model::TaskLog
56
40
  end
57
41
  end
58
42
  end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'legion/json'
5
+ require 'sequel'
6
+ require 'sequel/extensions/pg_json'
7
+
8
+ module Legion
9
+ module Extensions
10
+ module Apollo
11
+ module Helpers
12
+ module Embedding
13
+ class Error < StandardError; end
14
+ SPACE_FIELDS = %i[space_id provider model model_revision identity_source dimensions prefixes normalization].freeze
15
+
16
+ private
17
+
18
+ def embedding_parse_provenance(value:, **)
19
+ return nil if value.nil?
20
+
21
+ value = Legion::JSON.load(value) if value.is_a?(String)
22
+ value = value.to_h if value.is_a?(Sequel::Postgres::JSONHash) || value.is_a?(Sequel::Postgres::JSONBHash)
23
+ return nil unless value.is_a?(Hash)
24
+
25
+ value = value.transform_keys { |key| key.is_a?(String) ? key.to_sym : key }
26
+ if value[:prefixes].is_a?(Hash)
27
+ value[:prefixes] = value[:prefixes].transform_keys { |key| key.is_a?(String) ? key.to_sym : key }
28
+ end
29
+ value
30
+ rescue Legion::JSON::ParseError => e
31
+ handle_exception(e, level: :warn, operation: 'apollo.embedding.parse_provenance')
32
+ nil
33
+ end
34
+
35
+ # Fail forward across legion-llm releases: 0.16.9 returns flat routing
36
+ # fields without embedding_provenance. Derive the same space identity
37
+ # 0.16.10+ returns (key order and values mirror its embedding_identity)
38
+ # so vectors from both API shapes compare in one space.
39
+ def embedding_legacy_provenance(result:, task:, **)
40
+ vector = result[:vector]
41
+ provider = result[:provider].to_s
42
+ model = result[:model].to_s
43
+ instance = result[:instance].to_s
44
+ return nil unless vector.is_a?(Array) && !vector.empty?
45
+ return nil if provider.strip.empty? || model.strip.empty? || instance.strip.empty?
46
+
47
+ dimensions = result[:dimensions]
48
+ dimensions = vector.length unless dimensions.is_a?(Integer) && dimensions.positive?
49
+ identity = {
50
+ provider: provider,
51
+ model: model,
52
+ model_revision: nil,
53
+ identity_source: 'instance',
54
+ instance: instance,
55
+ dimensions: dimensions,
56
+ prefixes: { document: embedding_legacy_prefix(model: model, task: :document),
57
+ query: embedding_legacy_prefix(model: model, task: :query) },
58
+ normalization: 'none'
59
+ }
60
+ identity.merge(space_id: Digest::SHA256.hexdigest(Legion::JSON.dump(identity)), task: task.to_s)
61
+ end
62
+
63
+ # Registry semantics mirror legion-llm's prefix_for: the model base
64
+ # (before ':') keys the configured prefix registry; absent policies are ''.
65
+ def embedding_legacy_prefix(model:, task:, **)
66
+ llm = Legion::Settings[:llm]
67
+ embedding = llm[:embedding] if llm.is_a?(Hash)
68
+ registry = embedding[:prefix_registry] if embedding.is_a?(Hash)
69
+ registry = {} unless registry.is_a?(Hash)
70
+ base = model.to_s.split(':').first
71
+ model_prefixes = registry[base] || {}
72
+ (model_prefixes[task] || model_prefixes[task.to_s]).to_s
73
+ end
74
+
75
+ def embedding_valid?(vector:, provenance:, task: nil, **)
76
+ return false unless vector.is_a?(Array) && !vector.empty?
77
+ return false unless vector.all? { |value| value.is_a?(Numeric) && value.real? && value.finite? }
78
+ return false unless vector.any? { |value| !value.zero? }
79
+
80
+ parsed = embedding_parse_provenance(value: provenance)
81
+ embedding_provenance_valid?(provenance: parsed, task: task) && parsed[:dimensions] == vector.length
82
+ end
83
+
84
+ def embedding_compatible?(left:, right:, **)
85
+ left = embedding_parse_provenance(value: left)
86
+ right = embedding_parse_provenance(value: right)
87
+ return false unless embedding_provenance_valid?(provenance: left) && embedding_provenance_valid?(provenance: right)
88
+ return false unless SPACE_FIELDS.all? { |key| left[key] == right[key] }
89
+
90
+ left[:identity_source] == 'revision' || left[:instance] == right[:instance]
91
+ end
92
+
93
+ def embedding_provenance_valid?(provenance:, task: nil, **)
94
+ return false unless provenance.is_a?(Hash)
95
+ return false unless provenance[:space_id].is_a?(String) && provenance[:space_id].match?(/\A[0-9a-f]{64}\z/)
96
+ return false unless embedding_provenance_identity_valid?(provenance: provenance)
97
+ return false unless provenance[:dimensions].is_a?(Integer) && provenance[:dimensions].positive?
98
+ return false unless %w[document query].include?(provenance[:task]) && (!task || provenance[:task] == task.to_s)
99
+ return false unless provenance[:normalization] == 'none'
100
+
101
+ provenance[:prefixes].is_a?(Hash) && %i[document query].all? { |key| provenance[:prefixes][key].is_a?(String) }
102
+ end
103
+
104
+ def embedding_provenance_identity_valid?(provenance:, **)
105
+ return false unless %i[provider model instance].all? { |key| provenance[key].is_a?(String) && !provenance[key].strip.empty? }
106
+
107
+ revision = provenance[:model_revision]
108
+ case provenance[:identity_source]
109
+ when 'revision' then revision.is_a?(String) && !revision.strip.empty?
110
+ when 'instance' then provenance.key?(:model_revision) && revision.nil?
111
+ else false
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -5,100 +5,140 @@ module Legion
5
5
  module Apollo
6
6
  module Helpers
7
7
  module GraphQuery
8
- extend Legion::Settings::Helper
8
+ private
9
9
 
10
- SPREAD_FACTOR = 0.6
11
- DEFAULT_DEPTH = 2
12
- MIN_ACTIVATION = 0.1
13
-
14
- module_function
15
-
16
- def spread_factor = settings[:graph][:spread_factor]
17
- def default_depth = settings[:graph][:default_depth]
18
- def min_activation = settings[:graph][:min_activation]
19
-
20
- def default_query_limit = settings[:query][:default_limit]
21
- def default_query_min_confidence = settings[:query][:default_min_confidence]
22
-
23
- def build_traversal_sql(depth: default_depth, relation_types: nil, min_activation: self.min_activation, **)
24
- sf = spread_factor
25
- type_filter = if relation_types&.any?
26
- types = relation_types.map { |t| "'#{t}'" }.join(', ')
27
- "AND r.relation_type IN (#{types})"
28
- else
29
- ''
30
- end
10
+ def graph_build_traversal_sql(relation_types: nil, requesting_principal_id: nil, **)
11
+ type_filter = relation_types&.any? ? 'AND r.relation_type IN :relation_types' : ''
12
+ visibility = if requesting_principal_id
13
+ "AND #{graph_access_scope_sql(qualified: true, global_only: requesting_principal_id.zero?)}"
14
+ else
15
+ ''
16
+ end
31
17
 
32
18
  <<~SQL
33
19
  WITH RECURSIVE graph AS (
34
20
  SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
35
- 0 AS depth, 1.0::float AS activation
21
+ 0 AS depth, CAST(1.0 AS double precision) AS activation
36
22
  FROM apollo_entries e
37
- WHERE e.id = :entry_id
23
+ WHERE e.id = :entry_id AND e.status != 'archived' #{visibility}
38
24
 
39
25
  UNION ALL
40
26
 
41
27
  SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
42
28
  g.depth + 1,
43
- (g.activation * #{sf} * r.weight)::float
29
+ CAST(g.activation * :spread_factor * r.weight AS double precision)
44
30
  FROM graph g
45
31
  JOIN apollo_relations r ON r.from_entry_id = g.id #{type_filter}
46
32
  JOIN apollo_entries e ON e.id = r.to_entry_id
47
- WHERE g.depth < #{depth}
48
- AND g.activation * #{sf} * r.weight > #{min_activation}
33
+ WHERE g.depth < :depth
34
+ AND g.activation * :spread_factor * r.weight > :min_activation
35
+ AND e.status != 'archived' #{visibility}
36
+ ), ranked AS (
37
+ SELECT graph.*,
38
+ ROW_NUMBER() OVER (PARTITION BY id ORDER BY activation DESC, depth ASC) AS activation_rank
39
+ FROM graph
49
40
  )
50
- SELECT DISTINCT ON (id) id, content, content_type, confidence, tags, source_agent,
51
- depth, activation
52
- FROM graph
53
- ORDER BY id, activation DESC
41
+ SELECT id, content, content_type, confidence, tags, source_agent, depth, activation
42
+ FROM ranked
43
+ WHERE activation_rank = 1
44
+ ORDER BY id
54
45
  SQL
55
46
  end
56
47
 
57
- def build_semantic_search_sql(limit: default_query_limit, min_confidence: default_query_min_confidence,
58
- statuses: nil, tags: nil, domain: nil,
59
- requesting_principal_id: nil, **)
60
- conditions = ["e.confidence >= #{min_confidence}"]
48
+ def graph_build_semantic_search_sql(adapter: :postgres, **filters)
49
+ raise ArgumentError, "unsupported Apollo adapter: #{adapter}" unless %i[postgres sqlite].include?(adapter)
50
+
51
+ conditions = adapter == :postgres ? graph_semantic_postgres_conditions(**filters) : graph_semantic_sqlite_conditions(**filters)
52
+ conditions.push('e.confidence >= :min_confidence', 'e.embedding IS NOT NULL')
53
+ conditions << 'e.embedding_space_id = :embedding_space_id' if filters[:embedding_space_id]
54
+ conditions << 'e.embedding_dimensions = :embedding_dimensions' if filters[:embedding_dimensions]
55
+ conditions << 'e.knowledge_domain = :domain' if filters[:domain]
56
+ principal = filters[:requesting_principal_id]
57
+ conditions << graph_access_scope_sql(qualified: true, global_only: principal.zero?) if principal
58
+ if filters[:access_scope]
59
+ conditions << 'e.access_scope = :access_scope'
60
+ if filters[:access_scope].to_s != 'global'
61
+ conditions << if filters[:identity_principal_id].nil?
62
+ 'e.identity_principal_id IS NULL'
63
+ else
64
+ 'e.identity_principal_id = :identity_principal_id'
65
+ end
66
+ end
67
+ end
68
+ columns = 'e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent, ' \
69
+ 'e.access_count, e.created_at, e.knowledge_domain, e.access_scope, e.identity_principal_id'
70
+ where_clause = conditions.join(' AND ')
71
+
72
+ return "SELECT #{columns}, e.embedding, e.embedding_provenance FROM apollo_entries e WHERE #{where_clause}" if adapter == :sqlite
73
+
74
+ # Materialize the compatible space before pgvector evaluates a distance.
75
+ <<~SQL
76
+ WITH compatible AS MATERIALIZED (
77
+ SELECT #{columns}, e.embedding
78
+ FROM apollo_entries e
79
+ WHERE #{where_clause}
80
+ )
81
+ SELECT id, content, content_type, confidence, tags, source_agent,
82
+ access_count, created_at, knowledge_domain, access_scope, identity_principal_id,
83
+ (embedding <=> CAST(:embedding AS vector)) AS distance
84
+ FROM compatible
85
+ ORDER BY distance, id
86
+ LIMIT :limit
87
+ SQL
88
+ end
61
89
 
62
- if statuses&.any?
63
- status_list = statuses.map { |s| "'#{s}'" }.join(', ')
64
- conditions << "e.status IN (#{status_list})"
90
+ def graph_semantic_postgres_conditions(embedding_dimensions: nil, embedding_identity_source: nil,
91
+ statuses: nil, tags: nil, tag_match: :any, exclude_source_agents: [], **)
92
+ conditions = []
93
+ conditions << 'vector_dims(e.embedding) = :embedding_dimensions' if embedding_dimensions
94
+ if embedding_identity_source
95
+ instance_filter = embedding_identity_source == 'revision' ? " - 'instance'" : ''
96
+ conditions << "(e.embedding_provenance - 'task'#{instance_filter}) = CAST(:embedding_provenance AS jsonb)"
97
+ conditions << "e.embedding_provenance->>'task' = 'document'"
98
+ conditions << "jsonb_typeof(e.embedding_provenance->'instance') = 'string'"
99
+ conditions << "length(trim(e.embedding_provenance->>'instance')) > 0"
100
+ conditions << 'vector_norm(e.embedding) > 0'
65
101
  end
102
+ conditions << 'e.status = ANY(CAST(:statuses AS text[]))' if statuses&.any?
103
+ conditions << "e.tags #{tag_match.to_s == 'all' ? '@>' : '&&'} CAST(:tags AS text[])" if tags&.any?
104
+ conditions << '(e.source_agent IS NULL OR NOT (e.source_agent = ANY(CAST(:exclude_source_agents AS text[]))))' if exclude_source_agents&.any?
105
+ conditions
106
+ end
66
107
 
108
+ def graph_semantic_sqlite_conditions(statuses: nil, tags: nil, tag_match: :any, exclude_source_agents: [], **)
109
+ conditions = []
110
+ conditions << 'e.status IN (SELECT value FROM json_each(:statuses))' if statuses&.any?
67
111
  if tags&.any?
68
- tag_list = tags.map { |t| "'#{t}'" }.join(', ')
69
- conditions << "e.tags && ARRAY[#{tag_list}]::text[]"
112
+ conditions << if tag_match.to_s == 'all'
113
+ 'NOT EXISTS (SELECT 1 FROM json_each(:tags) wanted WHERE NOT EXISTS ' \
114
+ '(SELECT 1 FROM json_each(e.tags) stored WHERE stored.value = wanted.value))'
115
+ else
116
+ 'EXISTS (SELECT 1 FROM json_each(e.tags) stored ' \
117
+ 'WHERE stored.value IN (SELECT value FROM json_each(:tags)))'
118
+ end
70
119
  end
71
-
72
- conditions << "e.knowledge_domain = '#{domain}'" if domain
73
-
74
- if requesting_principal_id
75
- pid = requesting_principal_id.to_i
76
- conditions << <<~SCOPE_SQL.strip
77
- (e.access_scope = 'global'
78
- OR (e.access_scope = 'private'
79
- AND (e.identity_principal_id = #{pid}
80
- OR e.identity_id IN (SELECT id FROM identities WHERE principal_id = #{pid})))
81
- OR (e.access_scope = 'team'
82
- AND EXISTS (
83
- SELECT 1 FROM identity_group_memberships igm1
84
- JOIN identity_group_memberships igm2 ON igm1.group_id = igm2.group_id
85
- WHERE igm1.principal_id = #{pid}
86
- AND igm2.principal_id = e.identity_principal_id
87
- )))
88
- SCOPE_SQL
120
+ if exclude_source_agents&.any?
121
+ conditions << '(e.source_agent IS NULL OR e.source_agent NOT IN (SELECT value FROM json_each(:exclude_source_agents)))'
89
122
  end
123
+ conditions
124
+ end
90
125
 
91
- where_clause = conditions.join(' AND ')
126
+ def graph_access_scope_sql(qualified: false, global_only: false, **)
127
+ prefix = qualified ? 'e.' : ''
128
+ return "#{prefix}access_scope = 'global'" if global_only
92
129
 
93
130
  <<~SQL
94
- SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
95
- e.access_count, e.created_at, e.knowledge_domain,
96
- (e.embedding <=> :embedding) AS distance
97
- FROM apollo_entries e
98
- WHERE #{where_clause}
99
- AND e.embedding IS NOT NULL
100
- ORDER BY e.embedding <=> :embedding
101
- LIMIT #{limit}
131
+ (#{prefix}access_scope = 'global'
132
+ OR (#{prefix}access_scope = 'private'
133
+ AND (#{prefix}identity_principal_id = :requesting_principal_id
134
+ OR #{prefix}identity_id IN (SELECT id FROM identities WHERE principal_id = :requesting_principal_id)))
135
+ OR (#{prefix}access_scope = 'team'
136
+ AND EXISTS (
137
+ SELECT 1 FROM identity_group_memberships igm1
138
+ JOIN identity_group_memberships igm2 ON igm1.group_id = igm2.group_id
139
+ WHERE igm1.principal_id = :requesting_principal_id
140
+ AND igm2.principal_id = #{prefix}identity_principal_id
141
+ )))
102
142
  SQL
103
143
  end
104
144
  end
@@ -1,46 +1,55 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'confidence'
3
+ require 'legion/json'
4
4
 
5
5
  module Legion
6
6
  module Extensions
7
7
  module Apollo
8
8
  module Helpers
9
9
  module Similarity
10
- extend Legion::Logging::Helper
11
- extend Legion::JSON::Helper
12
-
13
- module_function
14
-
15
- def cosine_similarity(vec_a:, vec_b:, **)
16
- vec_a = parse_vector(vec_a)
17
- vec_b = parse_vector(vec_b)
18
- return 0.0 unless vec_a.is_a?(Array) && vec_b.is_a?(Array)
19
-
20
- dot = vec_a.zip(vec_b).sum { |x, y| x * y }
21
- mag_a = Math.sqrt(vec_a.sum { |x| x**2 })
22
- mag_b = Math.sqrt(vec_b.sum { |x| x**2 })
23
- return 0.0 if mag_a.zero? || mag_b.zero?
24
-
25
- dot / (mag_a * mag_b)
10
+ include Legion::Settings::Helper
11
+ include Legion::Logging::Helper
12
+ include Legion::JSON::Helper
13
+
14
+ private
15
+
16
+ def similarity_cosine(vec_a:, vec_b:, **)
17
+ left = similarity_parse_vector(vector: vec_a)
18
+ right = similarity_parse_vector(vector: vec_b)
19
+ return 0.0 unless left && right && left.length == right.length
20
+
21
+ scale_a = left.max_by(&:abs).abs
22
+ scale_b = right.max_by(&:abs).abs
23
+ return 0.0 if scale_a.zero? || scale_b.zero?
24
+
25
+ dot = mag_a = mag_b = 0.0
26
+ left.each_index do |index|
27
+ a = left[index].fdiv(scale_a)
28
+ b = right[index].fdiv(scale_b)
29
+ dot += a * b
30
+ mag_a += a * a
31
+ mag_b += b * b
32
+ end
33
+ (dot / Math.sqrt(mag_a * mag_b)).clamp(-1.0, 1.0)
26
34
  end
27
35
 
28
- def parse_vector(vec)
29
- return vec if vec.is_a?(Array)
30
- return nil unless vec.is_a?(String)
36
+ def similarity_parse_vector(vector:, **)
37
+ vector = json_parse(vector) if vector.is_a?(String)
38
+ return nil unless vector.is_a?(Array) && !vector.empty?
39
+ return nil unless vector.all? { |value| value.is_a?(Numeric) && value.real? && value.finite? }
31
40
 
32
- json_parse(vec)
33
- rescue StandardError => e
41
+ vector
42
+ rescue Legion::JSON::ParseError => e
34
43
  handle_exception(e, level: :warn, operation: 'apollo.similarity.parse_vector')
35
44
  nil
36
45
  end
37
46
 
38
- def above_corroboration_threshold?(similarity:, **)
39
- similarity >= Confidence::CORROBORATION_SIMILARITY_THRESHOLD
47
+ def similarity_above_corroboration_threshold?(similarity:, **)
48
+ similarity >= settings[:confidence][:corroboration_similarity]
40
49
  end
41
50
 
42
- def classify_match(similarity:, same_content_type: true, contradicts: false, **)
43
- if above_corroboration_threshold?(similarity: similarity) && same_content_type
51
+ def similarity_classify_match(similarity:, same_content_type: true, contradicts: false, **)
52
+ if similarity_above_corroboration_threshold?(similarity: similarity) && same_content_type
44
53
  contradicts ? :contradiction : :corroboration
45
54
  else
46
55
  :novel
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'sequel'
4
+ require 'sequel/extensions/pg_array'
5
+ require 'sequel/extensions/pg_json'
6
+ require 'legion/json'
7
+
8
+ module Legion
9
+ module Extensions
10
+ module Apollo
11
+ module Helpers
12
+ module Storage
13
+ private
14
+
15
+ def storage_serialize_tags(db:, tags:, **)
16
+ case db.database_type
17
+ when :postgres then Sequel.pg_array(Array(tags).map(&:to_s), :text)
18
+ when :sqlite then Legion::JSON.dump(Array(tags).map(&:to_s))
19
+ else raise ArgumentError, "unsupported Apollo adapter: #{db.database_type}"
20
+ end
21
+ end
22
+
23
+ def storage_serialize_embedding(db:, vector:, **)
24
+ return nil if vector.nil?
25
+
26
+ case db.database_type
27
+ when :postgres then "[#{vector.join(',')}]"
28
+ when :sqlite then Legion::JSON.dump(vector)
29
+ else raise ArgumentError, "unsupported Apollo adapter: #{db.database_type}"
30
+ end
31
+ end
32
+
33
+ def storage_serialize_provenance(db:, provenance:, **)
34
+ return nil if provenance.nil?
35
+
36
+ case db.database_type
37
+ when :postgres then Sequel.pg_jsonb(provenance)
38
+ when :sqlite then Legion::JSON.dump(provenance)
39
+ else raise ArgumentError, "unsupported Apollo adapter: #{db.database_type}"
40
+ end
41
+ end
42
+
43
+ def storage_deserialize_tags(tags:, **)
44
+ return [] if tags.nil? || tags == '{}'
45
+ return tags.to_a if tags.respond_to?(:to_ary)
46
+
47
+ parsed = Legion::JSON.load(tags)
48
+ raise ArgumentError, 'stored Apollo tags must be an array' unless parsed.is_a?(Array)
49
+
50
+ parsed
51
+ end
52
+
53
+ def storage_filter_tags(dataset:, tags:, tag_match: :any, **)
54
+ return dataset if tags.nil? || tags.empty?
55
+
56
+ values = storage_serialize_tags(db: dataset.db, tags: tags)
57
+ if dataset.db.database_type == :postgres
58
+ operator = tag_match.to_s == 'all' ? '@>' : '&&'
59
+ return dataset.where(Sequel.lit("tags #{operator} CAST(? AS text[])", values))
60
+ end
61
+
62
+ predicate = if tag_match.to_s == 'all'
63
+ 'NOT EXISTS (SELECT 1 FROM json_each(?) wanted WHERE NOT EXISTS ' \
64
+ '(SELECT 1 FROM json_each(tags) stored WHERE stored.value = wanted.value))'
65
+ else
66
+ 'EXISTS (SELECT 1 FROM json_each(tags) stored ' \
67
+ 'WHERE stored.value IN (SELECT value FROM json_each(?)))'
68
+ end
69
+ dataset.where(Sequel.lit(predicate, values))
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end