lex-synapse 0.4.15 → 0.4.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +74 -0
  3. data/CLAUDE.md +47 -38
  4. data/README.md +75 -45
  5. data/lib/legion/extensions/synapse/actors/challenge.rb +6 -0
  6. data/lib/legion/extensions/synapse/actors/decay.rb +25 -8
  7. data/lib/legion/extensions/synapse/actors/homeostasis.rb +13 -3
  8. data/lib/legion/extensions/synapse/client.rb +6 -2
  9. data/lib/legion/extensions/synapse/data/migrations/008_add_consecutive_successes.rb +9 -0
  10. data/lib/legion/extensions/synapse/data/migrations/009_correlate_task_targets.rb +11 -0
  11. data/lib/legion/extensions/synapse/data/migrations/010_add_last_decay_at.rb +16 -0
  12. data/lib/legion/extensions/synapse/data/migrations/011_add_success_credit_pending.rb +9 -0
  13. data/lib/legion/extensions/synapse/data/migrations/012_add_review_retries.rb +10 -0
  14. data/lib/legion/extensions/synapse/helpers/challenge.rb +5 -19
  15. data/lib/legion/extensions/synapse/helpers/confidence.rb +17 -3
  16. data/lib/legion/extensions/synapse/helpers/homeostasis.rb +2 -0
  17. data/lib/legion/extensions/synapse/helpers/proposals.rb +4 -17
  18. data/lib/legion/extensions/synapse/integration.rb +97 -0
  19. data/lib/legion/extensions/synapse/runners/challenge.rb +88 -36
  20. data/lib/legion/extensions/synapse/runners/crystallize.rb +24 -3
  21. data/lib/legion/extensions/synapse/runners/evaluate.rb +29 -26
  22. data/lib/legion/extensions/synapse/runners/pain.rb +14 -11
  23. data/lib/legion/extensions/synapse/runners/propose.rb +14 -8
  24. data/lib/legion/extensions/synapse/runners/report.rb +26 -19
  25. data/lib/legion/extensions/synapse/runners/retrieve.rb +8 -4
  26. data/lib/legion/extensions/synapse/settings.rb +53 -0
  27. data/lib/legion/extensions/synapse/version.rb +1 -1
  28. data/lib/legion/extensions/synapse.rb +1 -0
  29. metadata +8 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '037082609e6545e0a3581981a602d49afdd4a532cf4b15d166f0cf04fd3a746f'
4
- data.tar.gz: 42c81c769ef9f4367dec25d4713d5ab4bc4eb1491b88478bb365d5cbd3e2521e
3
+ metadata.gz: 4693d9ea96294087ce5edf804eec62b92106cb179748e4f4eeb78d65dcda9171
4
+ data.tar.gz: 0f816950bf81a388c2d2ee3fc06602fa15c78a0ca1b8f1c1e4662951a84d6507
5
5
  SHA512:
