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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b3132a716f6bac3837f9532c674d4d10aaa20326dae47bb2465ad8c3339702ce
4
- data.tar.gz: 467ad8bb7e6a6851197d5b4f6ef9bf09b24b60d497e57eba821cabf47763f2e4
3
+ metadata.gz: 86765125810bd126d5043a809268ed63bfac8f0653f3c443254c9351b8ad3e08
4
+ data.tar.gz: b841162c108cd4ca7e77a32a54735d7dc3e24d2826b3efe65f63ca2edef0f0d0
5
5
  SHA512:
6
- metadata.gz: 006cd9c4e3523f36e0077347546fd8a13934076209773bb8df796f8c04d5cdc2904d0e3431e1856bbb0a186eaaca8335eda9a3ba92f946e44eb7d88cea94a9a9
7
- data.tar.gz: c067bfb41d203f00d75cd92e7c64017f77e0065f76fcdbf8dc08621ed0a5d14bc10d0a5c338ab47df3e665bd8471162e88cbfa6d888c4427995d66941e90e083
6
+ metadata.gz: 7cde23c3ada440beadb9ff1db3e31906b8c50d7599416be0cfb289aad48a57b748a054919da2885c44120432085cea6ff5f62700b6c6c07932e44fb16f06f1a2
7
+ data.tar.gz: 1cf0063385d073236388353e46d1d0be72cd6fa4f6cc0b2236d7f019008e1715ebfdbe8d8680b9acaa89650c0358949f4e35f6900c90642dbe1d1526d78cd5b3
data/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.45] - 2026-10-30
4
+
5
+ ### Fixed
6
+ - Enforce caller scope on HTTP reads, deprecation, and every traversal hop; reject inaccessible seeds and hidden bridges, omit archived graph entries, and export only global confirmed mesh knowledge.
7
+ - Resolve HTTP ownership from authenticated framework principals, not request-body identity fields or receiving-process identity. Preserve explicit producer ownership and provenance through ingestion and writeback-store decoding; reject ownerless private/team writes.
8
+ - Restrict content-hash deduplication and race recovery to the same scope and private/team owner, preventing cross-owner IDs or confidence updates.
9
+ - Add `tag_match: :all` for conjunctive conversation tags while retaining default `:any`; apply confidence and source-agent exclusions to semantic queries, retrieval, and browse fallback.
10
+ - Dispatch canonical `legion.apollo` query/retrieve/traverse requests to the correct handlers and publish correlated, confirmed RabbitMQ replies. Preserve reply routing across retries and propagate unroutable, rejected, or timed-out publications.
11
+ - Preserve request filters, source metadata, and supplied embeddings on the wire; keep domain `content_type` in the JSON body without overriding the AMQP JSON content type.
12
+ - Use the released transport keyword envelope callback and reliable publisher for ingest/writeback. Preserve encrypted wire payloads and IV metadata, reject unaccepted publication without spooling, and support the in-process transport without database access.
13
+ - Request query embeddings for search and document embeddings for ingestion.
14
+ - Repair the writeback vectorizer's actual subscription receiver, reject failed generation/ingestion/publication, preserve source context and embedding provenance, and discard inbound routing metadata before forwarding to the store queue. Mandatory returns and bounded publisher confirms reach retry handling.
15
+ - Support SQLite JSON vectors/tags/provenance and native PostgreSQL vectors with portable traversal and SQLite decay; keep native entry IDs and matching query filters on both backends.
16
+ - Enforce embedding-space, model/revision, dimension, paired-prefix, and normalization compatibility before similarity, corroboration, or contradiction checks. Decode native PostgreSQL JSONB provenance and regenerate unknown legacy/precomputed document vectors instead of fabricating model identity.
17
+ - Dispatch GAS deposits and semantic lookups through callable Knowledge runner methods.
18
+ - Resolve unpublished companion dependencies before PR checks install the bundle, using exact commits and automatically returning to published gems when available. Preserve both Ruby test versions, full lint/security checks, and uploaded RSpec results without lowering runtime dependency floors.
19
+ - Keep actors limited to scheduling and delivery management; move expertise aggregation, entity-watchdog scanning, and contradiction workflows into runners, and keep utility helpers private and concern-prefixed.
20
+ - Reject failed ingest and writeback-store deliveries into bounded retries and dead-lettering instead of acknowledging unsuccessful runner results. Preserve correlated RPC retries without depending on the host task dispatcher's success envelope.
21
+ - Return explicit failures for unavailable models, semantic embedding errors, and failed GAS phases instead of reporting empty successful results. Read watchdog text from `TaskLog.entry`, retain failed texts for retry, and report accepted partial publications.
22
+ - Count distinct agents in expertise coverage and retain separate agent/domain groups even when identifiers contain colons.
23
+ - Accept both published legion-llm 0.16.9 flat embedding results and 0.16.10+ provenance results: flat results derive a stable deterministic space identity (instance-sourced `space_id`, mirroring the 0.16.10 identity fields) so semantic search and space-compatibility checks work on either release, and spaces carry over unchanged across the upgrade when the underlying identity does not.
24
+ - Parse the writeback integration specs' `APOLLO_RESULT=` payload to end of output instead of a single line, so the checks survive pretty-printed JSON dumps.
25
+
26
+ ### Added
27
+ - Add bounded `Maintenance.reembed_entries` for legacy backfill and model/dimension migration, with resumable cursors, truthful partial failures, and unchanged content/hash/ownership/status.
28
+
29
+ ### Changed
30
+ - Require `legion-transport >= 1.4.31` for the published keyword envelope API and fail-closed encryption contract.
31
+ - Use keyword-only arguments for Apollo-owned methods changed in this release and discard unused keywords with `**`; preserve required positional framework callbacks while dropping extra keywords before superclass dispatch.
32
+ - Require `legion-data >= 1.10.29` (migration 139) and `legion-llm >= 0.16.9` for ownership-scoped hash uniqueness and durable embedding provenance. The original content hash remains unchanged; published mainline migrations 137 and 138 remain untouched.
33
+ - Embedding routing remains solely owned by `legion-llm`; remove obsolete Apollo provider/model settings. Core-client legacy wire migration and synchronous remote retrieval remain outside this server release.
34
+ - Load standalone runners with their declared native dependencies, without adding LegionIO as a runtime or development dependency. Preserve the existing writeback helper entry points until their separate caller migration.
35
+
3
36
  ## [0.4.44] - 2026-10-30
