lex-apollo 0.4.44 → 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 +33 -0
  3. data/README.md +72 -14
  4. data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -41
  5. data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
  6. data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
  7. data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
  8. data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
  9. data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +4 -16
  10. data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
  11. data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
  12. data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
  13. data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
  14. data/lib/legion/extensions/apollo/api.rb +96 -41
  15. data/lib/legion/extensions/apollo/client.rb +20 -9
  16. data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
  17. data/lib/legion/extensions/apollo/helpers/capability.rb +10 -51
  18. data/lib/legion/extensions/apollo/helpers/confidence.rb +8 -52
  19. data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
  20. data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
  21. data/lib/legion/extensions/apollo/helpers/graph_query.rb +99 -43
  22. data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
  23. data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
  24. data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
  25. data/lib/legion/extensions/apollo/helpers/writeback.rb +64 -102
  26. data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
  27. data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
  28. data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
  29. data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +110 -0
  30. data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
  31. data/lib/legion/extensions/apollo/runners/gas.rb +87 -136
  32. data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
  33. data/lib/legion/extensions/apollo/runners/maintenance.rb +151 -64
  34. data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
  35. data/lib/legion/extensions/apollo/runners/request.rb +51 -46
  36. data/lib/legion/extensions/apollo/runners/search.rb +88 -0
  37. data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
  38. data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
  39. data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
  40. data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
  41. data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
  42. data/lib/legion/extensions/apollo/version.rb +1 -1
  43. data/lib/legion/extensions/apollo.rb +26 -24
  44. data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
  45. data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
  46. data/spec/legion/extensions/apollo/api_spec.rb +240 -8
  47. data/spec/legion/extensions/apollo/contradiction_spec.rb +28 -50
  48. data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
  49. data/spec/legion/extensions/apollo/helpers/capability_spec.rb +24 -27
  50. data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
  51. data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
  52. data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +108 -0
  53. data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
  54. data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
  55. data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
  56. data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +73 -74
  57. data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +32 -3
  58. data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
  59. data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
  60. data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
  61. data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +124 -0
  62. data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
  63. data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
  64. data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +23 -7
  65. data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
  66. data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -77
  67. data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
  68. data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +138 -6
  69. data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
  70. data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +314 -655
  71. data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +11 -2
  72. data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +33 -65
  73. data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
  74. data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
  75. data/spec/legion/extensions/apollo/runners/request_spec.rb +120 -98
  76. data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
  77. data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
  78. data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
  79. data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
  80. data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
  81. data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
  82. data/spec/spec_helper.rb +13 -15
  83. metadata +40 -14
  84. data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
  85. data/spec/legion/extensions/apollo/actors/contradiction_scanner_spec.rb +0 -38
  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 -39
  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,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,83 +5,139 @@ 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(relation_types: nil, **)
10
+ def graph_build_traversal_sql(relation_types: nil, requesting_principal_id: nil, **)
24
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
25
17
 
26
18
  <<~SQL
27
19
  WITH RECURSIVE graph AS (
28
20
  SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
29
- 0 AS depth, 1.0::float AS activation
21
+ 0 AS depth, CAST(1.0 AS double precision) AS activation
30
22
  FROM apollo_entries e
31
- WHERE e.id = :entry_id
23
+ WHERE e.id = :entry_id AND e.status != 'archived' #{visibility}
32
24
 
33
25
  UNION ALL
34
26
 
35
27
  SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
36
28
  g.depth + 1,
37
- (g.activation * :spread_factor * r.weight)::float
29
+ CAST(g.activation * :spread_factor * r.weight AS double precision)
38
30
  FROM graph g
39
31
  JOIN apollo_relations r ON r.from_entry_id = g.id #{type_filter}
40
32
  JOIN apollo_entries e ON e.id = r.to_entry_id
41
33
  WHERE g.depth < :depth
42
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
43
40
  )
44
- SELECT DISTINCT ON (id) id, content, content_type, confidence, tags, source_agent,
45
- depth, activation
46
- FROM graph
47
- 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
48
45
  SQL
49
46
  end
50
47
 
51
- def build_semantic_search_sql(statuses: nil, tags: nil, domain: nil, requesting_principal_id: nil, **)
52
- conditions = ['e.confidence >= :min_confidence']
53
- conditions << 'e.status IN :statuses' if statuses&.any?
54
- conditions << 'e.tags && CAST(:tags AS text[])' if tags&.any?
55
- conditions << 'e.knowledge_domain = :domain' if domain
56
-
57
- conditions << access_scope_sql if requesting_principal_id
48
+ def graph_build_semantic_search_sql(adapter: :postgres, **filters)
49
+ raise ArgumentError, "unsupported Apollo adapter: #{adapter}" unless %i[postgres sqlite].include?(adapter)
58
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'
59
70
  where_clause = conditions.join(' AND ')
60
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.
61
75
  <<~SQL
62
- SELECT e.id, e.content, e.content_type, e.confidence, e.tags, e.source_agent,
63
- e.access_count, e.created_at, e.knowledge_domain,
64
- (e.embedding <=> CAST(:embedding AS vector)) AS distance
65
- FROM apollo_entries e
66
- WHERE #{where_clause}
67
- AND e.embedding IS NOT NULL
68
- ORDER BY e.embedding <=> CAST(:embedding AS vector)
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
69
86
  LIMIT :limit
70
87
  SQL
71
88
  end
72
89
 
73
- def access_scope_sql
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'
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
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?
111
+ if tags&.any?
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
119
+ end
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)))'
122
+ end
123
+ conditions
124
+ end
125
+
126
+ def graph_access_scope_sql(qualified: false, global_only: false, **)
127
+ prefix = qualified ? 'e.' : ''
128
+ return "#{prefix}access_scope = 'global'" if global_only
129
+
74
130
  <<~SQL
75
- (access_scope = 'global'
76
- OR (access_scope = 'private'
77
- AND (identity_principal_id = :requesting_principal_id
78
- OR identity_id IN (SELECT id FROM identities WHERE principal_id = :requesting_principal_id)))
79
- OR (access_scope = 'team'
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'
80
136
  AND EXISTS (
81
137
  SELECT 1 FROM identity_group_memberships igm1
82
138
  JOIN identity_group_memberships igm2 ON igm1.group_id = igm2.group_id
83
139
  WHERE igm1.principal_id = :requesting_principal_id
84
- AND igm2.principal_id = identity_principal_id
140
+ AND igm2.principal_id = #{prefix}identity_principal_id
85
141
  )))
86
142
  SQL
87
143
  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
@@ -10,9 +10,9 @@ module Legion
10
10
  'node.js' => 'nodejs', 'vue.js' => 'vuejs', 'react.js' => 'reactjs'
11
11
  }.freeze
12
12
 
13
- module_function
13
+ private
14
14
 
15
- def normalize(raw)
15
+ def tag_normalize(raw:, **)
16
16
  tag = raw.to_s.strip.downcase
17
17
  tag = ALIASES[tag] if ALIASES.key?(tag)
18
18
  tag = tag.gsub(/[^a-z0-9\- ]/, '')
@@ -22,9 +22,9 @@ module Legion
22
22
  tag.empty? ? nil : tag
23
23
  end
24
24
 
25
- def normalize_all(tags, max: 5)
25
+ def tag_normalize_all(tags:, max: 5, **)
26
26
  Array(tags)
27
- .filter_map { |t| normalize(t) }
27
+ .filter_map { |tag| tag_normalize(raw: tag) }
28
28
  .uniq
29
29
  .first(max)
30
30
  end