Module: Legion::Apollo::Local

Extended by:
Logging::Helper
Defined in:
lib/legion/apollo/local.rb,
lib/legion/apollo/local/graph.rb

Overview

Node-local knowledge store backed by SQLite + FTS5. Mirrors Legion::Apollo’s public API but stores locally.

Defined Under Namespace

Modules: Graph

Constant Summary collapse

MIGRATION_PATH =

rubocop:disable Metrics/ModuleLength

File.expand_path('local/migrations', __dir__).freeze
LIFECYCLE_MUTEX =
Mutex.new
WRITE_MUTEX =
Mutex.new
SEED_MUTEX =
Mutex.new
HYDRATION_MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.graphObject



138
139
140
# File 'lib/legion/apollo/local.rb', line 138

def graph
  Legion::Apollo::Local::Graph
end

.hydrate_from_globalObject



225
226
227
228
229
230
231
232
# File 'lib/legion/apollo/local.rb', line 225

def hydrate_from_global
  return { success: false, error: :not_started } unless started?

  HYDRATION_MUTEX.synchronize { hydrate_from_global_without_lock }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.hydrate_from_global')
  { success: false, error: e.message }
end

.ingest(content:, tags: [], **opts) ⇒ Object

rubocop:disable Metrics/MethodLength



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/legion/apollo/local.rb', line 49

def ingest(content:, tags: [], **opts) # rubocop:disable Metrics/MethodLength
  return not_started_error unless started?

  tags = normalize_tags_input(tags)
  WRITE_MUTEX.synchronize do
    ingest_without_lock(content: content, tags: tags, **opts)
  end
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.ingest',
    tags:           Array(tags).size,
    source_channel: opts[:source_channel]
  )
  { success: false, error: e.message }
end

.promote_to_global(tags:, min_confidence: 0.6) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/legion/apollo/local.rb', line 180

def promote_to_global(tags:, min_confidence: 0.6) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  return { success: false, error: :not_started } unless started?

  tags = normalize_tags_input(tags)
  entries = query_by_tags(tags: tags)
  unless entries[:success] && entries[:results]&.any?
    log.info { "Apollo::Local promote_to_global skipped tag_count=#{tags.size} reason=no_entries" }
    return { success: true, promoted: 0 }
  end

  promoted = 0
  entries[:results].each do |entry|
    next if entry[:confidence].to_f < min_confidence

     = parse_tags(entry[:tags])
    hostname = begin
      ::Socket.gethostname
    rescue StandardError => e
      handle_exception(e, level: :debug, operation: 'apollo.local.resolve_hostname')
      'unknown'
    end
    result = Legion::Apollo.ingest(
      content:        entry[:content],
      tags:            + ['promoted_from_local'],
      source_channel: 'local_promotion',
      submitted_by:   "node:#{hostname}",
      confidence:     entry[:confidence],
      scope:          :global
    )
    promoted += 1 if result[:success]
  end

  log.info { "Apollo::Local promote_to_global completed promoted=#{promoted} tag_count=#{tags.size}" }
  { success: true, promoted: promoted }
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.promote_to_global',
    tag_count:      tags.size,
    min_confidence: min_confidence
  )
  { success: false, error: e.message }
end

.query(text:, limit: nil, min_confidence: nil, tags: nil, **opts) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/legion/apollo/local.rb', line 94

def query(text:, limit: nil, min_confidence: nil, tags: nil, **opts) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity
  return not_started_error unless started?

  text = normalize_text_input(text)
  tags = normalize_tags_input(tags)
  limit ||= local_setting(:default_limit, 5)
  min_confidence ||= local_setting(:min_confidence, 0.3)
  multiplier = local_setting(:fts_candidate_multiplier, 3)
  log.info do
    "Apollo::Local query executing text_length=#{text.to_s.length} " \
      "limit=#{limit} min_confidence=#{min_confidence} tag_count=#{Array(tags).size}"
  end
  log.debug { "Apollo::Local query limit=#{limit} min_confidence=#{min_confidence} tags=#{Array(tags).size}" }

  candidates = fts_search(text, limit: limit * multiplier)
  include_inferences = opts.fetch(:include_inferences, true)
  include_history = opts.fetch(:include_history, false)
  candidates = filter_candidates(candidates, min_confidence: min_confidence, tags: tags,
                                             include_inferences: include_inferences,
                                             include_history: include_history)
  candidates = cosine_rerank(text, candidates) if can_rerank?
  results = candidates.first(limit)

  tier = opts[:tier]
  results = results.map { |r| project_tier(r, tier) } if tier

  log.info { "Apollo::Local query completed count=#{results.size}" }
  { success: true, results: results, count: results.size, mode: :local, tier: tier }
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.query',
    limit:          limit,
    min_confidence: min_confidence,
    tag_count:      Array(tags).size
  )
  { success: false, error: e.message }