4
37
 
5
38
  ### Fixed
data/README.md CHANGED
@@ -1,15 +1,15 @@
1
1
  # lex-apollo
2
2
 
3
- Shared durable knowledge store for the GAIA cognitive mesh. Agents publish confirmed knowledge via RabbitMQ; a dedicated Apollo service persists to PostgreSQL+pgvector. Supports semantic search, concept graph traversal, and expertise tracking.
3
+ Shared durable knowledge store for the GAIA cognitive mesh. Agents publish confirmed knowledge via RabbitMQ; a dedicated Apollo service persists to PostgreSQL+pgvector or SQLite. Supports semantic search, concept graph traversal, and expertise tracking.
4
4
 
5
5
  ## Overview
6
6
 
7
7
  `lex-apollo` operates in two modes:
8
8
 
9
- - **Client mode**: Any agent loads this gem and calls runners. Runners publish to RabbitMQ — no direct database access required.
10
- - **Service mode**: A dedicated Apollo process runs the actors, subscribes to queues, generates embeddings, and writes to PostgreSQL+pgvector.
9
+ - **Client mode**: Load this gem without LegionIO. `Client` executes against loaded local models or returns action payloads where supported; `Runners::Request` handles broker publication when no local service is available.
10
+ - **Service mode**: A dedicated Apollo process runs the actors, subscribes to queues, generates embeddings, and writes to PostgreSQL+pgvector or SQLite.
11
11
 
12
- The backing store is Azure Database for PostgreSQL Flexible Server with the pgvector extension.
12
+ PostgreSQL uses native vector distance; SQLite stores JSON vectors and computes exact similarity over eligible rows, keeping bounded top-k results without limiting the candidate set before ranking. Both backends enforce the same ownership, filter, provenance, and traversal boundaries.
13
13
 
14
14
  ## Installation
15
15
 
@@ -25,10 +25,11 @@ gem 'lex-apollo'
25
25
 
26
26
  ```ruby
27
27
  require 'legion/extensions/apollo'
28
+ require 'legion/extensions/apollo/client'
28
29
 
29
30
  client = Legion::Extensions::Apollo::Client.new
30
31
 
31
- # Build a store payload (published to RabbitMQ for the Apollo service to persist)
32
+ # Store locally, or build a payload when no Entry model is loaded
32
33
  client.store_knowledge(
33
34
  content: 'BGP route reflectors reduce full-mesh IBGP complexity',
34
35
  content_type: :fact,
@@ -98,24 +99,76 @@ Startup explicitly binds the ingest, query, writeback-store, and writeback-vecto
98
99
 
99
100
  Automatic writeback checks research tool calls in `Legion::LLM::Inference::Response#tools`, accepting typed tools and symbol/string-keyed hashes. Existing response `tool_calls` and enrichment-based tool history remain supported. Responses must meet the configured minimum content length; Apollo context alone does not qualify a response for capture.
100
101
 
