lex-synapse 0.4.15 → 0.4.30

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '037082609e6545e0a3581981a602d49afdd4a532cf4b15d166f0cf04fd3a746f'
4
- data.tar.gz: 42c81c769ef9f4367dec25d4713d5ab4bc4eb1491b88478bb365d5cbd3e2521e
3
+ metadata.gz: 23dc6324e5d4c2ef4dc9da3d920c2f9dfad30fb38a661911ce44674e451ea39e
4
+ data.tar.gz: edbc6248740657037c09374b8903c71687adfcfd43c30cdb187cc3b814d8b993
5
5
  SHA512:
6
- metadata.gz: a5f60904a36dcf8fb276c75683485a7c4ef8207b9b1f1b6c03cae33bd392fa85d4fc44beb605aeae62f492be50be546b90b209021361d1105c9adc43306bfe21
7
- data.tar.gz: '059f003e2a808fe705e315b8c7c75c01631ac97ff86c2f675467dd563f37106ea039fc4aaddf32ad89315d4290226e0308d209c0e3df8ebd89644584ab315de9'
6
+ metadata.gz: 0345c669e42ace213793d5d2928a0907da0ec715837814c605d731d49c3146cbc0ee64af6983a0d7814cdc9624df5bcb7b2da879cfd5b6cc0a51a0c3a72aef36
7
+ data.tar.gz: cf0ec2201d785b4833bbbece98e6a46a5347dd5d3d4ef256812c8454063fc6b241cbd9982a508ed5db964ac36eae01d4b85e1a28ee65df75bc6a235d23b45917
data/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.30] - 2026-11-19
4
+ ### Fixed
5
+ - Report unknown downstream success rates as nil when no outcomes are complete; document reviewed recovery, retry, and decay behavior (fixes #25).
6
+
7
+ ## [0.4.29] - 2026-11-19
8
+ ### Fixed
9
+ - Seed zero throughput baselines from the full first traffic window and avoid unchanged baseline writes, preventing false startup spikes (fixes #24).
10
+
11
+ ## [0.4.28] - 2026-11-19
12
+ ### Fixed
13
+ - Wire the scheduled reviewer through transformer JSON results, prioritize fresh proposals, and persist bounded exponential review retries with expiry (fixes #27).
14
+
15
+ ## [0.4.27] - 2026-11-19
16
+ ### Fixed
17
+ - Start existing decay checkpoints at upgrade time and use conditional SQL multiplication without explicit locks, preserving concurrent confidence updates and newly arrived traffic (fixes #28).
18
+
19
+ ## [0.4.26] - 2026-11-19
20
+ ### Fixed
21
+ - Recover observe-mode confidence from confirmed downstream successes once, preserve evaluation credit provenance, and update confidence/streaks atomically in SQL; keep failure outcome handling outside a broad transaction (fixes #15, fixes #16).
22
+
23
+ ## [0.4.25] - 2026-11-19
24
+ ### Fixed
25
+ - Align README and agent notes with callable client/runner APIs, mutation-history simulation, automatic proposal review/application, and current tasker/Apollo integration limits (fixes #31).
26
+
27
+ ## [0.4.24] - 2026-11-19
28
+ ### Fixed
29
+ - Forward the injected reviewer through standalone client challenge cycles and initialize signals before application-time review checks (fixes #27).
30
+
31
+ ## [0.4.23] - 2026-11-19
32
+ ### Fixed
33
+ - Decay only complete idle hours since the latest activity, persisting a transactional checkpoint to prevent duplicate decay across retries and restarts (fixes #28).
34
+
35
+ ## [0.4.22] - 2026-11-19
36
+ ### Fixed
37
+ - Defer required challenge reviews when the reviewer is absent, fails, or abstains; retry deferred reviews and prevent unreviewed automatic application (fixes #27).
38
+
39
+ ## [0.4.21] - 2026-11-19
40
+ ### Fixed
41
+ - Calculate downstream success rate from completed outcomes only, expose unresolved and evaluation counts, and verify duplicate-safe task outcome correlation (fixes #25).
42
+
43
+ ## [0.4.20] - 2026-11-19
44
+ ### Fixed
45
+ - Keep observe-mode pass-through and clean attention rejections neutral for confidence and learning streaks; record the actual observed attention verdict (fixes #15).
46
+
47
+ ## [0.4.19] - 2026-11-19
48
+ ### Fixed
49
+ - Use non-overlapping autonomy ranges so mode labels match filtering, transformation, and self-modification at their inclusive lower thresholds (fixes #26).
50
+
51
+ ## [0.4.18] - 2026-11-19
52
+ ### Fixed
53
+ - Bootstrap zero throughput baselines from observed traffic without classifying the initial window as an anomaly; preserve batched homeostasis queries (fixes #24).
54
+
55
+ ## [0.4.17] - 2026-11-19
56
+ ### Fixed
57
+ - Initialize both homeostasis models on its first tick and report unavailable data explicitly (fixes #20).
58
+
59
+ ## [0.4.16] - 2026-11-19
60
+ ### Fixed
61
+ - Correct the documented hourly decay conversion to approximately 4.7% daily and a 14.4-day half-life (fixes #17).
62
+ - Preserve reactive repair eligibility across a failure penalty and persist consecutive successes for the existing >50 bonus, resetting the streak on failure (fixes #16).
63
+ - Connect wrapped relationship evaluation to lex-tasker 0.4.1 and subscribe to host task completion/failure events with durable task/signal correlation and duplicate outcome protection (references #18; tasker companion required).
64
+
3
65
  ## [0.4.15] - 2026-10-29
4
66
  ### Fixed
5
67
  - Treat missing configured conditioner/transformer capabilities as unavailable rather than successful learning; retain legitimate observe/filter pass-through.
data/CLAUDE.md CHANGED
@@ -10,7 +10,7 @@ Cognitive routing layer that wraps task chain relationships with observation, le
10
10
 
11
11
  **GitHub**: https://github.com/LegionIO/lex-synapse
12
12
  **License**: MIT
13
- **Version**: 0.4.11
13
+ **Version**: see `lib/legion/extensions/synapse/version.rb`
14
14
 
15
15
  ## Architecture
16
16
 
@@ -31,10 +31,10 @@ Legion::Extensions::Synapse
31
31
  │ ├── Mutate # versioned self-modification with before/after snapshots
32
32
  │ ├── Revert # rollback to previous mutation version (restores before_state)
33
33
  │ ├── Report # aggregate stats for GAIA consumption
34
- │ ├── Dream # replay historical signals in simulation mode
35
- │ ├── GaiaReport # GAIA tick hook: report confidence and health per synapse
36
- │ ├── Promote # Apollo integration: promote high-confidence synapse patterns
37
- │ ├── Retrieve # Apollo integration: retrieve relevant synapse patterns
34
+ │ ├── Dream # mutation-history inspection and copied-state simulation
35
+ │ ├── GaiaReport # aggregate confidence and health summaries for GAIA callers
36
+ │ ├── Promote # prepare high-confidence synapse knowledge entries
37
+ │ ├── Retrieve # seed synapses from caller-supplied knowledge entries
38
38
  │ ├── Propose # reactive (signal-driven) + proactive (periodic) proposal generation
39
39
  │ └── Challenge # conflict detection, LLM challenge, weighted aggregation, outcome resolution
40
40
  ├── Helpers/
@@ -43,7 +43,7 @@ Legion::Extensions::Synapse
43
43
  │ ├── RelationshipWrapper # Layer 1 -> Layer 2 wrapping
44
44
  │ └── Challenge # settings, constants, impact threshold helpers
45
45
  ├── Data/
46
- │ ├── Migrations/ # 001 synapses, 002 mutations, 003 signals, 004 proposals, 005 challenges, 006 slow_query_indexes, 007 blast_radius
46
+ │ ├── Migrations/ # 001 synapses, 002 mutations, 003 signals, 004 proposals, 005 challenges, 006 slow_query_indexes, 007 blast_radius, 008 consecutive_successes, 009 task targets, 010 last_decay_at
47
47
  │ └── Models/ # Synapse, SynapseMutation, SynapseSignal, SynapseProposal, SynapseChallenge
48
48
  ├── Transport/
49
49
  │ ├── Exchanges/Synapse
@@ -54,21 +54,30 @@ Legion::Extensions::Synapse
54
54
 
55
55
  ## Runner Methods (Public API)
56
56
 
57
- | Runner | Method | Signature |
57
+ The standalone `Client` includes these runners. `Client#evaluate(synapse_id:, payload: {})` injects the clients supplied at construction. The runner itself accepts `evaluate(synapse_id:, payload: {}, conditioner_client: nil, transformer_client: nil, **)`.
58
+
59
+ | Area | Callable signature | Behavior |
58
60
  |---|---|---|
59
- | Evaluate | `evaluate` | `evaluate(synapse_id:, payload: {}, conditioner_client: nil, transformer_client: nil)` |
60
- | Pain | `handle_pain` | `handle_pain(synapse_id:, task_id: nil)` — records failure, adjusts confidence, calls `revert` on 3+ consecutive failures |
61
- | Crystallize | `crystallize` | `crystallize(signal_pairs:, threshold: 20)` |
62
- | Mutate | `mutate` | `mutate(synapse_id:, mutation_type:, changes:, trigger:)` |
63
- | Revert | `revert` | `revert(synapse_id:, to_version: nil, trigger: 'pain')` — restores `before_state` from mutation record; records revert as new mutation |
64
- | Report | `report` | `report(synapse_id:)` |
65
- | Dream | `dream` | `dream(synapse_id:, limit:)` |
66
- | GaiaReport | `gaia_report` | Called during GAIA tick cycle |
67
- | Promote | `promote` | `promote(synapse_id:)` |
68
- | Retrieve | `retrieve` | `retrieve(...)` |
69
- | Propose | `propose`, `proposals`, `review_proposal` | `propose(synapse_id:, ...)` / `proposals(synapse_id:, status:)` / `review_proposal(proposal_id:, status:)` |
70
- | Challenge | `challenge_proposal`, `challenges`, `challenger_stats` | `challenge_proposal(proposal_id:)` / `challenges(proposal_id:)` / `challenger_stats` |
71
- | Blast Radius | `analyze_routing` | `analyze_routing(synapse_id:)` — logs blast radius analysis result |
61
+ | Pain | `handle_pain(synapse_id:, task_id: nil, signal_id: nil, **)` | Correlates failure when a signal ID is supplied; otherwise inserts a legacy failure record |
62
+ | Crystallize | `crystallize(signal_pairs: [], threshold: 20)` | Creates emergent synapses from supplied pairs; the default empty input discovers nothing |
63
+ | Mutate | `mutate(synapse_id:, mutation_type:, changes:, trigger:)` | Writes routing state and mutation history transactionally |
64
+ | Revert | `revert(synapse_id:, to_version: nil, trigger: 'pain')` | Restores the selected mutation's before-state and records a new history entry |
65
+ | Report | `report(synapse_id:, **)` | Reports evaluation counts separately from completed downstream outcomes |
66
+ | Dream | `dream_replay(synapse_id: nil, **)` | Returns mutation-history metadata, not replayed payloads |
67
+ | Dream | `dream_simulate(synapse_id:, mutation_type:, changes:, **)` | Copies state and estimates confidence by assuming one success; does not run historical payloads or write routing state |
68
+ | GAIA | `gaia_summary(**)`, `gaia_reflection(**)` | Returns aggregate health and recent mutation summaries for a caller to consume |
69
+ | Promote | `promote(synapse_id: nil, **)` | Returns candidate knowledge entries; does not publish to Apollo |
70
+ | Retrieve | `retrieve_and_seed(knowledge_entries:, **)` | Seeds from caller-supplied knowledge; does not query Apollo |
71
+ | Propose | `propose_reactive(synapse:, payload:, signal_id:, attention_result:, transform_result:, transformer_client: nil)` | Generates proposals from supplied evaluation evidence |
72
+ | Propose | `propose_proactive` | Analyzes stored signals for eligible active synapses |
73
+ | Client review | `proposals(synapse_id:, status: nil)`, `review_proposal(proposal_id:, status:)` | Lists proposals or records an explicit review status |
74
+ | Challenge | `challenge_proposal(proposal_id:, transformer_client: @transformer_client, **)` | Client defaults to its injected reviewer; runner default is nil |
75
+ | Challenge | `run_challenge_cycle(transformer_client: @transformer_client, **)` | Client defaults to its injected reviewer; runner default is nil; challenges, applies auto-accepted proposals, then resolves outcomes |
76
+ | Challenge | `apply_proposal(proposal_id:, **)`, `resolve_challenge_outcomes(proposal_id:)` | Applies approved/auto-accepted proposals or resolves their challenger outcomes |
77
+ | Challenge queries | `pending_challenges`, `challenges(proposal_id:)`, `challenger_stats` | Returns pending/deferred work, review records, or resolved challenger statistics |
78
+ | Blast radius | `compute(**)`, `blast_tier(synapse_id:)` | Recomputes graph-derived blast tiers or returns one stored tier |
79
+
80
+ `analyze_routing` is a private proposal-analysis stub, not the blast-radius API. See the README for review prerequisites and integration limits.
72
81
 
73
82
  ## Key Thresholds
74
83
 
@@ -91,37 +100,37 @@ Legion::Extensions::Synapse
91
100
 
92
101
  | Confidence | Mode | Capabilities |
93
102
  |------------|------|-------------|
94
- | 0.0-0.3 | OBSERVE | Log, pass through unchanged |
95
- | 0.3-0.6 | FILTER | Suppress signals |
96
- | 0.6-0.8 | TRANSFORM | Filter + transform within schemas |
97
- | 0.8-1.0 | AUTONOMOUS | Self-modify rules via proposals, infer transforms |
103
+ | 0.0 <= confidence < 0.3 | OBSERVE | Log, pass through unchanged |
104
+ | 0.3 <= confidence < 0.6 | FILTER | Suppress signals |
105
+ | 0.6 <= confidence < 0.8 | TRANSFORM | Filter + transform within schemas |
106
+ | 0.8 <= confidence <= 1.0 | AUTONOMOUS | Self-modify rules via proposals, infer transforms |
98
107
 
99
108
  ## Pain Auto-Revert
100
109
 
101
- `Runners::Pain#handle_pain` calls `revert(synapse_id:, trigger: 'pain')` directly when `consecutive_failures >= 3`. The revert finds the latest mutation record for the synapse's current version, restores `before_state` (attention, transform, routing_strategy, confidence, status), decrements version, marks the mutation outcome as `'reverted'`, and creates a new mutation record with `outcome: 'reverted'`.
110
+ `Runners::Pain#handle_pain` calls `revert(synapse_id:, trigger: 'pain')` directly when `consecutive_failures >= 3`. The revert finds the latest mutation record for the synapse's current version, restores `before_state` (attention, transform, routing_strategy, confidence, status), restores the saved live version, marks the mutation outcome as `'reverted'`, and creates a new uniquely versioned history record with `outcome: 'reverted'`.
102
111
 
103
112
  ## Data Model
104
113
 
105
- - **synapses**: Core routing definition with confidence, status, version, baseline_throughput, blast_radius
114
+ - **synapses**: Core routing definition with confidence, status, version, baseline_throughput, blast_radius, consecutive_successes, last_decay_at
106
115
  - **synapse_mutations**: Versioned change history with before/after JSON snapshots, trigger, outcome
107
- - **synapse_signals**: Per-signal outcome records (attention pass, transform success, latency_ms, downstream outcome)
116
+ - **synapse_signals**: Per-signal outcome records (observed attention verdict, evaluation success, latency_ms, correlated task/target, downstream outcome)
108
117
  - **synapse_proposals**: Proposed changes with status lifecycle (pending → approved/rejected/applied/expired/auto_accepted/auto_rejected), challenge_state, challenge_score, impact_score
109
118
  - **synapse_challenges**: Per-challenge verdicts (conflict/LLM), confidence tracking, outcome resolution
110
119
 
111
- ## Autonomous Observation Mode (v0.3.0)
120
+ ## Autonomous Proposal Application
112
121
 
113
- AUTONOMOUS-tier synapses (confidence >= 0.8) generate proposals instead of executing autonomous actions. Proposals are reactive (triggered on signal evaluation in `Runners::Evaluate`) or proactive (generated periodically by `Actors::Propose`). Settings: `lex-synapse.proposals.*` (enabled, reactive, proactive, max_per_run, llm_engine_options, thresholds).
122
+ AUTONOMOUS-tier synapses generate reactive or proactive proposals. `run_challenge_cycle` automatically applies auto-accepted proposals through the mutation runner; this is not observation-only operation. Explicitly approved proposals can be applied with `apply_proposal`. Settings: `lex-synapse.proposals.*`.
114
123
 
115
- ## Adversarial Challenge Phase (v0.4.0)
124
+ ## Adversarial Challenge Phase
116
125
 
117
- Pending proposals pass through: conflict detection → impact scoring → LLM challenge (gated by `impact_score >= 0.3`) → weighted aggregation → auto-accept/reject. Aggregation: `support_weight / (support_weight + challenge_weight)`, >= 0.85 auto-accepts, <= 0.15 auto-rejects. Settings: `lex-synapse.challenge.*`.
126
+ Impact scoring determines whether LLM review is required: impact >= the configured threshold (default 0.3) or HIGH/CRITICAL blast radius. Missing reviewers, errors, malformed responses, and abstentions leave a proposal pending with `challenge_state: deferred`. Deferred proposals retry with persisted exponential backoff (300 seconds initially, capped at 3600) and expire after three incomplete attempts; due new proposals precede retries. After completed review, conflict detection and weighted aggregation determine the decision: support weight / total weight, >= 0.85 auto-accepts and <= 0.15 auto-rejects by default. Lower-impact proposals retain conflict-only decisions. The scheduled actor constructs a transformer client and consumes JSON verdicts; the standalone client uses its injected reviewer. Settings: `lex-synapse.challenge.*`.
118
127
 
119
- ## GAIA / Apollo Integration (v0.2.2)
128
+ ## GAIA / Apollo Integration
120
129
 
121
- - **GaiaReport**: Called during GAIA tick to report per-synapse confidence and health metrics
122
- - **Dream**: Replays historical signals in simulation without affecting live state
123
- - **Promote**: Publishes high-confidence patterns to Apollo shared knowledge store
124
- - **Retrieve**: Pulls relevant patterns from Apollo to seed new synapses or adjust confidence
130
+ - `gaia_summary` and `gaia_reflection` return health and mutation summaries for callers.
131
+ - `dream_replay` inspects mutation history. `dream_simulate` changes a copied state and assumes a success adjustment; neither executes historical payloads or proves routing quality.
132
+ - `promote` prepares knowledge entries, and `retrieve_and_seed` consumes supplied entries. Apollo network publication/retrieval remains tracked in [#30](https://github.com/LegionIO/lex-synapse/issues/30).
133
+ - Task-chain dispatch requires the lex-tasker companion tracked in [#18](https://github.com/LegionIO/lex-synapse/issues/18).
125
134
 
126
135
  ## Dependencies
127
136
 
@@ -141,8 +150,8 @@ Pending proposals pass through: conflict detection → impact scoring → LLM ch
141
150
 
142
151
  ```bash
143
152
  bundle install
144
- bundle exec rspec # 412 specs, 0 failures
145
- bundle exec rubocop # 0 offenses
153
+ bundle exec rspec --format json --out tmp/rspec_results.json --format progress --out tmp/rspec_progress.txt
154
+ bundle exec rubocop -A
146
155
  ```
147
156
 
148
157
  Uses in-memory SQLite for model/runner tests.
data/README.md CHANGED
@@ -16,41 +16,28 @@ gem 'lex-synapse'
16
16
 
17
17
  ## Standalone Client
18
18
 
19
- Use the synapse engine without the full LegionIO framework:
19
+ Use the synapse engine with an initialized Sequel database containing this gem's migrations and Legion's data connection setting enabled. The host supplies that setup in a running LegionIO deployment.
20
20
 
21
21
  ```ruby
22
22
  require 'legion/extensions/synapse/client'
23
23
 
24
- # Optionally inject conditioner and transformer clients
25
- conditioner = Legion::Extensions::Conditioner::Client.new
26
- transformer = Legion::Extensions::Transformer::Client.new
27
-
28
- client = Legion::Extensions::Synapse::Client.new(
29
- conditioner_client: conditioner,
30
- transformer_client: transformer
31
- )
32
-
33
- # Create a synapse
34
- synapse = client.create(
35
- source_function_id: 1,
36
- target_function_id: 2,
37
- attention: '{"all":[{"fact":"status","operator":"equal","value":"open"}]}',
38
- transform: '{"template":"{\"message\":\"<%= title %>\"}","engine":"erb"}'
39
- )
40
-
41
- # Evaluate a signal through the synapse
42
- result = client.evaluate(synapse_id: synapse.id, payload: { status: 'open', title: 'Bug fix' })
24
+ client = Legion::Extensions::Synapse::Client.new
25
+ synapse = client.create(source_function_id: 1, target_function_id: 2)
26
+ result = client.evaluate(synapse_id: synapse.id, payload: { message: 'hello' })
43
27
  result[:success] # => true
44
- result[:mode] # => :transform (based on confidence level)
45
- result[:result] # => { message: "Bug fix" }
28
+ result[:mode] # => :transform (permission tier, not proof of transformation)
29
+ result[:transformed] # => false (no transform configured)
30
+ result[:result] # => { message: 'hello' }
46
31
 
47
- # Get synapse stats
48
32
  report = client.report(synapse_id: synapse.id)
49
- report[:confidence] # => 0.72
50
- report[:signals_24h] # => 1
51
- report[:success_rate] # => 1.0
33
+ report[:confidence] # => 0.72
34
+ report[:signals_24h] # => 1
35
+ report[:completed_outcomes_24h] # => 0
36
+ report[:success_rate] # => nil (downstream completion is unknown)
52
37
  ```
53
38
 
39
+ For configured rules, require `legion/extensions/conditioner/client` and `legion/extensions/transformer/client`, then inject `conditioner_client:` and `transformer_client:` into `Client.new`. `Client#evaluate` uses those injected clients. A successful evaluation is separate from downstream task completion.
40
+
54
41
  ## Architecture
55
42
 
56
43
  ### Three-Layer Model
@@ -67,16 +54,18 @@ Each synapse has a confidence score (0.0-1.0) that governs what it's allowed to
67
54
 
68
55
  | Range | Mode | Permitted Actions |
69
56
  |-------|------|-------------------|
70
- | 0.0-0.3 | OBSERVE | Log what it would do, pass through unchanged |
71
- | 0.3-0.6 | FILTER | Can suppress signals, cannot modify |
72
- | 0.6-0.8 | TRANSFORM | Can filter + transform within defined schemas |
73
- | 0.8-1.0 | AUTONOMOUS | Generates proposals for self-modification |
57
+ | 0.0 <= confidence < 0.3 | OBSERVE | Log what it would do, pass through unchanged |
58
+ | 0.3 <= confidence < 0.6 | FILTER | Can suppress signals, cannot modify |
59
+ | 0.6 <= confidence < 0.8 | TRANSFORM | Can filter + transform within defined schemas |
60
+ | 0.8 <= confidence <= 1.0 | AUTONOMOUS | Generates proposals for self-modification |
74
61
 
75
62
  **Starting scores**: explicit=0.7, emergent=0.3, seeded=0.5
76
63
 
77
- **Adjustments**: success +0.02, failure -0.05, validation failure -0.03, 50+ consecutive successes +0.05 bonus
64
+ Observe-mode pass-through and clean attention rejections are neutral: they neither change confidence nor advance/reset the success streak. Signals retain the conditioner verdict even when observe mode passes the payload through. A confirmed downstream success credits an observe evaluation once (+0.02 and its success-streak increment), so an observing synapse can recover; eligible evaluations already credited at evaluation time are never credited again.
65
+
66
+ **Adjustments**: eligible evaluation success +0.02, failure -0.05, validation failure -0.03, more than 50 consecutive successful evaluations +0.05 bonus (streak persisted; failures reset it)
78
67
 
79
- **Decay**: Unused synapses fade at 0.998x per hour (~15% per day of inactivity)
68
+ **Decay**: Unused synapses fade at 0.998x per hour (~4.7% per day of inactivity; half-life ~14.4 days)
80
69
 
81
70
  ### Pain Signals
82
71
 
@@ -87,31 +76,46 @@ Downstream task failures propagate backward through the chain:
87
76
 
88
77
  ### Homeostasis
89
78
 
90
- - **Spike detection**: Throughput >3x baseline for 60+ seconds triggers dampening
91
- - **Drought detection**: Zero throughput for 10x average interval flags for review
92
- - **Baseline tracking**: Exponential moving average of signals/minute
79
+ - **Spike detection**: Counts windows with throughput >3x baseline for 60+ seconds
80
+ - **Drought detection**: Counts windows with zero throughput for 10x the average interval
81
+ - **Baseline tracking**: Exponential moving average of signals/minute, bootstrapped from zero on the first traffic window; the homeostasis actor reports anomalies without changing status
93
82
 
94
83
  ## Runners
95
84
 
96
85
  ### Evaluate
97
- `evaluate(synapse_id:, payload:, conditioner_client:, transformer_client:)`
86
+ Runner: `evaluate(synapse_id:, payload: {}, conditioner_client: nil, transformer_client: nil, **)`. Client: `evaluate(synapse_id:, payload: {})`.
98
87
 
99
88
  Main signal flow: load synapse → check autonomy → run attention (conditioner) → run transform (transformer) → record signal → adjust confidence → generate proposals if AUTONOMOUS.
100
89
 
90
+ ### Task-chain integration
91
+
92
+ The lex-synapse side is implemented here; live dispatch requires the lex-tasker companion tracked in [#18](https://github.com/LegionIO/lex-synapse/issues/18). With that companion and this extension loaded, relationships explicitly wrapped
93
+ as synapses are evaluated before child task creation. Unwrapped relationships retain
94
+ the ordinary conditioner/transformer pipeline. Suppressed or unavailable evaluations
95
+ do not dispatch a child; accepted evaluations pass their result directly to the target
96
+ without applying the relationship's rules a second time. Task payloads must be hashes.
97
+ Delayed children retain the evaluated payload and its signal correlation.
98
+
99
+ The LegionIO host's `task.failed` and `task.completed` events update the correlated
100
+ signal by task ID and target runner/function. Intermediate stage events and repeated
101
+ completion events do not count as additional outcomes. This integration uses the host
102
+ event bus for outcomes and synchronous evaluation at dispatch; it does not depend on
103
+ an AMQP producer publishing `synapse.evaluate` or `task.failed`.
104
+
101
105
  ### Pain
102
- `handle_pain(synapse_id:, task_id:)`
106
+ `handle_pain(synapse_id:, task_id: nil, signal_id: nil, **)`
103
107
 
104
108
  Downstream failure handler. Records failed signal, adjusts confidence, calls `revert` on 3+ consecutive failures, may dampen synapse.
105
109
 
106
110
  ### Revert
107
- `revert(synapse_id:, to_version:, trigger:)`
111
+ `revert(synapse_id:, to_version: nil, trigger: 'pain')`
108
112
 
109
113
  Rolls back to a previous mutation version, restoring `before_state`. Records the revert as a new mutation entry.
110
114
 
111
115
  ### Crystallize
112
- `crystallize(signal_pairs:, threshold: 20)`
116
+ `crystallize(signal_pairs: [], threshold: 20)`
113
117
 
114
- Bottom-up emergence. Creates new synapses for source/target pairs exceeding the threshold.
118
+ Creates emergent synapses from supplied source/target pairs meeting the threshold. With no supplied pairs, no synapses are created.
115
119
 
116
120
  ### Mutate
117
121
  `mutate(synapse_id:, mutation_type:, changes:, trigger:)`
@@ -119,17 +123,23 @@ Bottom-up emergence. Creates new synapses for source/target pairs exceeding the
119
123
  Versioned self-modification. Records before/after state snapshots.
120
124
 
121
125
  ### Report
122
- `report(synapse_id:)`
126
+ `report(synapse_id:, **)`
123
127
 
124
128
  Aggregates stats: confidence, status, 24h signal count, success rate, last mutation.
125
129
 
126
130
  ### Dream
127
- `dream(synapse_id:, limit:)`
128
-
129
- Replays historical signals in simulation mode without affecting live state.
131
+ `dream_replay(synapse_id: nil, **)` returns mutation-history metadata and a timeline. `dream_simulate(synapse_id:, mutation_type:, changes:, **)` changes a copy of the routing state and estimates confidence by assuming one success. Neither executes historical payloads or empirically validates a proposed change; routing state is unchanged.
130
132
 
131
133
  ### Propose / Challenge
132
- AUTONOMOUS-tier synapses generate proposals (reactive on evaluation, proactive periodically). Proposals are subjected to a multi-stage challenge pipeline: conflict detection → impact scoring → optional LLM challenge → weighted aggregation → auto-accept/reject.
134
+ `propose_reactive(synapse:, payload:, signal_id:, attention_result:, transform_result:, transformer_client: nil)` generates proposals from evaluation evidence. `propose_proactive` analyzes stored signals. The client exposes `proposals(synapse_id:, status: nil)` and `review_proposal(proposal_id:, status:)` for review.
135
+
136
+ `challenge_proposal(proposal_id:, transformer_client: @transformer_client, **)` and `run_challenge_cycle(transformer_client: @transformer_client, **)` use the client's injected reviewer by default; runner defaults are nil. The cycle challenges pending/deferred proposals and automatically applies auto-accepted proposals. See required-review rules below. `apply_proposal(proposal_id:, **)` handles explicit approvals or auto-acceptance; `resolve_challenge_outcomes(proposal_id:)` scores observed challenger outcomes. Query methods are `pending_challenges`, `challenges(proposal_id:)`, and `challenger_stats`.
137
+
138
+ ### GAIA, knowledge entries, and blast radius
139
+
140
+ `gaia_summary(**)` returns aggregate health; `gaia_reflection(**)` adds recent mutation information. `promote(synapse_id: nil, **)` returns candidate knowledge entries without publishing them. `retrieve_and_seed(knowledge_entries:, **)` consumes supplied knowledge entries without querying Apollo. Live Apollo integration is tracked in [#30](https://github.com/LegionIO/lex-synapse/issues/30).
141
+
142
+ `compute(**)` recomputes blast-radius tiers from the active routing graph. `blast_tier(synapse_id:)` returns a stored tier. The private `analyze_routing` proposal stub is not a blast-radius API.
133
143
 
134
144
  ## Relationship Wrapper
135
145
 
@@ -159,6 +169,20 @@ Five tables: `synapses` (core routing + confidence + status + blast_radius), `sy
159
169
  - [LegionIO](https://github.com/LegionIO/LegionIO) framework (for AMQP actor mode)
160
170
  - Standalone Client works without the framework (requires Sequel + database)
161
171
 
172
+ ### Outcome reporting
173
+
174
+ `report(synapse_id:)` measures the last 24 hours by signal creation time. `success_rate` is successful downstream outcomes divided by completed outcomes (`success` plus `failed`), and is `nil` when none are complete. `completed_outcomes_24h`, `successful_outcomes_24h`, and `failed_outcomes_24h` expose that denominator. `unresolved_signals_24h` includes pending tasks and evaluations that never dispatch; these do not count as completed failures. `evaluation_successes_24h` counts successful evaluation/pass-through records and is not proof of downstream completion or transformation execution.
175
+
176
+ `Integration.attach_task` associates an evaluation signal with its downstream task and target runner/function. `Integration.record_outcome` and the installed host task event listeners finalize that same signal once; duplicate or conflicting completion notifications do not create another attempt. Live task-chain attachment depends on the lex-tasker companion tracked in [#18](https://github.com/LegionIO/lex-synapse/issues/18).
177
+
178
+ ### Required proposal review
179
+
180
+ The challenge cycle automatically applies auto-accepted proposals. HIGH/CRITICAL blast radius or impact at/above the configured threshold requires a completed LLM review before automatic acceptance/application. Missing reviewers, errors, malformed responses, and abstentions leave the proposal pending with `challenge_state: deferred`; the cycle reports a `deferred` count. The scheduled actor constructs a transformer client and requests a JSON verdict; standalone clients use their injected reviewer. New proposals have priority over due retries. Incomplete or unavailable reviews use persisted exponential backoff (300 seconds initially, capped at 3600) and expire after three attempts. Configure `review_retry_seconds`, `review_max_retry_seconds`, and `review_max_attempts` under `lex-synapse.challenge`. Explicit operator approval can still reopen an expired proposal. Lower-impact proposals retain conflict-based automatic decisions. Explicit operator approval remains a separate application path.
181
+
182
+ ### Idle decay timing
183
+
184
+ Only active synapses with at least one complete hour since their most recent signal are eligible for idle decay. The actor applies `0.998 ** elapsed_whole_hours`, measuring from the latest of creation time, last signal, and the persisted `last_decay_at` checkpoint. A recent signal resets the idle interval. Fractional hours remain for the next tick. A delayed tick or restart catches up the current idle interval; repeated ticks do not apply the same hours twice. Confidence is multiplied in SQL and the checkpoint advances in the same conditional update, without an explicit row lock. Changed checkpoints and newly arrived signals prevent stale ticks from writing. Existing rows receive the upgrade timestamp as their initial checkpoint so pre-upgrade idle hours are not charged twice.
185
+
162
186
  ## License
163
187
 
164
188
  MIT
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/extensions/transformer/client'
4
+
3
5
  require_relative '../runners/challenge'
4
6
 
5
7
  module Legion
@@ -9,6 +11,10 @@ module Legion
9
11
  class Challenge < Legion::Extensions::Actors::Every
10
12
  include Legion::Extensions::Synapse::Runners::Challenge
11
13
 
14
+ def args
15
+ { transformer_client: Legion::Extensions::Transformer::Client.new }
16
+ end
17
+
12
18
  def runner_class = self.class
13
19
 
14
20
  def runner_function
@@ -1,5 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/extensions/synapse/data/models/synapse'
4
+ require 'legion/extensions/synapse/data/models/synapse_signal'
5
+ require 'legion/extensions/synapse/helpers/confidence'
6
+
3
7
  module Legion
4
8
  module Extensions
5
9
  module Synapse
@@ -11,18 +15,31 @@ module Legion
11
15
  def check_subtask? = false
12
16
  def generate_task? = false
13
17
 
14
- def action(**)
18
+ def action(now: Time.now, **)
15
19
  return { status: :skipped, reason: :no_data } unless defined?(Legion::Data)
16
20
 
17
- Data::Model.define_synapse_model
18
- decayed = 0
21
+ Legion::Extensions::Synapse::Data::Model.define_synapse_model
22
+ Legion::Extensions::Synapse::Data::Model.define_synapse_signal_model
23
+ unless defined?(Legion::Extensions::Synapse::Data::Model::Synapse) &&
24
+ defined?(Legion::Extensions::Synapse::Data::Model::SynapseSignal)
25
+ return { status: :skipped, reason: :no_data }
26
+ end
19
27
 
20
- Data::Model::Synapse.where(status: 'active').each do |synapse|
21
- new_conf = Helpers::Confidence.decay(synapse.confidence, hours: 1)
22
- next if new_conf == synapse.confidence
28
+ model = Legion::Extensions::Synapse::Data::Model::Synapse
29
+ signals = Legion::Extensions::Synapse::Data::Model::SynapseSignal
30
+ decayed = 0
31
+ model.where(status: 'active').each do |synapse|
32
+ last_signal = signals.where(synapse_id: synapse.id).order(Sequel.desc(:created_at)).first&.created_at
33
+ idle_start = [synapse.created_at, last_signal, synapse.last_decay_at].compact.max
34
+ hours = ((now - idle_start) / 3600).floor
35
+ next unless hours.positive?
23
36
 
24
- synapse.update(confidence: new_conf)
25
- decayed += 1
37
+ factor = Legion::Extensions::Synapse::Helpers::Confidence::DECAY_RATE**hours
38
+ recent_activity = signals.where(synapse_id: synapse.id).where { created_at > idle_start }
39
+ changed = model.where(id: synapse.id, status: 'active', last_decay_at: synapse.last_decay_at)
40
+ .exclude(recent_activity.exists)
41
+ .update(confidence: Sequel[:confidence] * factor, last_decay_at: idle_start + (hours * 3600))
42
+ decayed += changed if synapse.confidence.positive?
26
43
  end
27
44
 
28
45
  { decayed: decayed }
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/extensions/synapse/data/models/synapse'
4
+ require 'legion/extensions/synapse/data/models/synapse_signal'
5
+
3
6
  module Legion
4
7
  module Extensions
5
8
  module Synapse
@@ -14,8 +17,14 @@ module Legion
14
17
  def action(**)
15
18
  return { status: :skipped, reason: :no_data } unless defined?(Legion::Data)
16
19
 
20
+ Legion::Extensions::Synapse::Data::Model.define_synapse_model
21
+ Legion::Extensions::Synapse::Data::Model.define_synapse_signal_model
22
+ unless defined?(Legion::Extensions::Synapse::Data::Model::Synapse) &&
23
+ defined?(Legion::Extensions::Synapse::Data::Model::SynapseSignal)
24
+ return { status: :skipped, reason: :no_data }
25
+ end
26
+
17
27
  results = { spikes: 0, droughts: 0, updated: 0 }
18
- return results unless defined?(Legion::Extensions::Synapse::Data::Model::Synapse)
19
28
 
20
29
  cutoff = Time.now - 60
21
30
  window_seconds = 60.0
@@ -27,9 +36,8 @@ module Legion
27
36
  .group_and_count(:synapse_id)
28
37
  .as_hash(:synapse_id, :count)
29
38
 
30
- # Fetch only active synapses with a nonzero baseline — eager-load to avoid N+1
39
+ # Include new zero baselines so the first traffic window can initialize the EWMA
31
40
  active_synapses = synapse_model.where(status: 'active')
32
- .where { baseline_throughput > 0 } # rubocop:disable Style/NumericPredicate
33
41
  .all
34
42
  return results if active_synapses.empty?
35
43
 
@@ -48,6 +56,8 @@ module Legion
48
56
  end
49
57
 
50
58
  new_baseline = Helpers::Homeostasis.update_baseline(baseline, current)
59
+ next if new_baseline == baseline
60
+
51
61
  updates << { synapse_id: synapse.id, baseline_throughput: new_baseline }
52
62
  results[:updated] += 1
53
63
  end
@@ -84,8 +84,12 @@ module Legion
84
84
  { success: true, proposal_id: proposal_id, status: status }
85
85
  end
86
86
 
87
- def challenge_proposal(proposal_id:)
88
- super(proposal_id: proposal_id, transformer_client: @transformer_client)
87
+ def challenge_proposal(proposal_id:, transformer_client: @transformer_client, **)
88
+ super(proposal_id: proposal_id, transformer_client: transformer_client)
89
+ end
90
+
91
+ def run_challenge_cycle(transformer_client: @transformer_client, **)
92
+ super(transformer_client: transformer_client)
89
93
  end
90
94
 
91
95
  def challenges(proposal_id:)
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ change do
5
+ alter_table(:synapses) do
6
+ add_column :consecutive_successes, Integer, null: false, default: 0
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ change do
5
+ alter_table(:synapse_signals) do
6
+ add_column :target_runner_class, String
7
+ add_column :target_function, String
8
+ add_index :task_id
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ up do
5
+ alter_table(:synapses) do
6
+ add_column :last_decay_at, DateTime
7
+ end
8
+ from(:synapses).update(last_decay_at: Sequel::CURRENT_TIMESTAMP)
9
+ end
10
+
11
+ down do
12
+ alter_table(:synapses) do
13
+ drop_column :last_decay_at
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ change do
5
+ alter_table(:synapse_signals) do
6
+ add_column :success_credit_pending, TrueClass, null: false, default: false
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ change do
5
+ alter_table(:synapse_proposals) do
6
+ add_column :review_attempts, Integer, null: false, default: 0
7
+ add_column :next_review_at, DateTime
8
+ end
9
+ end
10
+ end
@@ -8,7 +8,7 @@ module Legion
8
8
  VALID_VERDICTS = %w[support challenge abstain].freeze
9
9
  VALID_CHALLENGER_TYPES = %w[conflict llm].freeze
10
10
  VALID_OUTCOMES = %w[correct incorrect].freeze
11
- VALID_CHALLENGE_STATES = %w[challenging challenged].freeze
11
+ VALID_CHALLENGE_STATES = %w[challenging challenged deferred].freeze
12
12
 
13
13
  IMPACT_WEIGHTS = {
14
14
  'llm_transform' => 0.7,
@@ -25,6 +25,9 @@ module Legion
25
25
  llm_engine_options: { temperature: 0.2, max_tokens: 512 },
26
26
  outcome_observation_window: 50,
27
27
  max_per_cycle: 5,
28
+ review_max_attempts: 3,
29
+ review_retry_seconds: 300,
30
+ review_max_retry_seconds: 3600,
28
31
  challenger_starting_confidence: 0.5,
29
32
  challenger_correct_adjustment: 0.05,
30
33
  challenger_incorrect_adjustment: -0.08
@@ -21,9 +21,9 @@ module Legion
21
21
  CONSECUTIVE_BONUS_THRESHOLD = 50
22
22
 
23
23
  AUTONOMY_RANGES = {
24
- observe: 0.0..0.3,
25
- filter: 0.3..0.6,
26
- transform: 0.6..0.8,
24
+ observe: 0.0...0.3,
25
+ filter: 0.3...0.6,
26
+ transform: 0.6...0.8,
27
27
  autonomous: 0.8..1.0
28
28
  }.freeze
29
29
 
@@ -45,6 +45,20 @@ module Legion
45
45
  clamp(confidence * (DECAY_RATE**hours))
46
46
  end
47
47
 
48
+ # Arithmetic uses the current stored values, never a caller's stale snapshot.
49
+ def adjust_persisted(synapse:, event:, **)
50
+ delta = ADJUSTMENTS.fetch(event)
51
+ streak = event == :success ? Sequel[:consecutive_successes] + 1 : 0
52
+ adjustment = delta
53
+ adjustment += Sequel.case({ (streak > CONSECUTIVE_BONUS_THRESHOLD) => ADJUSTMENTS[:consecutive_bonus] }, 0) if event == :success
54
+ confidence = Sequel[:confidence] + adjustment
55
+ clamped = Sequel.case({ (confidence < 0.0) => 0.0, (confidence > 1.0) => 1.0 }, confidence)
56
+ synapse.class.where(id: synapse.id).update(confidence: clamped, consecutive_successes: streak)
57
+ synapse.refresh
58
+ Legion::Events.emit('synapse.confidence_update', delta: delta, event: event, new_confidence: synapse.confidence) if defined?(Legion::Events)
59
+ synapse.confidence
60
+ end
61
+
48
62
  def autonomy_mode(confidence)
49
63
  AUTONOMY_RANGES.each do |mode, range|
50
64
  return mode if range.include?(confidence)
@@ -25,6 +25,8 @@ module Legion
25
25
  end
26
26
 
27
27
  def update_baseline(current_baseline, new_sample, alpha: 0.1)
28
+ return new_sample if current_baseline.zero? || current_baseline == new_sample
29
+
28
30
  ((1 - alpha) * current_baseline) + (alpha * new_sample)
29
31
  end
30
32
 
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/logging/helper'
4
+ require 'legion/extensions/synapse/client'
5
+ require 'legion/extensions/conditioner/client'
6
+ require 'legion/extensions/transformer/client'
7
+
8
+ module Legion
9
+ module Extensions
10
+ module Synapse
11
+ # Optional LegionIO/lex-tasker integration. Standalone clients need neither host.
12
+ module Integration
13
+ @event_mutex = Mutex.new
14
+
15
+ class << self
16
+ include Legion::Logging::Helper
17
+
18
+ def evaluate_relationship(relationship_id:, payload:, **)
19
+ Legion::Extensions::Synapse::Data::Model.define_synapse_model
20
+ synapse = Legion::Extensions::Synapse::Data::Model::Synapse.first(relationship_id: relationship_id)
21
+ return { wrapped: false } unless synapse
22
+
23
+ client = Legion::Extensions::Synapse::Client.new(
24
+ conditioner_client: Legion::Extensions::Conditioner::Client.new,
25
+ transformer_client: Legion::Extensions::Transformer::Client.new
26
+ )
27
+ evaluation = client.evaluate(synapse_id: synapse.id, payload: payload)
28
+ evaluation.merge(wrapped: true, allowed: evaluation[:success] == true && evaluation[:passed] == true)
29
+ end
30
+
31
+ def attach_task(signal_id:, task_id:, runner_class:, function:, **)
32
+ return unless signal_id
33
+
34
+ Legion::Extensions::Synapse::Data::Model::SynapseSignal.where(id: signal_id).update(
35
+ task_id: task_id, target_runner_class: runner_class.to_s, target_function: function.to_s
36
+ )
37
+ end
38
+
39
+ def record_outcome(task_id:, outcome:, runner_class:, function:, **)
40
+ raise ArgumentError, 'invalid task outcome' unless %i[success failed].include?(outcome)
41
+ return { recorded: 0 } unless task_id
42
+
43
+ Legion::Extensions::Synapse::Data::Model.define_synapse_signal_model
44
+ # Data may be unavailable during host startup/shutdown; model definitions are lazy.
45
+ return { recorded: 0 } unless Legion::Extensions::Synapse::Data::Model.const_defined?(:SynapseSignal, false)
46
+
47
+ model = Legion::Extensions::Synapse::Data::Model::SynapseSignal
48
+ recorded = 0
49
+ model.where(task_id: task_id, downstream_outcome: nil,
50
+ target_runner_class: runner_class.to_s, target_function: function.to_s).all.each do |signal|
51
+ if outcome == :failed
52
+ result = Legion::Extensions::Synapse::Client.new.handle_pain(
53
+ synapse_id: signal.synapse_id, task_id: task_id, signal_id: signal.id
54
+ )
55
+ recorded += 1 if result[:success] && !result[:duplicate]
56
+ else
57
+ recorded += record_success(signal: signal)
58
+ end
59
+ end
60
+ { recorded: recorded }
61
+ end
62
+
63
+ def install_events!(events:, **)
64
+ @event_mutex.synchronize do
65
+ return if @event_bus.equal?(events)
66
+
67
+ @event_bus = events
68
+ events.on('task.failed') { |event| record_outcome(**event, outcome: :failed) }
69
+ events.on('task.completed') { |event| record_outcome(**event, outcome: :success) }
70
+ end
71
+ end
72
+
73
+ private
74
+
75
+ def record_success(signal:)
76
+ # Only the outcome claim and its confidence credit are atomic; pain/revert
77
+ # never run within an outer outcome transaction.
78
+ signal.db.transaction do
79
+ changed = signal.class.where(id: signal.id, downstream_outcome: nil).update(
80
+ downstream_outcome: 'success', success_credit_pending: false
81
+ )
82
+ if changed.positive? && signal.success_credit_pending
83
+ Legion::Extensions::Synapse::Data::Model.define_synapse_model
84
+ synapse = Legion::Extensions::Synapse::Data::Model::Synapse[signal.synapse_id]
85
+ Legion::Extensions::Synapse::Helpers::Confidence.adjust_persisted(synapse: synapse, event: :success)
86
+ end
87
+ changed
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
95
+
96
+ # Events belongs to the optional LegionIO host, not the standalone extension dependencies.
97
+ Legion::Extensions::Synapse::Integration.install_events!(events: Legion::Events) if defined?(Legion::Events)
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'legion/logging/helper'
4
+
3
5
  require_relative '../helpers/challenge'
4
6
  require_relative '../helpers/confidence'
5
7
  require_relative '../data/models/synapse'
@@ -14,15 +16,18 @@ module Legion
14
16
  module Synapse
15
17
  module Runners
16
18
  module Challenge
19
+ include Legion::Logging::Helper
17
20
  include BlastRadius
18
21
 
19
22
  def pending_challenges
20
23
  Data::Model.define_synapse_proposal_model
21
- Data::Model::SynapseProposal.where(status: 'pending', challenge_state: nil)
22
- .order(Sequel.asc(:id)).all
24
+ Data::Model::SynapseProposal.where(status: 'pending')
25
+ .where(Sequel.|({ challenge_state: nil }, { challenge_state: 'deferred' }))
26
+ .where(Sequel.|({ next_review_at: nil }, Sequel[:next_review_at] <= Time.now))
27
+ .order(Sequel.case({ { challenge_state: nil } => 0 }, 1), Sequel.asc(:id)).all
23
28
  end
24
29
 
25
- def challenge_proposal(proposal_id:, transformer_client: nil)
30
+ def challenge_proposal(proposal_id:, transformer_client: nil, **)
26
31
  Data::Model.define_synapse_proposal_model
27
32
  Data::Model.define_synapse_challenge_model
28
33
  Data::Model.define_synapse_model
@@ -32,23 +37,36 @@ module Legion
32
37
 
33
38
  proposal = Data::Model::SynapseProposal[proposal_id]
34
39
  return { success: false, error: 'proposal not found' } unless proposal
35
- return { success: false, error: 'proposal not challengeable' } unless proposal.status == 'pending' && proposal.challenge_state.nil?
40
+
41
+ challengeable = proposal.status == 'pending' && [nil, 'deferred'].include?(proposal.challenge_state)
42
+ return { success: false, error: 'proposal not challengeable' } unless challengeable
36
43
 
37
44
  synapse = Data::Model::Synapse[proposal.synapse_id]
38
45
  return { success: false, error: 'synapse not found' } unless synapse
39
46
 
40
- proposal.update(challenge_state: 'challenging')
47
+ if proposal.next_review_at && proposal.next_review_at > Time.now
48
+ return { success: false, deferred: true, proposal_id: proposal.id, reason: :review_backoff }
49
+ end
50
+
51
+ claimed = Data::Model::SynapseProposal.where(id: proposal.id, status: 'pending',
52
+ challenge_state: proposal.challenge_state,
53
+ review_attempts: proposal.review_attempts).update(challenge_state: 'challenging')
54
+ return { success: false, error: 'proposal already claimed' } if claimed.zero?
55
+
56
+ proposal.refresh
41
57
 
42
58
  impact = calculate_impact_score(proposal, synapse)
43
59
  confidence_impact = estimate_confidence_impact(proposal, synapse)
44
60
  proposal.update(impact_score: impact, estimated_confidence_impact: confidence_impact)
45
61
 
46
- conflict_check(proposal)
62
+ if review_required?(impact: impact, synapse: synapse)
63
+ return defer_review(proposal: proposal, reason: :reviewer_unavailable) unless transformer_client
47
64
 
48
- needs_llm = Helpers::Challenge.above_impact_threshold?(impact) ||
49
- requires_llm_review?(synapse.blast_radius.to_s)
50
- llm_challenge(proposal, synapse, transformer_client) if needs_llm && transformer_client
65
+ review = llm_challenge(proposal, synapse, transformer_client)
66
+ return defer_review(proposal: proposal, reason: :review_incomplete) if review.verdict == 'abstain'
67
+ end
51
68
 
69
+ conflict_check(proposal)
52
70
  aggregate_challenges(proposal)
53
71
  end
54
72
 
@@ -88,7 +106,9 @@ module Legion
88
106
  { success: true, proposal_id: proposal_id, success_rate: success_rate, resolved: challenges.size }
89
107
  end
90
108
 
91
- def apply_proposal(proposal_id:)
109
+ def apply_proposal(proposal_id:, **)
110
+ Data::Model.define_synapse_signal_model
111
+ Data::Model.define_synapse_challenge_model
92
112
  Data::Model.define_synapse_proposal_model
93
113
  Data::Model.define_synapse_model
94
114
 
@@ -100,6 +120,11 @@ module Legion
100
120
  synapse = Data::Model::Synapse[proposal.synapse_id]
101
121
  return { success: false, error: 'synapse not found' } unless synapse
102
122
 
123
+ if proposal.status == 'auto_accepted' && review_required?(impact: calculate_impact_score(proposal, synapse), synapse: synapse)
124
+ reviewed = Data::Model::SynapseChallenge.where(proposal_id: proposal.id, challenger_type: 'llm', verdict: %w[support challenge]).any?
125
+ return defer_review(proposal: proposal, reason: :reviewer_unavailable) unless reviewed
126
+ end
127
+
103
128
  mutation = mutation_for_proposal(proposal)
104
129
  return { success: false, error: "unsupported proposal_type: #{proposal.proposal_type}" } unless mutation
105
130
 
@@ -115,24 +140,26 @@ module Legion
115
140
  result.merge(proposal_id: proposal.id, status: 'applied', decision: 'applied')
116
141
  end
117
142
 
118
- def run_challenge_cycle(transformer_client: nil)
143
+ def run_challenge_cycle(transformer_client: nil, **)
119
144
  Data::Model.define_synapse_proposal_model
120
145
  Data::Model.define_synapse_challenge_model
121
- return { challenged: 0, applied: 0, resolved: 0 } unless Helpers::Challenge.enabled?
146
+ return { challenged: 0, deferred: 0, applied: 0, resolved: 0 } unless Helpers::Challenge.enabled?
122
147
 
123
148
  settings = Helpers::Challenge.settings
124
149
  max = settings[:max_per_cycle] || 5
125
150
 
126
151
  challenged = 0
152
+ deferred = 0
127
153
  pending_challenges.first(max).each do |proposal|
128
- challenge_proposal(proposal_id: proposal.id, transformer_client: transformer_client)
129
- challenged += 1
154
+ result = challenge_proposal(proposal_id: proposal.id, transformer_client: transformer_client)
155
+ result[:deferred] ? deferred += 1 : challenged += 1
130
156
  end
131
157
 
132
158
  applied = 0
133
159
  Data::Model::SynapseProposal.where(status: 'auto_accepted').order(Sequel.asc(:id)).limit(max).each do |proposal|
134
160
  result = apply_proposal(proposal_id: proposal.id)
135
161
  applied += 1 if result[:success]
162
+ deferred += 1 if result[:deferred]
136
163
  end
137
164
 
138
165
  resolved = 0
@@ -152,11 +179,27 @@ module Legion
152
179
  resolved += 1
153
180
  end
154
181
 
155
- { challenged: challenged, applied: applied, resolved: resolved }
182
+ { challenged: challenged, deferred: deferred, applied: applied, resolved: resolved }
156
183
  end
157
184
 
158
185
  private
159
186
 
187
+ def review_required?(impact:, synapse:)
188
+ Legion::Extensions::Synapse::Helpers::Challenge.above_impact_threshold?(impact) ||
189
+ requires_llm_review?(synapse.blast_radius.to_s)
190
+ end
191
+
192
+ def defer_review(proposal:, reason:)
193
+ settings = Legion::Extensions::Synapse::Helpers::Challenge.settings
194
+ attempts = proposal.review_attempts + 1
195
+ expired = attempts >= settings[:review_max_attempts]
196
+ delay = [settings[:review_retry_seconds] * (2**(attempts - 1)), settings[:review_max_retry_seconds]].min
197
+ proposal.update(status: expired ? 'expired' : 'pending', challenge_state: 'deferred', challenge_score: nil,
198
+ review_attempts: attempts, next_review_at: expired ? nil : Time.now + delay)
199
+ { success: false, deferred: !expired, expired: expired, proposal_id: proposal.id,
200
+ decision: expired ? 'expired' : 'deferred', reason: reason }
201
+ end
202
+
160
203
  def mutation_for_proposal(proposal)
161
204
  case proposal.proposal_type
162
205
  when 'llm_transform', 'transform_mutation'
@@ -208,7 +251,7 @@ module Legion
208
251
  challenger_confidence: llm_confidence
209
252
  )
210
253
  rescue StandardError => e
211
- log.warn("Challenge LLM call failed: #{e.message}")
254
+ handle_exception(e, level: :warn, operation: :challenge_llm, proposal_id: proposal.id)
212
255
  Data::Model::SynapseChallenge.create(
213
256
  proposal_id: proposal.id, challenger_type: 'llm',
214
257
  verdict: 'abstain', reasoning: "LLM error: #{e.message}",
@@ -269,12 +312,16 @@ module Legion
269
312
  "Rationale: #{proposal.rationale}\n" \
270
313
  "Proposed inputs: #{proposal.inputs}\n" \
271
314
  "Proposed output: #{proposal.output}\n\n" \
272
- "Is this change sound? Respond in exactly this format:\n" \
273
- "VERDICT: SUPPORT or CHALLENGE or ABSTAIN\n" \
274
- 'REASONING: one sentence explanation'
315
+ 'Is this change sound? Respond with a JSON object containing "verdict" ("support", "challenge", or "abstain") ' \
316
+ 'and "reasoning" (one sentence explanation).'
275
317
  end
276
318
 
277
319
  def parse_llm_verdict(response)
320
+ if response.is_a?(Hash)
321
+ verdict = response[:verdict].to_s.downcase
322
+ verdict = 'abstain' unless Legion::Extensions::Synapse::Helpers::Challenge::VALID_VERDICTS.include?(verdict)
323
+ return [verdict, response[:reasoning].to_s.slice(0, 200)]
324
+ end
278
325
  return ['abstain', 'no LLM response'] unless response.is_a?(String)
279
326
 
280
327
  text = response.to_s.strip
@@ -14,7 +14,7 @@ module Legion
14
14
  module Evaluate
15
15
  include Propose
16
16
 
17
- def evaluate(synapse_id:, payload: {}, conditioner_client: nil, transformer_client: nil)
17
+ def evaluate(synapse_id:, payload: {}, conditioner_client: nil, transformer_client: nil, **)
18
18
  Data::Model.define_synapse_model
19
19
  Data::Model.define_synapse_signal_model
20
20
  Data::Model.define_synapse_proposal_model
@@ -22,6 +22,7 @@ module Legion
22
22
  return { success: false, error: 'synapse not found' } unless synapse
23
23
  return { success: false, error: 'synapse not active' } unless Helpers::Confidence::EVALUABLE_STATUSES.include?(synapse.status)
24
24
 
25
+ proposal_eligible = Legion::Extensions::Synapse::Helpers::Confidence.can_self_modify?(synapse.confidence)
25
26
  mode = Helpers::Confidence.autonomy_mode(synapse.confidence)
26
27
  start_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC, :millisecond)
27
28
 
@@ -52,18 +53,15 @@ module Legion
52
53
  end
53
54
 
54
55
  # Step 3: Record signal
55
- signal_record = record_signal(synapse, attention_result[:passed], transform_result[:success], elapsed)
56
-
57
- # Step 4: Adjust confidence (skip if run_transform already penalized for validation failure)
58
- new_confidence = synapse.confidence
59
- unless transform_result[:validation_failure]
60
- event = transform_result[:success] ? :success : :failure
61
- new_confidence = Helpers::Confidence.adjust(synapse.confidence, event)
62
- synapse.update(confidence: new_confidence)
63
- end
56
+ signal_record = record_signal(synapse, attention_result[:observed_passed], transform_result[:success], elapsed,
57
+ success_credit_pending: mode == :observe && transform_result[:success])
58
+
59
+ # Step 4: Observation and correct filtering are neutral; transform failures are penalized once.
60
+ new_confidence = adjust_evaluation_confidence(synapse: synapse, transform_result: transform_result,
61
+ mode: mode, attention_result: attention_result)
64
62
 
65
63
  # Step 5: Generate proposals if autonomous
66
- if Helpers::Confidence.can_self_modify?(new_confidence) && Helpers::Proposals.reactive?
64
+ if (proposal_eligible || Helpers::Confidence.can_self_modify?(new_confidence)) && Helpers::Proposals.reactive?
67
65
  propose_reactive(
68
66
  synapse: synapse, payload: payload, signal_id: signal_record&.id,
69
67
  attention_result: attention_result, transform_result: transform_result,
@@ -77,23 +75,28 @@ module Legion
77
75
  passed: attention_result[:passed],
78
76
  transformed: transform_result[:transformed] == true,
79
77
  result: transform_result[:result],
80
- latency_ms: elapsed
78
+ latency_ms: elapsed,
79
+ signal_id: signal_record.id
81
80
  }
82
81
  end
83
82
 
84
83
  private
85
84
 
85
+ def adjust_evaluation_confidence(synapse:, transform_result:, mode:, attention_result:)
86
+ return synapse.confidence if mode == :observe || !attention_result[:passed]
87
+ return synapse.confidence if transform_result[:validation_failure]
88
+
89
+ event = transform_result[:success] ? :success : :failure
90
+ Legion::Extensions::Synapse::Helpers::Confidence.adjust_persisted(synapse: synapse, event: event)
91
+ end
92
+
86
93
  def check_attention(synapse, payload, mode, conditioner_client)
87
- return { passed: true } if synapse.attention.nil? || synapse.attention.empty?
94
+ return { passed: true, observed_passed: true } if synapse.attention.nil? || synapse.attention.empty?
88
95
  return { passed: mode == :observe, unavailable: true, error: 'conditioner unavailable' } unless conditioner_client.respond_to?(:evaluate)
89
96
 
90
97
  result = conditioner_client.evaluate(conditions: Legion::JSON.load(synapse.attention), values: payload)
91
- passed = result[:valid]
92
-
93
- # In OBSERVE mode, always pass through regardless of result
94
- passed = true if mode == :observe
95
-
96
- { passed: passed }
98
+ # Preserve the measured verdict even when observe mode permits pass-through.
99
+ { passed: mode == :observe || result[:valid], observed_passed: result[:valid] }
97
100
  end
98
101
 
99
102
  def run_transform(synapse, payload, transformer_client)
@@ -111,18 +114,18 @@ module Legion
111
114
  if result[:success]
112
115
  { success: true, transformed: true, result: result[:result] }
113
116
  else
114
- new_conf = Helpers::Confidence.adjust(synapse.confidence, :validation_failure)
115
- synapse.update(confidence: new_conf)
117
+ Legion::Extensions::Synapse::Helpers::Confidence.adjust_persisted(synapse: synapse, event: :validation_failure)
116
118
  { success: false, result: payload, error: result[:errors], validation_failure: true }
117
119
  end
118
120
  end
119
121
 
120
- def record_signal(synapse, passed_attention, transform_success, latency_ms)
122
+ def record_signal(synapse, passed_attention, transform_success, latency_ms, success_credit_pending: false)
121
123
  Data::Model::SynapseSignal.create(
122
- synapse_id: synapse.id,
123
- passed_attention: passed_attention,
124
- transform_success: transform_success,
125
- latency_ms: latency_ms.to_i
124
+ synapse_id: synapse.id,
125
+ passed_attention: passed_attention,
126
+ transform_success: transform_success,
127
+ latency_ms: latency_ms.to_i,
128
+ success_credit_pending: success_credit_pending
126
129
  )
127
130
  end
128
131
 
@@ -14,24 +14,27 @@ module Legion
14
14
 
15
15
  CONSECUTIVE_FAILURE_THRESHOLD = 3
16
16
 
17
- def handle_pain(synapse_id:, task_id: nil)
17
+ def handle_pain(synapse_id:, task_id: nil, signal_id: nil, **)
18
18
  Data::Model.define_synapse_model
19
19
  Data::Model.define_synapse_signal_model
20
20
  synapse = Data::Model::Synapse[synapse_id]
21
21
  return { success: false, error: 'synapse not found' } unless synapse
22
22
 
23
- # Record failed signal
24
- Data::Model::SynapseSignal.create(
25
- synapse_id: synapse.id,
26
- task_id: task_id,
27
- passed_attention: true,
28
- transform_success: true,
29
- downstream_outcome: 'failed'
30
- )
23
+ # A task completion updates its original evaluation; repeated events are neutral.
24
+ if signal_id
25
+ changed = Legion::Extensions::Synapse::Data::Model::SynapseSignal
26
+ .where(id: signal_id, synapse_id: synapse_id, task_id: task_id, downstream_outcome: nil)
27
+ .update(downstream_outcome: 'failed', success_credit_pending: false)
28
+ return { success: true, duplicate: true } if changed.zero?
29
+ else
30
+ Legion::Extensions::Synapse::Data::Model::SynapseSignal.create(
31
+ synapse_id: synapse.id, task_id: task_id, passed_attention: true,
32
+ transform_success: true, downstream_outcome: 'failed'
33
+ )
34
+ end
31
35
 
32
36
  # Adjust confidence
33
- new_confidence = Helpers::Confidence.adjust(synapse.confidence, :failure)
34
- synapse.update(confidence: new_confidence)
37
+ new_confidence = Legion::Extensions::Synapse::Helpers::Confidence.adjust_persisted(synapse: synapse, event: :failure)
35
38
 
36
39
  # Check consecutive failures
37
40
  consecutive = count_consecutive_failures(synapse)
@@ -9,7 +9,7 @@ module Legion
9
9
  module Synapse
10
10
  module Runners
11
11
  module Report
12
- def report(synapse_id:)
12
+ def report(synapse_id:, **)
13
13
  Data::Model.define_synapse_model
14
14
  Data::Model.define_synapse_mutation_model
15
15
  Data::Model.define_synapse_signal_model
@@ -22,28 +22,35 @@ module Legion
22
22
 
23
23
  total_recent = recent_signals.count
24
24
  successful = recent_signals.where(downstream_outcome: 'success').count
25
- success_rate = total_recent.positive? ? (successful.to_f / total_recent).round(4) : 0.0
25
+ failed = recent_signals.where(downstream_outcome: 'failed').count
26
+ completed = successful + failed
27
+ success_rate = completed.positive? ? (successful.to_f / completed).round(4) : nil
26
28
 
27
29
  last_mutation = synapse.mutations_dataset.order(Sequel.desc(:id)).first
28
30
 
29
31
  {
30
- success: true,
31
- synapse_id: synapse.id,
32
- confidence: synapse.confidence,
33
- status: synapse.status,
34
- origin: synapse.origin,
35
- version: synapse.version,
36
- signals_24h: total_recent,
37
- success_rate: success_rate,
38
- total_signals: signals.count,
39
- last_mutation: if last_mutation
40
- {
41
- type: last_mutation.mutation_type,
42
- trigger: last_mutation.trigger,
43
- version: last_mutation.version,
44
- outcome: last_mutation.outcome
45
- }
46
- end
32
+ success: true,
33
+ synapse_id: synapse.id,
34
+ confidence: synapse.confidence,
35
+ status: synapse.status,
36
+ origin: synapse.origin,
37
+ version: synapse.version,
38
+ signals_24h: total_recent,
39
+ success_rate: success_rate,
40
+ completed_outcomes_24h: completed,
41
+ successful_outcomes_24h: successful,
42
+ failed_outcomes_24h: failed,
43
+ unresolved_signals_24h: total_recent - completed,
44
+ evaluation_successes_24h: recent_signals.where(transform_success: true).count,
45
+ total_signals: signals.count,
46
+ last_mutation: if last_mutation
47
+ {
48
+ type: last_mutation.mutation_type,
49
+ trigger: last_mutation.trigger,
50
+ version: last_mutation.version,
51
+ outcome: last_mutation.outcome
52
+ }
53
+ end
47
54
  }
48
55
  end
49
56
  end
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module Extensions
5
5
  module Synapse
6
- VERSION = '0.4.15'
6
+ VERSION = '0.4.30'
7
7
  end
8
8
  end
9
9
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'legion/extensions/synapse/version'
4
4
  require_relative 'synapse/client'
5
+ require 'legion/extensions/synapse/integration'
5
6
 
6
7
  module Legion
7
8
  module Extensions
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lex-synapse
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.15
4
+ version: 0.4.30
5
5
  platform: ruby
6
6
  authors:
7
7
  - Esity
@@ -173,6 +173,11 @@ files:
173
173
  - lib/legion/extensions/synapse/data/migrations/005_add_synapse_challenges.rb
174
174
  - lib/legion/extensions/synapse/data/migrations/006_add_slow_query_indexes.rb
175
175
  - lib/legion/extensions/synapse/data/migrations/007_add_blast_radius.rb
176
+ - lib/legion/extensions/synapse/data/migrations/008_add_consecutive_successes.rb
177
+ - lib/legion/extensions/synapse/data/migrations/009_correlate_task_targets.rb
178
+ - lib/legion/extensions/synapse/data/migrations/010_add_last_decay_at.rb
179
+ - lib/legion/extensions/synapse/data/migrations/011_add_success_credit_pending.rb
180
+ - lib/legion/extensions/synapse/data/migrations/012_add_review_retries.rb
176
181
  - lib/legion/extensions/synapse/data/models/synapse.rb
177
182
  - lib/legion/extensions/synapse/data/models/synapse_challenge.rb
178
183
  - lib/legion/extensions/synapse/data/models/synapse_mutation.rb
@@ -183,6 +188,7 @@ files:
183
188
  - lib/legion/extensions/synapse/helpers/homeostasis.rb
184
189
  - lib/legion/extensions/synapse/helpers/proposals.rb
185
190
  - lib/legion/extensions/synapse/helpers/relationship_wrapper.rb
191
+ - lib/legion/extensions/synapse/integration.rb
186
192
  - lib/legion/extensions/synapse/runners/blast_radius.rb
187
193
  - lib/legion/extensions/synapse/runners/challenge.rb
188
194
  - lib/legion/extensions/synapse/runners/crystallize.rb