6
- metadata.gz: a5f60904a36dcf8fb276c75683485a7c4ef8207b9b1f1b6c03cae33bd392fa85d4fc44beb605aeae62f492be50be546b90b209021361d1105c9adc43306bfe21
7
- data.tar.gz: '059f003e2a808fe705e315b8c7c75c01631ac97ff86c2f675467dd563f37106ea039fc4aaddf32ad89315d4290226e0308d209c0e3df8ebd89644584ab315de9'
6
+ metadata.gz: b3c85871bc735230e8c5e2c73df99eea422ea028eb411462529ef9c6aa3599c4e691fe35b7979c5531659881233fd3f34903aa964bd391625910842d9becf8ae
7
+ data.tar.gz: 8cfbaf0885ad441ad2a462efa07e708bf3e521e7133c784704bec1ec3db143a6f3d8f9fcc07375a1eaa6d603210917b8f535914052e04ffdd3b5720b66463f12
data/CHANGELOG.md CHANGED
@@ -1,5 +1,79 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.33] - 2026-11-19
4
+ ### Fixed
5
+ - Feed periodic crystallization from the latest 1000 completed parent-child task edges, retaining threshold and duplicate checks (fixes #29).
6
+
7
+ ## [0.4.32] - 2026-11-19
8
+ ### Fixed
9
+ - Resolve proposal and review options through native extension settings, define defaults, and emit structured runtime exceptions while propagating programming errors (fixes #32).
10
+
11
+ ## [0.4.31] - 2026-11-19
12
+ ### Fixed
13
+ - Claim proposal application and persist routing state, mutation history, and applied status in one transaction (fixes #23).
14
+
15
+ ## [0.4.30] - 2026-11-19
16
+ ### Fixed
17
+ - Report unknown downstream success rates as nil when no outcomes are complete; document reviewed recovery, retry, and decay behavior (fixes #25).
18
+
19
+ ## [0.4.29] - 2026-11-19
20
+ ### Fixed
21
+ - Seed zero throughput baselines from the full first traffic window and avoid unchanged baseline writes, preventing false startup spikes (fixes #24).
22
+
23
+ ## [0.4.28] - 2026-11-19
24
+ ### Fixed
25
+ - Wire the scheduled reviewer through transformer JSON results, prioritize fresh proposals, and persist bounded exponential review retries with expiry (fixes #27).
26
+
27
+ ## [0.4.27] - 2026-11-19
28
+ ### Fixed
29
+ - 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).
30
+
31
+ ## [0.4.26] - 2026-11-19
32
+ ### Fixed
33
+ - 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).
34
+
35
+ ## [0.4.25] - 2026-11-19
36
+ ### Fixed
37
+ - 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).
38
+
39
+ ## [0.4.24] - 2026-11-19
40
+ ### Fixed
41
+ - Forward the injected reviewer through standalone client challenge cycles and initialize signals before application-time review checks (fixes #27).
42
+
43
+ ## [0.4.23] - 2026-11-19
44
+ ### Fixed
45
+ - Decay only complete idle hours since the latest activity, persisting a transactional checkpoint to prevent duplicate decay across retries and restarts (fixes #28).
46
+
47
+ ## [0.4.22] - 2026-11-19
48
+ ### Fixed
49
+ - Defer required challenge reviews when the reviewer is absent, fails, or abstains; retry deferred reviews and prevent unreviewed automatic application (fixes #27).
50
+
51
+ ## [0.4.21] - 2026-11-19
52
+ ### Fixed
53
+ - Calculate downstream success rate from completed outcomes only, expose unresolved and evaluation counts, and verify duplicate-safe task outcome correlation (fixes #25).
54
+
55
+ ## [0.4.20] - 2026-11-19
56
+ ### Fixed
57
+ - Keep observe-mode pass-through and clean attention rejections neutral for confidence and learning streaks; record the actual observed attention verdict (fixes #15).
58
+
59
+ ## [0.4.19] - 2026-11-19
60
+ ### Fixed
61
+ - Use non-overlapping autonomy ranges so mode labels match filtering, transformation, and self-modification at their inclusive lower thresholds (fixes #26).
62
+
63
+ ## [0.4.18] - 2026-11-19
64
+ ### Fixed
65
+ - Bootstrap zero throughput baselines from observed traffic without classifying the initial window as an anomaly; preserve batched homeostasis queries (fixes #24).
66
+
67
+ ## [0.4.17] - 2026-11-19
68
+ ### Fixed
69
+ - Initialize both homeostasis models on its first tick and report unavailable data explicitly (fixes #20).
70
+
71
+ ## [0.4.16] - 2026-11-19
72
+ ### Fixed
73
+ - Correct the documented hourly decay conversion to approximately 4.7% daily and a 14.4-day half-life (fixes #17).
74
+ - Preserve reactive repair eligibility across a failure penalty and persist consecutive successes for the existing >50 bonus, resetting the streak on failure (fixes #16).
75
+ - 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).
76
+
3
77
  ## [0.4.15] - 2026-10-29
4
78
  ### Fixed
5
79
  - 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,26 @@ 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
189
+
190
+ ### Proposal and review settings
191
+
192
+ Configure `extensions.synapse.proposals` and `extensions.synapse.challenge` using symbol keys through `Legion::Settings` (JSON configuration keys are normalized by the loader). Defaults are exposed by `Legion::Extensions::Synapse.default_settings`. Standalone clients use the same settings and defaults. Migrate the former top-level `lex-synapse` section to `extensions.synapse`; that legacy path is no longer read.
193
+
194
+ Scheduled crystallization samples the latest 1000 completed child tasks from the shared `tasks` table and groups their parent/child function IDs. At least 20 sampled edges are required for an observing emergent synapse. Failed or pending children do not count. Existing function pairs are skipped on later cycles. Standalone callers may still supply `signal_pairs:` explicitly; an empty array disables collection for that call.
@@ -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