102
+ ### Service Request Contract
103
+
104
+ The canonical exchange is `legion.apollo`, routing key `legion.apollo.query`. Requests use `action: "query"`, `"retrieve"`, or `"traverse"`; query text is the `query` field. Omitted action defaults to `query`. `Runners::Request.query` and `.retrieve` accept Ruby `text:` and translate it to the wire field. This release does not bridge the core client's older `apollo` exchange or `text` payload.
105
+
106
+ RabbitMQ callers supply `reply_to` and `correlation_id` as AMQP properties (body fields are accepted when properties are absent). Replies contain the actual Knowledge result, use the default exchange and supplied queue, and retain correlation. Unsupported actions and invalid request fields receive structured errors. Reply publication uses mandatory routing and publisher confirms; failure reaches subscription retry handling, preserving reply metadata. Requests without `reply_to` remain fire-and-forget; `Request` returns dispatch status, not a synchronous remote result.
107
+
108
+ Search/retrieval accept `status`, `tags`, `domain`, `min_confidence`, `exclude_source_agents`, and `tag_match`. The default `tag_match: :any` means tag overlap. Use `tag_match: :all` with both `llm_conversation_history` and the conversation-specific tag to isolate one conversation. Filtering also applies to chronological browse fallback. Search uses embedding task `:query`; ingestion uses `:document`.
109
+
110
+ ### Ownership Boundaries
111
+
112
+ HTTP reads and deprecation derive the database principal from authenticated `legion.auth` / `legion.principal` middleware state. JSON identity fields are not trusted. Anonymous or unmapped callers see only global entries; private/team ingestion requires a resolved owner. Authentication middleware must populate those environment values before mounting this standalone API. Statistics retain their existing global aggregate behavior.
113
+
114
+ Broker producers are trusted to supply database principal IDs. Missing or null request principals mean global-only visibility, and missing ingestion ownership stays null rather than becoming the receiving service's identity. Producer scope, identity, provenance, context, and supplied embeddings survive ingestion and writeback-store decoding. Direct internal Knowledge calls retain their existing nil-principal/process-identity semantics.
115
+
116
+ Traversal checks the seed and every hop: inaccessible and archived nodes cannot bridge into visible results. Mesh export includes only global confirmed entries. Migration 139 scopes active content-hash uniqueness to access scope and private/team owner; identical content may belong to different owners without rewriting its hash. Global entries share one global hash boundary. Archived copies are excluded from uniqueness.
117
+
118
+ ### Embedding Compatibility and Migration
119
+
120
+ Deploy `legion-data >= 1.10.29` and `legion-llm >= 0.16.10`, then apply data migration 139 before starting this service version. Existing active/archive content, hashes, IDs, owners, and vectors are preserved. SQLite gains JSON-text vectors/provenance; PostgreSQL vectors become unconstrained in dimension. Legacy model provenance is deliberately left unknown, not inferred from the old column size. The migration is irreversible because restoring global uniqueness or one fixed dimension could destroy valid data.
121
+
122
+ Every usable vector carries `embedding_provenance`: routed provider/model, authoritative revision (or exact instance when no revision is known), actual dimensions, document/query prefix pair, normalization, task, and stable `space_id`. Search uses query vectors; stored vectors must be document vectors. Only compatible profiles participate in similarity, corroboration, or contradiction checks, even when two unrelated models return the same dimension. Invalid, zero, or unknown-profile vectors cannot silently enter comparisons.
123
+
124
+ `legion-llm` owns embedding routing; Apollo has no independent default model/provider. Supplied document vectors are reused only with valid provenance. Unknown legacy/precomputed vectors regenerate through the real router before successful ingestion. Source model/provider metadata remains separate from embedding provenance.
125
+
126
+ Backfill legacy rows in bounded batches:
127
+
128
+ ```ruby
129
+ maintenance = Legion::Extensions::Apollo::Runners::Maintenance
130
+ result = maintenance.reembed_entries(limit: 100, after_id: nil)
131
+ # Continue from result[:next_after_id]; inspect result[:failures] for retries.
132
+ ```
133
+
134
+ The default selects active rows with unknown space IDs. To migrate a known space after a model, dimension, prefix, or revision change, pass `legacy_only: false, from_space_id: old_space_id` and optionally constrain the target with `provider:`, `model:`, `instance:`, and `dimensions:`. Each batch generates real embeddings and updates only vector/provenance fields; concurrent content changes are skipped. IDs, content, hashes, ownership, status, and timestamps remain unchanged. Queries in the new space exclude incompatible old rows until migration reaches them.
135
+
136
+ PostgreSQL migration removes incompatible direct-column ANN indexes but preserves dimension-constrained expression indexes and unrelated indexes. Native exact search remains available; large installations should plan compatible per-space/dimension indexes separately.
137
+
138
+ ### Writeback Delivery
139
+
140
+ `WritebackVectorize` dispatches to the callable Writeback runner. Generation errors, explicit ingest failures, and failed broker publications raise into subscription retry handling. Forwarding strips the inbound exchange/routing key so generated vectors reach `legion.apollo.writeback.store`, not the vectorizer again. Producer ownership (including explicit null), context, source metadata, and embedding provenance survive delivery. Mandatory routing and bounded publisher confirms establish broker acceptance, not synchronous remote persistence.
141
+
142
+ `Ingest`, `WritebackStore`, and `GasSubscriber` reject unsuccessful runner results into retry handling rather than acknowledging them as completed. The subscription delivery hook invokes the runner directly because the host task dispatcher can suppress runner exceptions; Apollo does not generate tasks or subtasks for these deliveries. Retry exhaustion dead-letters the message. RPC retries retain `reply_to` and `correlation_id`.
143
+
144
+ Core-client legacy wire migration and synchronous retrieval deadlines/fan-out remain outside this server release.
145
+
101
146
  ### Service Mode