end

.query_by_tags(tags:, limit: 50) ⇒ Object

rubocop:disable Metrics/MethodLength



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/legion/apollo/local.rb', line 161

def query_by_tags(tags:, limit: 50) # rubocop:disable Metrics/MethodLength
  return { success: false, error: :not_started } unless started?

  tags = normalize_tags_input(tags)
  results = query_by_tags_via_sql(tags: tags, limit: limit)

  log.info { "Apollo::Local query_by_tags completed tag_count=#{tags.size} count=#{results.size}" }
  { success: true, results: results, count: results.size }
rescue StandardError => e
  handle_exception(
    e,
    level:     :error,
    operation: 'apollo.local.query_by_tags',
    tag_count: tags.size,
    limit:     limit
  )
  { success: false, error: e.message }
end

.reset!Object



142
143
144
145
146
147
# File 'lib/legion/apollo/local.rb', line 142

def reset!
  LIFECYCLE_MUTEX.synchronize do
    @started = false
    @seeded = false
  end
end

.retrieve(text:, limit: 5) ⇒ Object



134
135
136
# File 'lib/legion/apollo/local.rb', line 134

def retrieve(text:, limit: 5, **)
  query(text: text, limit: limit, **)
end

.seed_self_knowledgeObject



149
150
151
152
153
154
155
# File 'lib/legion/apollo/local.rb', line 149

def seed_self_knowledge
  return unless started?

  SEED_MUTEX.synchronize { seed_self_knowledge_without_lock }
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'apollo.local.seed_self_knowledge')
end

.seeded?Boolean

Returns:

  • (Boolean)


157
158
159
# File 'lib/legion/apollo/local.rb', line 157

def seeded?
  @seeded == true
end

.shutdownObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/legion/apollo/local.rb', line 33

def shutdown
  LIFECYCLE_MUTEX.synchronize do
    @started = false
    @seeded = false
    log.info 'Legion::Apollo::Local shutdown'
  end
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'apollo.local.shutdown')
  @started = false
  @seeded = false
end


259
260
261
262
263
264
265
266
267
# File 'lib/legion/apollo/local.rb', line 259

def source_links_for(entry_id:)
  return not_started_error unless started?

  links = db[:local_source_links].where(entry_id: entry_id).all
  { success: true, links: links, count: links.size }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.source_links_for', entry_id: entry_id)
  { success: false, error: e.message }
end

.startObject



26
27
28
29
30
31
# File 'lib/legion/apollo/local.rb', line 26

def start
  LIFECYCLE_MUTEX.synchronize { start_without_lock }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.start')
  @started = false
end

.started?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/legion/apollo/local.rb', line 45

def started?
  @started == true
end

.upsert(content:, tags: [], **opts) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/legion/apollo/local.rb', line 67

def upsert(content:, tags: [], **opts) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize
  return not_started_error unless started?

  sorted_tags = normalize_tags_input(tags).sort
  tag_json = Legion::JSON.dump(sorted_tags)
  WRITE_MUTEX.synchronize do
    existing = db[:local_knowledge].where(tags: tag_json).first

    if existing
      update_upsert_entry(existing, content, tag_json, opts)
    else
      result = ingest_without_lock(content: content, tags: sorted_tags, **opts)
      result[:mode] = :inserted if result[:success] && result[:mode] != :deduplicated
      result
    end
  end
rescue StandardError => e
  handle_exception(
    e,
    level:          :warn,
    operation:      'apollo.local.upsert',
    tags:           Array(tags).size,
    source_channel: opts[:source_channel]
  )
  { success: false, error: e.message }
end

.version_chain(entry_id:, max_depth: 50) ⇒ Object

rubocop:disable Metrics/MethodLength



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/legion/apollo/local.rb', line 234

def version_chain(entry_id:, max_depth: 50) # rubocop:disable Metrics/MethodLength
  return not_started_error unless started?

  chain = []
  current_id = entry_id
  seen = Set.new

  max_depth.times do
    break unless current_id
    break if seen.include?(current_id)

    seen.add(current_id)
    row = db[:local_knowledge].where(id: current_id).first
    break unless row

    chain << row
    current_id = row[:parent_knowledge_id]
  end

  { success: true, chain: chain, count: chain.size }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.version_chain', entry_id: entry_id)
  { success: false, error: e.message }
end