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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +125 -0
- data/README.md +113 -18
- data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -38
- data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
- data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
- data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
- data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
- data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +5 -19
- data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
- data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
- data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
- data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
- data/lib/legion/extensions/apollo/api.rb +116 -51
- data/lib/legion/extensions/apollo/client.rb +20 -9
- data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
- data/lib/legion/extensions/apollo/helpers/capability.rb +10 -63
- data/lib/legion/extensions/apollo/helpers/confidence.rb +9 -53
- data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
- data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
- data/lib/legion/extensions/apollo/helpers/graph_query.rb +107 -67
- data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
- data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
- data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
- data/lib/legion/extensions/apollo/helpers/writeback.rb +67 -109
- data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
- data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
- data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
- data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +110 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +165 -144
- data/lib/legion/extensions/apollo/runners/knowledge.rb +349 -371
- data/lib/legion/extensions/apollo/runners/maintenance.rb +242 -56
- data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
- data/lib/legion/extensions/apollo/runners/request.rb +51 -47
- data/lib/legion/extensions/apollo/runners/search.rb +88 -0
- data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
- data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
- data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
- data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
- data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
- data/lib/legion/extensions/apollo/transport.rb +20 -0
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +26 -24
- data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
- data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
- data/spec/legion/extensions/apollo/api_spec.rb +250 -28
- data/spec/legion/extensions/apollo/contradiction_spec.rb +23 -54
- data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
- data/spec/legion/extensions/apollo/helpers/capability_spec.rb +26 -29
- data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
- data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
- data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +88 -80
- data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
- data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
- data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
- data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +98 -71
- data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +220 -0
- data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
- data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
- data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
- data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +124 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +108 -0
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -83
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +246 -0
- data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
- data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +332 -683
- data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +174 -0
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +42 -160
- data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
- data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
- data/spec/legion/extensions/apollo/runners/request_spec.rb +146 -107
- data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
- data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
- data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
- data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
- data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
- data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
- data/spec/spec_helper.rb +13 -15
- metadata +71 -13
- data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
- data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
- data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
- data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
- data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +0 -49
- data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
- data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
- 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:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 86765125810bd126d5043a809268ed63bfac8f0653f3c443254c9351b8ad3e08
|
|
4
|
+
data.tar.gz: b841162c108cd4ca7e77a32a54735d7dc3e24d2826b3efe65f63ca2edef0f0d0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 7cde23c3ada440beadb9ff1db3e31906b8c50d7599416be0cfb289aad48a57b748a054919da2885c44120432085cea6ff5f62700b6c6c07932e44fb16f06f1a2
|
|
7
|
+
data.tar.gz: 1cf0063385d073236388353e46d1d0be72cd6fa4f6cc0b2236d7f019008e1715ebfdbe8d8680b9acaa89650c0358949f4e35f6900c90642dbe1d1526d78cd5b3
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,130 @@
|
|
|
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
|
+
|
|
36
|
+
## [0.4.44] - 2026-10-30
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
- Preflight required Entry, Expertise, and AccessLog models before ingestion mutates data; unavailable deployments now log the missing components and return `apollo_data_not_available` without creating partial entries (#42).
|
|
40
|
+
- Refuse semantic queries that cannot be audited before embedding, lookup, or confidence boosts; preserve non-audited traversal only for the `unknown` agent.
|
|
41
|
+
- Require Relation persistence before bounded corroboration promotion; keep relation statistics optional when the relation model is unavailable.
|
|
42
|
+
|
|
43
|
+
## [0.4.43] - 2026-10-30
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
- Commit entry creation or corroboration, expertise bookkeeping, and ingest access logging as one transaction; queue contradiction work only after commit (#41).
|
|
47
|
+
- Roll back complete ingest state when any synchronous persistence side effect fails, including a corroboration confidence update.
|
|
48
|
+
- Recover content-hash races through a nested savepoint only when a committed winner exists; otherwise return a truthful failure without partial data.
|
|
49
|
+
|
|
50
|
+
## [0.4.42] - 2026-10-30
|
|
51
|
+
|
|
52
|
+
### Fixed
|
|
53
|
+
- Retain independently sourced candidate evidence during ingest and bootstrap exactly one fresh-store confirmation through the bounded corroboration checker (#40).
|
|
54
|
+
- Snapshot pre-existing confirmations so a bootstrap-derived confirmation cannot promote its paired candidate on a later scan or duplicate the relation.
|
|
55
|
+
- Preserve domain, type, access scope, provider, source-channel, private-owner, and team-membership corroboration boundaries during bootstrap.
|
|
56
|
+
|
|
57
|
+
## [0.4.41] - 2026-10-30
|
|
58
|
+
|
|
59
|
+
### Fixed
|
|
60
|
+
- Execute service-side deprecation, force decay, stale archival, and dispute resolution while retaining no-data client action envelopes (#39).
|
|
61
|
+
- Archive deprecated entries with retained reason/source metadata; make identical repeats idempotent and return truthful HTTP success, missing, unavailable, and persistence-failure responses.
|
|
62
|
+
- Apply the approved dispute policy: `accept`/`keep` confirms, `reject` archives, and invalid or non-disputed decisions leave state unchanged. Persist lifecycle status and decision metadata atomically.
|
|
63
|
+
- Keep force decay limited to confidence multiplication and use last-update-or-creation time for stale archival.
|
|
64
|
+
- Handle bodyless API requests and pass explicit payload hashes to the JSON helper so health, validation, and unavailable-data responses remain JSON.
|
|
65
|
+
|
|
66
|
+
## [0.4.40] - 2026-10-30
|
|
67
|
+
|
|
68
|
+
### Fixed
|
|
69
|
+
- Persist GAS synthesis through normal ingestion and report separate successful entry, failed entry, persisted relation, failed relation, and skipped relation counts (#38).
|
|
70
|
+
- Resolve graph sources from successful fact IDs, including deduplicated entries; reject missing endpoints, self-links, cross-scope links, weak/unsupported edges, and duplicate edges within a batch.
|
|
71
|
+
- Retain synthesis provenance for successfully stored sources and continue processing independent relations after a write failure.
|
|
72
|
+
- Include the existing GAS `supports_by` and `extends` relation types in the traversal vocabulary.
|
|
73
|
+
|
|
74
|
+
## [0.4.39] - 2026-10-29
|
|
75
|
+
|
|
76
|
+
### Fixed
|
|
77
|
+
- Load the GAS runner explicitly and return its module as the subscription receiver, so audit events call `Gas.process` instead of attempting to dispatch on a String (#37).
|
|
78
|
+
|
|
79
|
+
## [0.4.38] - 2026-10-29
|
|
80
|
+
|
|
81
|
+
### Fixed
|
|
82
|
+
- Recognize research tools in canonical `Response.tools`, including typed tool objects and symbol/string-keyed hashes, when deciding whether to capture writeback (#36).
|
|
83
|
+
- Preserve existing `tool_calls` and enrichment-based research detection; Apollo-only and non-research responses remain ineligible.
|
|
84
|
+
|
|
85
|
+
## [0.4.37] - 2026-10-29
|
|
86
|
+
|
|
87
|
+
### Fixed
|
|
88
|
+
- Dispatch the contradiction scanner through its actual actor entry point and deliberately invoke the internal private detector (#35).
|
|
89
|
+
- Snapshot pending work safely, continue after individual failures, and retain only failed items for a later scan.
|
|
90
|
+
- Commit contradiction relations and disputed statuses atomically after LLM checks; database failures roll back and remain retryable.
|
|
91
|
+
|
|
92
|
+
## [0.4.36] - 2026-10-29
|
|
93
|
+
|
|
94
|
+
### Fixed
|
|
95
|
+
- Declare all five Apollo exchange-to-queue bindings explicitly for the two-exchange topology instead of relying on single-exchange inference (#34).
|
|
96
|
+
- Bind the GAS subscription even when its queue class is already loaded; repeated startup remains idempotent.
|
|
97
|
+
|
|
98
|
+
## [0.4.35] - 2026-10-29
|
|
99
|
+
|
|
100
|
+
### Fixed
|
|
101
|
+
- Construct request query and ingest messages with keyword payloads so Ruby 3.4+ can publish them through the real transport classes (#33).
|
|
102
|
+
- Check the transport connection's actual session state instead of calling an unavailable top-level `connected?` API.
|
|
103
|
+
|
|
104
|
+
## [0.4.34] - 2026-10-29
|
|
105
|
+
|
|
106
|
+
### Fixed
|
|
107
|
+
- Scope ingestion and maintenance corroboration to matching domains, content types, access scopes, and eligible lifecycle states (#32).
|
|
108
|
+
- Reuse query visibility rules for private ownership and shared-team membership; unresolved ownership cannot corroborate restricted knowledge.
|
|
109
|
+
- Search past dependent sources instead of allowing the first same-source match to hide eligible independent evidence.
|
|
110
|
+
|
|
111
|
+
## [0.4.33] - 2026-10-29
|
|
112
|
+
|
|
113
|
+
### Fixed
|
|
114
|
+
- Bind semantic-search and graph-traversal values through Sequel, including tags, statuses, domains, ownership, limits, confidence thresholds, and traversal depth (#31).
|
|
115
|
+
- Bind vector literals and contradiction-query limits instead of interpolating values into SQL.
|
|
116
|
+
|
|
117
|
+
## [0.4.32] - 2026-10-29
|
|
118
|
+
|
|
119
|
+
### Fixed
|
|
120
|
+
- Preserve usable writeback embeddings during ingestion instead of generating them again, allowing storage-only nodes to persist vectors without an embedding provider (#30).
|
|
121
|
+
- Reject zero, nonnumeric, and nonfinite supplied vectors before persistence; retain the existing embedding fallback when no usable vector is supplied.
|
|
122
|
+
|
|
123
|
+
## [0.4.31] - 2026-10-29
|
|
124
|
+
|
|
125
|
+
### Fixed
|
|
126
|
+
- Detect embedding capability through the provider-agnostic SSOT router lane rather than an Ollama-specific availability check.
|
|
127
|
+
|
|
3
128
|
## [0.4.30] - 2026-07-31
|
|
4
129
|
|
|
5
130
|
### Removed
|
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**:
|
|
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
|
-
|
|
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
|
-
#
|
|
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,
|
|
@@ -69,33 +70,122 @@ client.agent_profile(agent_id: 'my-agent-001')
|
|
|
69
70
|
### Maintenance
|
|
70
71
|
|
|
71
72
|
```ruby
|
|
72
|
-
#
|
|
73
|
+
# Multiply each non-archived entry's confidence by the supplied factor
|
|
73
74
|
client.force_decay(factor: 0.5)
|
|
74
75
|
|
|
75
|
-
# Archive entries
|
|
76
|
+
# Archive non-archived entries untouched for N days
|
|
76
77
|
client.archive_stale(days: 90)
|
|
77
78
|
|
|
78
79
|
# Resolve a corroboration dispute
|
|
79
80
|
client.resolve_dispute(entry_id: 'entry-uuid', resolution: :accept)
|
|
80
81
|
```
|
|
81
82
|
|
|
83
|
+
With a loaded Entry model, these methods execute against the service database and return persisted outcomes. Without local data, Ruby callers retain the existing action envelopes; these envelopes do not claim a successful mutation.
|
|
84
|
+
|
|
85
|
+
- `deprecate_entry` archives the entry and preserves its other source metadata, storing the supplied reason as `source_context.deprecation_reason`. An identical repeat is a no-op.
|
|
86
|
+
- `force_decay` accepts a finite factor from 0 through 1 and changes confidence only; it does not implicitly archive entries.
|
|
87
|
+
- `archive_stale` accepts nonnegative days and uses `COALESCE(updated_at, created_at)` to determine staleness.
|
|
88
|
+
- `resolve_dispute` accepts `:accept` or `:keep` to confirm a disputed entry, or `:reject` to archive it. It records `source_context.dispute_resolution`, sets `confirmed_at` when confirming, and preserves confidence. Unknown resolutions and non-disputed entries fail without mutation.
|
|
89
|
+
|
|
90
|
+
The standalone deprecation endpoint returns HTTP 200 after success, 404 for a missing entry, 503 when local data is unavailable, and 500 when persistence fails. Lifecycle status and metadata changes commit together.
|
|
91
|
+
|
|
82
92
|
## Architecture
|
|
83
93
|
|
|
84
94
|
### Client Mode
|
|
85
95
|
|
|
86
|
-
Runners build structured payloads and publish to the `apollo` exchange via RabbitMQ. No PostgreSQL or pgvector dependency is needed in the calling agent. Transport requires `Legion::Transport` to be loaded
|
|
96
|
+
Runners build structured payloads and publish to the `legion.apollo` exchange via RabbitMQ. No PostgreSQL or pgvector dependency is needed in the calling agent. Transport requires `Legion::Transport` to be loaded.
|
|
97
|
+
|
|
98
|
+
Startup explicitly binds the ingest, query, writeback-store, and writeback-vectorize queues to `legion.apollo`, using each queue's name as its routing key. The `legion.apollo.gas` queue binds separately to `llm.audit` with routing key `llm.audit.complete`. Repeated startup preserves these bindings.
|
|
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.
|
|
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.
|
|
87
145
|
|
|
88
146
|
### Service Mode
|
|
89
147
|
|
|
90
|
-
|
|
148
|
+
Service actors include:
|
|
91
149
|
|
|
92
150
|
| Actor | Type | Interval | Purpose |
|
|
93
151
|
|---|---|---|---|
|
|
94
|
-
| `Ingest` | Subscription | on-message | Receive knowledge, generate embeddings, persist to
|
|
152
|
+
| `Ingest` | Subscription | on-message | Receive knowledge, generate embeddings, persist to the configured backend |
|
|
95
153
|
| `QueryResponder` | Subscription | on-message | Handle semantic queries, return results via RPC |
|
|
96
154
|
| `Decay` | Interval | 3600s | Confidence decay cycle across all entries |
|
|
97
155
|
| `ExpertiseAggregator` | Interval | 1800s | Recalculate domain proficiency scores |
|
|
98
156
|
| `CorroborationChecker` | Interval | 900s | Scan pending entries for auto-confirm threshold |
|
|
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.
|
|
166
|
+
|
|
167
|
+
### Atomic Ingestion
|
|
168
|
+
|
|
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.
|
|
170
|
+
|
|
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.
|
|
172
|
+
|
|
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.
|
|
174
|
+
|
|
175
|
+
### GAS Persistence
|
|
176
|
+
|
|
177
|
+
GAS deposits facts and synthesis through normal Knowledge ingestion. New synthesis entries remain candidates and record their original source indices plus successfully stored source entry IDs in `source_context`; existing deduplicated entries retain their metadata.
|
|
178
|
+
|
|
179
|
+
The `process` result's top-level counts describe generated phase outputs. Its `deposited` object reports storage outcomes:
|
|
180
|
+
|
|
181
|
+
- `deposited`, `facts`, and `synthesis` count successful ingest results with entry IDs, including deduplication—not just newly inserted rows.
|
|
182
|
+
- `failed` counts rejected or failed entry writes.
|
|
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.
|
|
185
|
+
|
|
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.
|
|
187
|
+
|
|
188
|
+
Relation deduplication is batch-local; repeated audit events are not an exactly-once delivery contract.
|
|
99
189
|
|
|
100
190
|
### GAIA Tick Integration
|
|
101
191
|
|
|
@@ -105,27 +195,32 @@ Apollo is wired into the GAIA tick cycle at the `knowledge_retrieval` phase (pha
|
|
|
105
195
|
|
|
106
196
|
Entries have a confidence score between 0.0 and 1.0:
|
|
107
197
|
|
|
108
|
-
- New entries start at `
|
|
109
|
-
-
|
|
198
|
+
- New entries start at `confidence.initial` (default 0.5) with status `candidate`
|
|
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.
|
|
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.
|
|
110
201
|
- Each retrieval adds a small boost (+0.02, capped at 1.0)
|
|
111
|
-
-
|
|
112
|
-
- 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.
|
|
113
203
|
|
|
114
|
-
|
|
204
|
+
Defaults live in `Apollo.default_settings`; maintenance owns decay and the private confidence helpers calculate retrieval and corroboration boosts.
|
|
115
205
|
|
|
116
206
|
## Requirements
|
|
117
207
|
|
|
118
208
|
### Client mode
|
|
119
209
|
- Ruby >= 3.4
|
|
120
|
-
- RabbitMQ (via `legion-transport`)
|
|
210
|
+
- RabbitMQ (via `legion-transport >= 1.4.31`)
|
|
121
211
|
|
|
122
212
|
### Service mode
|
|
123
|
-
- PostgreSQL with pgvector
|
|
213
|
+
- PostgreSQL with pgvector (including `vector_norm`) or SQLite with JSON and window-function support
|
|
124
214
|
- RabbitMQ
|
|
125
|
-
- `legion-data
|
|
215
|
+
- `legion-data >= 1.10.29`, with migration 139 applied
|
|
216
|
+
- `legion-llm >= 0.16.10`, with an available routed embedding provider
|
|
126
217
|
|
|
127
218
|
## Development
|
|
128
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
|
+
|
|
129
224
|
```bash
|
|
130
225
|
bundle install
|
|
131
226
|
bundle exec rspec
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'legion/extensions/actors/every'
|
|
4
|
-
|
|
4
|
+
require 'legion/extensions/apollo/runners/contradictions'
|
|
5
5
|
|
|
6
6
|
module Legion
|
|
7
7
|
module Extensions
|
|
@@ -9,50 +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
|
-
|
|
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
|
-
items = []
|
|
30
|
-
items << queue.pop until queue.empty?
|
|
31
|
-
items
|
|
32
|
-
end
|
|
33
|
-
end
|
|
34
|
-
|
|
35
|
-
def runner_class = Legion::Extensions::Apollo::Runners::Knowledge
|
|
13
|
+
def runner_class = Legion::Extensions::Apollo::Runners::Contradictions
|
|
36
14
|
def runner_function = 'scan_pending_contradictions'
|
|
37
15
|
def time = settings[:actors][:contradiction_interval]
|
|
38
16
|
def run_now? = false
|
|
39
17
|
def use_runner? = false
|
|
40
18
|
def check_subtask? = false
|
|
41
19
|
def generate_task? = false
|
|
42
|
-
|
|
43
|
-
def every
|
|
44
|
-
items = self.class.drain
|
|
45
|
-
return if items.empty?
|
|
46
|
-
|
|
47
|
-
log.debug("Apollo ContradictionScanner.every processing=#{items.size}")
|
|
48
|
-
runner = Object.new.extend(Legion::Extensions::Apollo::Runners::Knowledge)
|
|
49
|
-
items.each do |item|
|
|
50
|
-
runner.detect_contradictions(item[:entry_id], item[:embedding], item[:content])
|
|
51
|
-
end
|
|
52
|
-
log.info("Apollo ContradictionScanner.every completed=#{items.size}")
|
|
53
|
-
rescue StandardError => e
|
|
54
|
-
handle_exception(e, level: :error, operation: 'apollo.actor.contradiction_scanner')
|
|
55
|
-
end
|
|
56
20
|
end
|
|
57
21
|
end
|
|
58
22
|
end
|
|
@@ -1,155 +1,22 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require 'digest'
|
|
4
3
|
require 'legion/extensions/actors/every'
|
|
5
|
-
|
|
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
|
-
|
|
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,34 +1,20 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'legion/extensions/actors/subscription'
|
|
4
|
+
require 'legion/extensions/apollo/runners/gas'
|
|
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 GasSubscriber < Legion::Extensions::Actors::Subscription
|
|
10
|
-
|
|
12
|
+
include Legion::Extensions::Apollo::Transport::SubscriptionDelivery
|
|
13
|
+
|
|
14
|
+
def runner_class = Legion::Extensions::Apollo::Runners::Gas
|
|
11
15
|
def runner_function = 'process'
|
|
12
16
|
def check_subtask? = false
|
|
13
17
|
def generate_task? = false
|
|
14
|
-
def use_runner? = false
|
|
15
|
-
|
|
16
|
-
def enabled? # rubocop:disable Legion/Extension/ActorEnabledSideEffects
|
|
17
|
-
defined?(Legion::Extensions::Apollo::Runners::Gas) &&
|
|
18
|
-
Legion.const_defined?(:Transport, false)
|
|
19
|
-
rescue StandardError => e
|
|
20
|
-
handle_exception(e, level: :warn, operation: 'apollo.gas_subscriber.enabled')
|
|
21
|
-
false
|
|
22
|
-
end
|
|
23
|
-
|
|
24
|
-
def create_queue
|
|
25
|
-
return if queues.const_defined?(:GasSubscriber, false)
|
|
26
|
-
|
|
27
|
-
queues.const_set(:GasSubscriber, Apollo::Transport::Queues::GasSubscriber) unless queues.const_defined?(:GasSubscriber, false)
|
|
28
|
-
exchange_object = Apollo::Transport::Exchanges::LlmAudit.new
|
|
29
|
-
queue_object = Apollo::Transport::Queues::GasSubscriber.new
|
|
30
|
-
queue_object.bind(exchange_object, routing_key: 'llm.audit.complete')
|
|
31
|
-
end
|
|
32
18
|
end
|
|
33
19
|
end
|
|
34
20
|
end
|