102
147
 
103
148
  Service actors include:
104
149
 
105
150
  | Actor | Type | Interval | Purpose |
106
151
  |---|---|---|---|
107
- | `Ingest` | Subscription | on-message | Receive knowledge, generate embeddings, persist to PostgreSQL |
152
+ | `Ingest` | Subscription | on-message | Receive knowledge, generate embeddings, persist to the configured backend |
108
153
  | `QueryResponder` | Subscription | on-message | Handle semantic queries, return results via RPC |
109
154
  | `Decay` | Interval | 3600s | Confidence decay cycle across all entries |
110
155
  | `ExpertiseAggregator` | Interval | 1800s | Recalculate domain proficiency scores |
111
156
  | `CorroborationChecker` | Interval | 900s | Scan pending entries for auto-confirm threshold |
112
157
  | `GasSubscriber` | Subscription | on-message | Process `llm.audit.complete` events and persist accepted GAS outputs |
158
+ | `WritebackVectorize` | Subscription | on-message | Generate compatible document vectors and ingest or forward with retryable failures |
159
+ | `WritebackStore` | Subscription | on-message | Persist producer-owned writeback payloads |
160
+ | `ContradictionScanner` | Interval | 600s | Scan queued entries and retain failures for retry |
161
+ | `EntityWatchdog` | Interval | 120s | Extract entities from recent `TaskLog.entry` values and publish missing knowledge |
162
+
163
+ 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
+
165
+ 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.
113
166
 
114
167
  ### Atomic Ingestion
115
168
 
116
169
  After text embedding is complete, an ingest commits its Entry change (including a corroboration boost), expertise bookkeeping, and ingest access log in one database transaction. Contradiction scanning is queued only after that transaction commits. Failed entry, expertise, access-log, or corroboration-side-effect writes leave no partial row, confidence boost, or queued contradiction work.
117
170
 
118
- Content-hash uniqueness conflicts use a nested savepoint. If another transaction committed the winner, Apollo records against that winner; if no winner can be read after rollback, the ingest fails rather than reporting a nil or partial success.
171
+ Content-hash uniqueness conflicts use a nested savepoint. If another transaction committed a winner in the same scope and owner boundary, Apollo records against that winner; if no permitted winner can be read after rollback, the ingest fails rather than reporting a nil, foreign, or partial success.
119
172
 
120
173
  Apollo preflights Entry, Expertise, and AccessLog before ingestion writes anything; a missing required model rejects the request without a partial entry. Semantic queries require AccessLog before embedding, lookup, or confidence boosts so reads remain auditable. Traversal requires it only when a non-`unknown` agent causes an audit write. Relation remains optional for statistics, but corroboration does not promote a candidate unless it can persist the matching relation.
121
174
 
@@ -128,6 +181,7 @@ The `process` result's top-level counts describe generated phase outputs. Its `d
128
181
  - `deposited`, `facts`, and `synthesis` count successful ingest results with entry IDs, including deduplication—not just newly inserted rows.
129
182
  - `failed` counts rejected or failed entry writes.
130
183
  - `relations`, `relations_failed`, and `relations_skipped` distinguish persisted edges, failed writes or missing endpoints, and intentionally skipped edges.
184
+ - Top-level `success` is false when an entry or relation write fails; operational phase failures also return an explicit error.
131
185
 
132
186
  Relations must meet the configured confidence gate, use a supported type, and connect an unambiguous successful fact deposit to an existing target in the same access scope. Self-links and duplicate edges within the batch are skipped. Independent relation failures do not discard successful entry deposits or prevent later edges from being processed. Existing GAS types `supports_by` and `extends` are also accepted by graph traversal.
133
187
 
@@ -141,28 +195,32 @@ Apollo is wired into the GAIA tick cycle at the `knowledge_retrieval` phase (pha
141
195
 
142
196
  Entries have a confidence score between 0.0 and 1.0:
143
197
 
144
- - New entries start at `INITIAL_CONFIDENCE` (0.5) with status `candidate`
198
+ - New entries start at `confidence.initial` (default 0.5) with status `candidate`
145
199
  - Ingestion corroborates confirmed evidence. The bounded periodic checker can bootstrap one confirmation from a pair of independently sourced candidates; it marks that confirmation as bootstrap-derived so its paired candidate does not confirm solely by seeing the new status on a later scan.
146
200
  - Corroboration stays within the same knowledge domain, content type, and access scope. Equal known providers and equal source channels are not independent. Private evidence requires the same resolved owner; team evidence requires shared identity-group membership. Unresolved private/team ownership does not corroborate.
147
201
  - Each retrieval adds a small boost (+0.02, capped at 1.0)
148
- - Confidence decays hourly by factor 0.998; entries below 0.1 are archived
149
- - The GAIA write gate (`meets_write_gate?`) requires confidence > 0.6 and novelty > 0.3 for the tick write-back path
202
+ - The hourly maintenance cycle applies age-dependent power-law decay after `decay_min_age_hours` (default 168 hours), using `power_law_alpha` (default 0.05). Eligible entries below `decay_threshold` (default 0.05) are archived.
150
203
 
151
- See `helpers/confidence.rb` for all constants and math helpers.
204
+ Defaults live in `Apollo.default_settings`; maintenance owns decay and the private confidence helpers calculate retrieval and corroboration boosts.
152
205
 
153
206
  ## Requirements
154
207
 
155
208
  ### Client mode
156
209
  - Ruby >= 3.4
157
- - RabbitMQ (via `legion-transport`)
210
+ - RabbitMQ (via `legion-transport >= 1.4.31`)
158
211
 
159
212
  ### Service mode
160
- - PostgreSQL with pgvector extension
213
+ - PostgreSQL with pgvector (including `vector_norm`) or SQLite with JSON and window-function support
161
214
  - RabbitMQ
162
- - `legion-data` for database connection management
215
+ - `legion-data >= 1.10.29`, with migration 139 applied
216
+ - `legion-llm >= 0.16.10`, with an available routed embedding provider
163
217
 
164
218
  ## Development
165
219
 
220
+ PR checks run the full Ruby 3.4/4.0 suite, RuboCop, and Bundler Audit against the same Gemfile. `.github/actions/setup-ruby/action.yml` checks published companion versions before Bundler runs and checks out the exact schema/provenance commits under `tmp/ci-dependencies/` only while their required releases are unavailable. Each dependency automatically returns to RubyGems once published; main, scheduled, and release builds always use published gems.
221
+
222
+ To reproduce the unreleased stack locally, place the companion revisions named in that action under `tmp/ci-dependencies/legion-data` and `tmp/ci-dependencies/legion-llm`, then run the commands below. The Gemfile's local paths are guarded; lockfiles and these temporary checkouts remain untracked.
223
+
166
224
  ```bash
167
225
  bundle install
168
226
  bundle exec rspec
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/every'
4
- require_relative '../runners/knowledge'
4
+ require 'legion/extensions/apollo/runners/contradictions'
5
5
 
6
6
  module Legion
7
7
  module Extensions
@@ -9,53 +9,14 @@ module Legion
9
9
  module Actor
10
10
  class ContradictionScanner < Legion::Extensions::Actors::Every
11
11
  include Legion::Settings::Helper
12
- include Legion::Logging::Helper
13
12
 
14
- @queue = Queue.new
15
- @mutex = Mutex.new
16
-
17
- class << self
18
- attr_reader :queue, :mutex
19
-
20
- def enqueue(entry_id:, embedding:, content:)
21
- queue.push({ entry_id: entry_id, embedding: embedding, content: content })
22
- end
23
-
24
- def pending_count
25
- queue.size
26
- end
27
-
28
- def drain
29
- mutex.synchronize { Array.new(queue.size) { queue.pop(true) } }
30
- end
31
- end
32
-
33
- def runner_class = self.class
13
+ def runner_class = Legion::Extensions::Apollo::Runners::Contradictions
34
14
  def runner_function = 'scan_pending_contradictions'
35
15
  def time = settings[:actors][:contradiction_interval]
36
16
  def run_now? = false
37
17
  def use_runner? = false
38
18
  def check_subtask? = false
39
19
  def generate_task? = false
40
-
41
- def scan_pending_contradictions(**)
42
- items = self.class.drain
43
- return { processed: 0, failed: 0 } if items.empty?
44
-
45
- runner = Object.new.extend(Legion::Extensions::Apollo::Runners::Knowledge)
46
- processed = 0
47
- failed = 0
48
- items.each do |item|
49
- runner.send(:detect_contradictions, item[:entry_id], item[:embedding], item[:content])
50
- processed += 1
51
- rescue StandardError => e
52
- self.class.enqueue(**item)
53
- failed += 1
54
- handle_exception(e, level: :error, operation: 'apollo.actor.contradiction_scanner', entry_id: item[:entry_id])
55
- end
56
- log.info("Apollo ContradictionScanner.scan_pending_contradictions processed=#{processed} failed=#{failed}")
57
- { processed: processed, failed: failed }
58
- end
59
20
  end
60
21
  end
61
22
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/every'
4
- require_relative '../runners/maintenance'
4
+ require 'legion/extensions/apollo/runners/maintenance'
5
5
 
6
6
  module Legion
7
7
  module Extensions
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/every'
4
- require_relative '../runners/maintenance'
4
+ require 'legion/extensions/apollo/runners/maintenance'
5
5
 
6
6
  module Legion
7
7
  module Extensions
@@ -1,155 +1,22 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'digest'
4
3
  require 'legion/extensions/actors/every'
5
- require_relative '../runners/knowledge'
6
- require_relative '../runners/entity_extractor'
4
+ require 'legion/extensions/apollo/runners/entity_watchdog'
7
5
 
8
6
  module Legion
9
7
  module Extensions
10
8
  module Apollo
11
9
  module Actor
12
10
  class EntityWatchdog < Legion::Extensions::Actors::Every
13
- include Legion::Extensions::Apollo::Runners::Knowledge
14
- include Legion::Extensions::Apollo::Runners::EntityExtractor
15
11
  include Legion::Settings::Helper
16
12
 
17
- DEDUP_THRESHOLD_DEFAULT = 0.92
18
- TASK_LOG_LOOKBACK_SECONDS = 300
19
- TASK_LOG_LIMIT = 50
20
-
21
- def runner_class = self.class
13
+ def runner_class = Legion::Extensions::Apollo::Runners::EntityWatchdog
22
14
  def runner_function = 'scan_and_ingest'
23
15
  def time = settings[:actors][:entity_watchdog_interval]
24
16
  def run_now? = false
25
17
  def use_runner? = false
26
18
  def check_subtask? = false
27
19
  def generate_task? = false
28
-
29
- def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
30
- defined?(Legion::Extensions::Apollo::Runners::EntityExtractor) &&
31
- Legion.const_defined?(:Transport, false)
32
- rescue StandardError => e
33
- handle_exception(e, level: :warn, operation: 'apollo.entity_watchdog.enabled')
34
- false
35
- end
36
-
37
- def scan_and_ingest
38
- texts = recent_task_log_texts
39
- log.debug("EntityWatchdog scan_and_ingest log_texts=#{texts.size}")
40
- return { success: true, ingested: 0, reason: :no_logs } if texts.empty?
41
-
42
- ingested = 0
43
- texts.each do |text|
44
- next if task_log_text_processed?(text)
45
-
46
- result = extract_entities(
47
- text: text,
48
- entity_types: entity_types,
49
- min_confidence: min_entity_confidence
50
- )
51
- next unless result[:success]
52
-
53
- mark_task_log_text_processed(text) unless result[:source] == :unavailable
54
- result[:entities].each do |entity|
55
- next if entity_exists_in_apollo?(entity)
56
-
57
- publish_entity_ingest(entity)
58
- ingested += 1
59
- end
60
- end
61
-
62
- log.info("EntityWatchdog ingested=#{ingested} logs_scanned=#{texts.size}")
63
- { success: true, ingested: ingested, logs_scanned: texts.size }
64
- rescue StandardError => e
65
- handle_exception(e, level: :error, operation: 'apollo.entity_watchdog.scan_and_ingest')
66
- { success: false, error: e.message }
67
- end
68
-
69
- def recent_task_log_texts
70
- return [] unless defined?(Legion::Data) && defined?(Legion::Data::Model::TaskLog)
71
-
72
- lookback = settings[:entity_watchdog][:lookback_seconds]
73
- log_limit = settings[:entity_watchdog][:log_limit]
74
- cutoff = Time.now - lookback
75
- logs = Legion::Data::Model::TaskLog
76
- .where { created_at >= cutoff }
77
- .order(Sequel.desc(:created_at))
78
- .limit(log_limit)
79
- .select_map(:message)
80
- texts = logs.map(&:to_s).reject(&:empty?).uniq
81
- log.debug("EntityWatchdog recent_task_log_texts lookback=#{lookback} limit=#{log_limit} raw=#{logs.size} unique=#{texts.size}")
82
- texts
83
- rescue StandardError => e
84
- handle_exception(e, level: :warn, operation: 'apollo.entity_watchdog.recent_task_log_texts')
85
- []
86
- end
87
-
88
- def entity_exists_in_apollo?(entity)
89
- result = retrieve_relevant(
90
- query: entity[:name].to_s,
91
- limit: 1,
92
- min_confidence: settings[:entity_watchdog][:exists_min_confidence],
93
- tags: [entity[:type].to_s]
94
- )
95
- return false unless result[:success] && result[:count].positive?
96
-
97
- closest = result[:entries].first
98
- distance = closest[:distance].to_f
99
- distance <= (1.0 - dedup_similarity_threshold)
100
- rescue StandardError => e
101
- handle_exception(e, level: :warn, operation: 'apollo.entity_watchdog.entity_exists_in_apollo')
102
- false
103
- end
104
-
105
- def publish_entity_ingest(entity)
106
- return unless defined?(Legion::Extensions::Apollo::Transport::Messages::Ingest)
107
-
108
- Legion::Extensions::Apollo::Transport::Messages::Ingest.new(
109
- content: "#{entity[:type].to_s.capitalize}: #{entity[:name]}",
110
- content_type: 'concept',
111
- tags: [entity[:type].to_s, 'entity_watchdog'],
112
- source_agent: 'lex-apollo:entity_watchdog',
113
- context: { entity_type: entity[:type], original_name: entity[:name] }
114
- ).publish
115
- log.info("EntityWatchdog published entity type=#{entity[:type]} name=#{entity[:name]}")
116
- rescue StandardError => e
117
- handle_exception(e, level: :error, operation: 'apollo.entity_watchdog.publish_entity_ingest')
118
- end
119
-
120
- def entity_types
121
- Array(settings[:entity_watchdog][:types]).map(&:to_s)
122
- end
123
-
124
- def min_entity_confidence
125
- settings[:entity_watchdog][:min_confidence].to_f
126
- end
127
-
128
- def dedup_similarity_threshold
129
- settings[:entity_watchdog][:dedup_threshold].to_f
130
- end
131
-
132
- def task_log_text_processed?(text)
133
- processed_task_log_hashes.key?(task_log_text_hash(text))
134
- end
135
-
136
- def mark_task_log_text_processed(text)
137
- hashes = processed_task_log_hashes
138
- hashes[task_log_text_hash(text)] = true
139
- hashes.shift while hashes.size > processed_task_log_hash_limit
140
- end
141
-
142
- def processed_task_log_hashes
143
- @processed_task_log_hashes ||= {}
144
- end
145
-
146
- def processed_task_log_hash_limit
147
- [settings[:entity_watchdog][:log_limit].to_i * 4, 100].max
148
- end
149
-
150
- def task_log_text_hash(text)
151
- Digest::SHA256.hexdigest(text.to_s)
152
- end
153
20
  end
154
21
  end
155
22
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/every'
4
- require_relative '../runners/expertise'
4
+ require 'legion/extensions/apollo/runners/expertise'
5
5
 
6
6
  module Legion
7
7
  module Extensions
@@ -1,32 +1,20 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/subscription'
4
- require_relative '../runners/gas'
4
+ require 'legion/extensions/apollo/runners/gas'
5
+ require 'legion/extensions/apollo/transport/subscription_delivery'
5
6
 
6
7
  module Legion
7
8
  module Extensions
8
9
  module Apollo
9
10
  module Actor
10
11
  class GasSubscriber < Legion::Extensions::Actors::Subscription
12
+ include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
13
+
11
14
  def runner_class = Legion::Extensions::Apollo::Runners::Gas
12
15
  def runner_function = 'process'
13
16
  def check_subtask? = false
14
17
  def generate_task? = false
15
- def use_runner? = false
16
-
17
- def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
18
- defined?(Legion::Extensions::Apollo::Runners::Gas) &&
19
- Legion.const_defined?(:Transport, false)
20
- rescue StandardError => e
21
- handle_exception(e, level: :warn, operation: 'apollo.gas_subscriber.enabled')
22
- false
23
- end
24
-
25
- def create_queue
26
- exchange_object = Legion::Extensions::Apollo::Transport::Exchanges::LlmAudit.new
27
- queue_object = Legion::Extensions::Apollo::Transport::Queues::GasSubscriber.new
28
- queue_object.bind(exchange_object, routing_key: 'llm.audit.complete')
29
- end
30
18
  end
31
19
  end
32
20
  end
@@ -1,23 +1,23 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/subscription'
4
+ require 'legion/extensions/apollo/runners/knowledge'
5
+ require 'legion/extensions/apollo/transport/subscription_delivery'
4
6
 
5
7
  module Legion
6
8
  module Extensions
7
9
  module Apollo
8
10
  module Actor
9
11
  class Ingest < Legion::Extensions::Actors::Subscription
10
- def runner_class = 'Legion::Extensions::Apollo::Runners::Knowledge'
12
+ include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
13
+
14
+ def runner_class = Legion::Extensions::Apollo::Runners::Knowledge
11
15
  def runner_function = 'handle_ingest'
12
16
  def check_subtask? = false
13
17
  def generate_task? = false
14
18
 
15
- def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
16
- defined?(Legion::Extensions::Apollo::Runners::Knowledge) &&
17
- Legion.const_defined?(:Transport, false)
18
- rescue StandardError => e
19
- handle_exception(e, level: :warn, operation: 'apollo.ingest.enabled')
20
- false
19
+ def process_message(message, metadata, delivery_info, **)
20
+ { identity_principal_id: nil, identity_id: nil, identity_canonical_name: nil }.merge(super(message, metadata, delivery_info))
21
21
  end
22
22
  end
23
23
  end
@@ -1,22 +1,41 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/subscription'
4
+ require 'legion/extensions/apollo/runners/query_response'
5
+ require 'legion/extensions/apollo/transport/subscription_delivery'
4
6
 
5
7
  module Legion
6
8
  module Extensions
7
9
  module Apollo
8
10
  module Actor
9
11
  class QueryResponder < Legion::Extensions::Actors::Subscription
10
- def runner_class = 'Legion::Extensions::Apollo::Runners::Knowledge'
11
- def runner_function = 'handle_query'
12
+ include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
13
+
14
+ def runner_class = Legion::Extensions::Apollo::Runners::QueryResponse
15
+ def runner_function = 'handle_request'
16
+ def use_runner? = false
12
17
  def check_subtask? = false
13
18
  def generate_task? = false
14
19
 
15
- def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
16
- defined?(Legion::Extensions::Apollo::Runners::Knowledge) &&
17
- Legion.const_defined?(:Transport, false)
20
+ def process_message(message, metadata, delivery_info, **)
21
+ super(message, metadata, delivery_info).tap do |request|
22
+ request[:reply_to] = metadata.reply_to if metadata.respond_to?(:reply_to) && metadata.reply_to
23
+ request[:correlation_id] = metadata.correlation_id if metadata.respond_to?(:correlation_id) && metadata.correlation_id
24
+ end
25
+ end
26
+
27
+ private
28
+
29
+ def republish_with_retry_count(_delivery_info, metadata, payload, new_count, **)
30
+ headers = (metadata&.headers || {}).merge(Legion::Extensions::Actors::RetryPolicy::RETRY_COUNT_HEADER => new_count)
31
+ @queue.channel.default_exchange.publish(
32
+ payload, routing_key: @queue.name, headers: headers, content_type: metadata&.content_type,
33
+ content_encoding: metadata&.content_encoding, reply_to: metadata&.reply_to,
34
+ correlation_id: metadata&.correlation_id, persistent: true
35
+ )
36
+ true
18
37
  rescue StandardError => e
19
- handle_exception(e, level: :warn, operation: 'apollo.query_responder.enabled')
38
+ handle_exception(e, level: :warn, operation: 'apollo.query_responder.retry')
20
39
  false
21
40
  end
22
41
  end
@@ -1,21 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/extensions/actors/subscription'
4
+ require 'legion/extensions/apollo/runners/knowledge'
5
+ require 'legion/extensions/apollo/transport/subscription_delivery'
4
6
 
5
7
  module Legion
6
8
  module Extensions
7
9
  module Apollo
8
10
  module Actor
9
11
  class WritebackStore < Legion::Extensions::Actors::Subscription
10
- def runner_class = 'Legion::Extensions::Apollo::Runners::Knowledge'
12
+ include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
13
+
14
+ def runner_class = Legion::Extensions::Apollo::Runners::Knowledge
11
15
  def runner_function = 'handle_ingest'
12
16
  def check_subtask? = false
13
17
  def generate_task? = false
14
18
 
19
+ def process_message(message, metadata, delivery_info, **)
20
+ { identity_principal_id: nil, identity_id: nil, identity_canonical_name: nil }.merge(super(message, metadata, delivery_info))
21
+ end
22
+
15
23
  def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
16
- defined?(Legion::Extensions::Apollo::Runners::Knowledge) &&
17
- Legion.const_defined?(:Transport, false) &&
18
- Helpers::Capability.apollo_write_enabled?
24
+ settings[:data][:apollo_write] == true
19
25
  rescue StandardError => e
20
26
  handle_exception(e, level: :warn, operation: 'apollo.writeback_store.enabled')
21
27
  false