fable-engine 1.3.1__py3-none-any.whl
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.
- fable_compressor.py +356 -0
- fable_engine/__init__.py +1 -0
- fable_engine/actions/__init__.py +291 -0
- fable_engine/actions/cas.py +182 -0
- fable_engine/actions/deliberation.py +523 -0
- fable_engine/actions/fleet.py +807 -0
- fable_engine/actions/lifecycle.py +298 -0
- fable_engine/actions/scrapers.py +116 -0
- fable_engine/actions/system3.py +815 -0
- fable_engine/browser.py +824 -0
- fable_engine/cas.py +974 -0
- fable_engine/fable_session.json +510 -0
- fable_engine/guards.py +283 -0
- fable_engine/schema.py +714 -0
- fable_engine/scrapers/__init__.py +32 -0
- fable_engine/scrapers/arxiv.py +115 -0
- fable_engine/scrapers/base.py +386 -0
- fable_engine/scrapers/github.py +129 -0
- fable_engine/scrapers/reddit.py +154 -0
- fable_engine/scrapers/web.py +120 -0
- fable_engine/scrapers/x.py +125 -0
- fable_engine/scrapers/youtube.py +132 -0
- fable_engine/server.py +414 -0
- fable_engine/session.py +1819 -0
- fable_engine/test_server.py +1362 -0
- fable_engine/updater.py +541 -0
- fable_engine-1.3.1.dist-info/LICENSE +22 -0
- fable_engine-1.3.1.dist-info/METADATA +173 -0
- fable_engine-1.3.1.dist-info/RECORD +104 -0
- fable_engine-1.3.1.dist-info/WHEEL +5 -0
- fable_engine-1.3.1.dist-info/entry_points.txt +5 -0
- fable_engine-1.3.1.dist-info/top_level.txt +6 -0
- fable_mode/__init__.py +3 -0
- fable_mode/__main__.py +4 -0
- fable_mode/adapters.py +1014 -0
- fable_mode/installer.py +553 -0
- fable_mode/launcher.py +437 -0
- fable_mode/manifest.py +142 -0
- fable_mode/resources.json +114 -0
- fable_mode/safety.py +103 -0
- fable_mode_entry.py +10 -0
- fable_v2/__init__.py +146 -0
- fable_v2/adapters.py +151 -0
- fable_v2/coder_fleet/__init__.py +100 -0
- fable_v2/coder_fleet/ast_tools.py +158 -0
- fable_v2/coder_fleet/compute.py +199 -0
- fable_v2/coder_fleet/design_engine.py +1316 -0
- fable_v2/coder_fleet/diagnostics.py +293 -0
- fable_v2/coder_fleet/fleet_dispatcher.py +214 -0
- fable_v2/coder_fleet/mock_auditor.py +306 -0
- fable_v2/coder_fleet/mutation.py +216 -0
- fable_v2/coder_fleet/property_oracle.py +260 -0
- fable_v2/coder_fleet/receipt_attestor.py +122 -0
- fable_v2/coder_fleet/red_team_swarm.py +908 -0
- fable_v2/coder_fleet/test_harness.py +198 -0
- fable_v2/coder_fleet/vector_engine.py +1287 -0
- fable_v2/coder_fleet/visual.py +357 -0
- fable_v2/coder_fleet/workspace.py +153 -0
- fable_v2/cortical/__init__.py +20 -0
- fable_v2/cortical/plasticity_engine.py +992 -0
- fable_v2/execution_broker.py +811 -0
- fable_v2/proof_engine.py +1141 -0
- fable_v2/protocol.py +485 -0
- fable_v2/runtime.py +1010 -0
- fable_v2/system3/__init__.py +204 -0
- fable_v2/system3/causal.py +558 -0
- fable_v2/system3/dialectical.py +577 -0
- fable_v2/system3/evolution.py +503 -0
- fable_v2/system3/executive.py +338 -0
- fable_v2/system3/free_energy.py +479 -0
- fable_v2/system3/hyperbolic.py +555 -0
- fable_v2/system3/induction.py +336 -0
- fable_v2/system3/kripke.py +548 -0
- fable_v2/system3/oracle.py +745 -0
- fable_v2/verifiers.py +72 -0
- tests/__init__.py +1 -0
- tests/test_anti_loop_circuit_breaker.py +64 -0
- tests/test_auto_updater.py +407 -0
- tests/test_coder_fleet.py +535 -0
- tests/test_delegation_compiler.py +54 -0
- tests/test_descriptor_boundaries.py +126 -0
- tests/test_design_engine.py +603 -0
- tests/test_epistemic_evidence_validator.py +66 -0
- tests/test_execution_broker.py +233 -0
- tests/test_fable_v2.py +406 -0
- tests/test_fleet_transitions.py +116 -0
- tests/test_fsm_redteam_evolution.py +406 -0
- tests/test_goal_rubric_and_pipeline.py +367 -0
- tests/test_hebbian_plasticity.py +585 -0
- tests/test_packaging_runtime.py +194 -0
- tests/test_proof_engine.py +259 -0
- tests/test_red_team_swarm.py +645 -0
- tests/test_redteam_remediation.py +169 -0
- tests/test_registration_transaction.py +375 -0
- tests/test_requested_regressions.py +467 -0
- tests/test_scrapers.py +370 -0
- tests/test_server_actions.py +93 -0
- tests/test_server_frontier_actions.py +269 -0
- tests/test_server_protocol.py +88 -0
- tests/test_stealth_browser.py +970 -0
- tests/test_system3.py +381 -0
- tests/test_system3_deep_integration.py +385 -0
- tests/test_system3_frontier.py +436 -0
- tests/test_vector_engine.py +608 -0
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
"""Unit tests for Modular Fable Part 2: Hebbian Cortical Plasticity & Lifelong Neuro-Evolutionary Engine."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
# Ensure workspace root is in sys.path
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
11
|
+
|
|
12
|
+
from fable_v2.coder_fleet import CoderFleetDispatcher, RedTeamSwarm
|
|
13
|
+
from fable_v2.cortical import (
|
|
14
|
+
CorticalDomain,
|
|
15
|
+
CorticalLobe,
|
|
16
|
+
HebbianPlasticityEngine,
|
|
17
|
+
HeuristicAntibody,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TestHebbianCorticalPlasticity(unittest.TestCase):
|
|
22
|
+
"""Exhaustive test suite for HebbianPlasticityEngine and cortical domain lobes."""
|
|
23
|
+
|
|
24
|
+
def setUp(self) -> None:
|
|
25
|
+
self.temp_dir = tempfile.TemporaryDirectory()
|
|
26
|
+
self.cortex_path = Path(self.temp_dir.name)
|
|
27
|
+
self.engine = HebbianPlasticityEngine(cortex_dir=self.cortex_path)
|
|
28
|
+
|
|
29
|
+
def tearDown(self) -> None:
|
|
30
|
+
self.temp_dir.cleanup()
|
|
31
|
+
|
|
32
|
+
def test_cortical_domain_enum(self) -> None:
|
|
33
|
+
"""Verify CorticalDomain defines all 5 specialized domains."""
|
|
34
|
+
self.assertEqual(CorticalDomain.RUST.value, "rust")
|
|
35
|
+
self.assertEqual(CorticalDomain.PYTHON.value, "python")
|
|
36
|
+
self.assertEqual(CorticalDomain.DESIGN_3D.value, "design_3d")
|
|
37
|
+
self.assertEqual(CorticalDomain.RESEARCH.value, "research")
|
|
38
|
+
self.assertEqual(CorticalDomain.CONCURRENCY.value, "concurrency")
|
|
39
|
+
self.assertEqual(len(CorticalDomain), 5)
|
|
40
|
+
|
|
41
|
+
def test_heuristic_antibody_dataclass_and_serialization(self) -> None:
|
|
42
|
+
"""Verify HeuristicAntibody serialization and formatting."""
|
|
43
|
+
ab = HeuristicAntibody(
|
|
44
|
+
antibody_id="ab_rust_deadlock_1",
|
|
45
|
+
domain="rust",
|
|
46
|
+
trigger_condition="Holding std::sync::Mutex across await",
|
|
47
|
+
lethal_anti_pattern="let g = mutex.lock().unwrap(); async_call().await;",
|
|
48
|
+
prescribed_defense="Use tokio::sync::Mutex or scope guard",
|
|
49
|
+
severity="CRITICAL",
|
|
50
|
+
source_task_id="task_100",
|
|
51
|
+
created_at="2026-09-04T12:00:00Z",
|
|
52
|
+
verified_counterfactual="Deadlock test verified 0 stalls",
|
|
53
|
+
)
|
|
54
|
+
d = ab.to_dict()
|
|
55
|
+
self.assertEqual(d["antibody_id"], "ab_rust_deadlock_1")
|
|
56
|
+
self.assertEqual(d["severity"], "CRITICAL")
|
|
57
|
+
|
|
58
|
+
ab_restored = HeuristicAntibody.from_dict(d)
|
|
59
|
+
self.assertEqual(ab_restored.antibody_id, ab.antibody_id)
|
|
60
|
+
self.assertEqual(ab_restored.prescribed_defense, ab.prescribed_defense)
|
|
61
|
+
|
|
62
|
+
md = ab.to_markdown()
|
|
63
|
+
self.assertIn("#### Antibody `ab_rust_deadlock_1` [CRITICAL]", md)
|
|
64
|
+
self.assertIn("Holding std::sync::Mutex across await", md)
|
|
65
|
+
self.assertIn("Verified Counterfactual", md)
|
|
66
|
+
|
|
67
|
+
def test_cortical_lobe_dataclass_and_disk_roundtrip(self) -> None:
|
|
68
|
+
"""Verify CorticalLobe serialization, markdown formatting, and disk save/load."""
|
|
69
|
+
ab = HeuristicAntibody(
|
|
70
|
+
antibody_id="ab_py_mut",
|
|
71
|
+
domain="python",
|
|
72
|
+
trigger_condition="Mutable default parameter",
|
|
73
|
+
lethal_anti_pattern="def f(x=[])",
|
|
74
|
+
prescribed_defense="Use None sentinel",
|
|
75
|
+
severity="HIGH",
|
|
76
|
+
)
|
|
77
|
+
lobe = CorticalLobe(
|
|
78
|
+
domain=CorticalDomain.PYTHON,
|
|
79
|
+
activation_count=7,
|
|
80
|
+
synaptic_weights={"asyncio": 0.85, "typing": 0.72},
|
|
81
|
+
antibodies=[ab],
|
|
82
|
+
specialized_heuristics=["Always use __slots__ for memory efficiency"],
|
|
83
|
+
last_consolidated_at="2026-09-04T12:00:00Z",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
lobe_file = self.cortex_path / "python_test.md"
|
|
87
|
+
lobe.save_to_disk(lobe_file)
|
|
88
|
+
self.assertTrue(lobe_file.exists())
|
|
89
|
+
|
|
90
|
+
loaded_lobe = CorticalLobe.load_from_disk(lobe_file)
|
|
91
|
+
self.assertEqual(loaded_lobe.domain, CorticalDomain.PYTHON)
|
|
92
|
+
self.assertEqual(loaded_lobe.activation_count, 7)
|
|
93
|
+
self.assertAlmostEqual(loaded_lobe.synaptic_weights["asyncio"], 0.85, places=2)
|
|
94
|
+
self.assertEqual(len(loaded_lobe.antibodies), 1)
|
|
95
|
+
self.assertEqual(loaded_lobe.antibodies[0].antibody_id, "ab_py_mut")
|
|
96
|
+
self.assertEqual(len(loaded_lobe.specialized_heuristics), 1)
|
|
97
|
+
|
|
98
|
+
def test_lobe_activation(self) -> None:
|
|
99
|
+
"""Verify activating a lobe increments its counter and primes nodes."""
|
|
100
|
+
lobe = self.engine.activate_lobe("rust", co_activated_nodes=["tokio", "pin_project"])
|
|
101
|
+
self.assertEqual(lobe.domain, CorticalDomain.RUST)
|
|
102
|
+
self.assertEqual(lobe.activation_count, 1)
|
|
103
|
+
self.assertIn("tokio", lobe.synaptic_weights)
|
|
104
|
+
self.assertIn("pin_project", lobe.synaptic_weights)
|
|
105
|
+
self.assertGreaterEqual(lobe.synaptic_weights["tokio"], 0.05)
|
|
106
|
+
|
|
107
|
+
# Second activation
|
|
108
|
+
lobe2 = self.engine.activate_lobe(CorticalDomain.RUST, co_activated_nodes=["tokio"])
|
|
109
|
+
self.assertEqual(lobe2.activation_count, 2)
|
|
110
|
+
self.assertGreater(lobe2.synaptic_weights["tokio"], 0.20)
|
|
111
|
+
|
|
112
|
+
def test_task_consolidation_hebbian_rule(self) -> None:
|
|
113
|
+
"""Verify Hebbian rule delta updates: ΔW_ij = η * Score * (A_i * A_j)."""
|
|
114
|
+
# Baseline activation
|
|
115
|
+
self.engine.activate_lobe("concurrency", co_activated_nodes=["atomic_cas", "hazard_ptrs"])
|
|
116
|
+
initial_lobe = self.engine._load_or_create_lobe(CorticalDomain.CONCURRENCY)
|
|
117
|
+
initial_w = initial_lobe.synaptic_weights["atomic_cas"]
|
|
118
|
+
|
|
119
|
+
# Successful consolidation (Score = 1.0, η = 0.1)
|
|
120
|
+
receipt = self.engine.consolidate_task(
|
|
121
|
+
domain="concurrency",
|
|
122
|
+
task_id="task_cas_test_1",
|
|
123
|
+
final_passed=True,
|
|
124
|
+
co_activated_nodes=["atomic_cas", "hazard_ptrs"],
|
|
125
|
+
)
|
|
126
|
+
self.assertEqual(receipt["status"], "CONSOLIDATED")
|
|
127
|
+
self.assertTrue(receipt["final_passed"])
|
|
128
|
+
self.assertEqual(receipt["learning_rate"], 0.10)
|
|
129
|
+
self.assertEqual(receipt["score"], 1.0)
|
|
130
|
+
self.assertEqual(receipt["plasticity_mode"], "LTP")
|
|
131
|
+
|
|
132
|
+
# Verify weight increased via BCM LTP (delta_w = learning_rate * A_domain * A_node)
|
|
133
|
+
# A_domain = min(1.0, max(0.30, 0.40 + 0.10 * 2)) = 0.60
|
|
134
|
+
# A_node = max(0.75, min(0.90, 0.90 - 0 * 0.03)) = 0.90
|
|
135
|
+
# delta_w = 0.10 * 0.60 * 0.90 = 0.054
|
|
136
|
+
expected_delta = 0.10 * (0.40 + 0.10 * 2) * 0.90
|
|
137
|
+
updated_w = receipt["synaptic_weights"]["atomic_cas"]
|
|
138
|
+
self.assertAlmostEqual(updated_w, initial_w + expected_delta, places=2)
|
|
139
|
+
self.assertGreater(updated_w, initial_w)
|
|
140
|
+
|
|
141
|
+
# Verify global synaptic matrix pair co-activation was recorded
|
|
142
|
+
matrix = self.engine.get_synaptic_matrix()
|
|
143
|
+
self.assertIn("atomic_cas", matrix)
|
|
144
|
+
self.assertIn("hazard_ptrs", matrix["atomic_cas"])
|
|
145
|
+
self.assertGreaterEqual(matrix["atomic_cas"]["hazard_ptrs"], 0.15)
|
|
146
|
+
|
|
147
|
+
def test_homeostatic_weight_bounding(self) -> None:
|
|
148
|
+
"""Verify synaptic weights remain strictly bounded within [0.05, 1.0]."""
|
|
149
|
+
domain = CorticalDomain.RESEARCH
|
|
150
|
+
|
|
151
|
+
# Run 20 consolidations to push weight towards maximum
|
|
152
|
+
for i in range(20):
|
|
153
|
+
receipt = self.engine.consolidate_task(
|
|
154
|
+
domain=domain,
|
|
155
|
+
task_id=f"iter_{i}",
|
|
156
|
+
final_passed=True,
|
|
157
|
+
co_activated_nodes=["citation_verifier", "causal_dag"],
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
weights = receipt["synaptic_weights"]
|
|
161
|
+
for node, w in weights.items():
|
|
162
|
+
self.assertLessEqual(w, 1.0, f"Weight for {node} exceeded 1.0: {w}")
|
|
163
|
+
self.assertGreaterEqual(w, 0.05, f"Weight for {node} fell below 0.05: {w}")
|
|
164
|
+
|
|
165
|
+
def test_antibody_synthesis_from_red_team_breakages(self) -> None:
|
|
166
|
+
"""Verify broken scenarios synthesize persistent HeuristicAntibodies."""
|
|
167
|
+
broken_scenarios = [
|
|
168
|
+
{
|
|
169
|
+
"scenario_id": "toctou_race_burst",
|
|
170
|
+
"vector": "concurrency_race",
|
|
171
|
+
"hypothesis": "What will happen if 16 threads mutate the file descriptor concurrently?",
|
|
172
|
+
"broken": True,
|
|
173
|
+
"error_message": "FileExistsError: Cannot create file that already exists",
|
|
174
|
+
"reproduction_code": "race_harness.run(threads=16)",
|
|
175
|
+
"severity": "CRITICAL",
|
|
176
|
+
"prescribed_defense": "Use atomic O_CREAT | O_EXCL flags",
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
"scenario_id": "null_byte_injection",
|
|
180
|
+
"vector": "byzantine_payload",
|
|
181
|
+
"hypothesis": "What will happen if payload contains \\x00 byte?",
|
|
182
|
+
"broken": True,
|
|
183
|
+
"error_message": "ValueError: embedded null byte",
|
|
184
|
+
"severity": "HIGH",
|
|
185
|
+
"remediation_directives": ["Sanitize input using null-byte strip filter"],
|
|
186
|
+
},
|
|
187
|
+
]
|
|
188
|
+
|
|
189
|
+
receipt = self.engine.consolidate_task(
|
|
190
|
+
domain="concurrency",
|
|
191
|
+
task_id="task_red_team_harden_01",
|
|
192
|
+
broken_scenarios=broken_scenarios,
|
|
193
|
+
final_passed=True,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
self.assertEqual(receipt["antibodies_added"], 2)
|
|
197
|
+
self.assertEqual(receipt["total_antibodies"], 2)
|
|
198
|
+
|
|
199
|
+
lobe = self.engine._load_or_create_lobe(CorticalDomain.CONCURRENCY)
|
|
200
|
+
self.assertEqual(len(lobe.antibodies), 2)
|
|
201
|
+
ab_ids = [a.antibody_id for a in lobe.antibodies]
|
|
202
|
+
self.assertIn("ab_concurrency_toctou_race_burst", ab_ids)
|
|
203
|
+
self.assertIn("ab_concurrency_null_byte_injection", ab_ids)
|
|
204
|
+
|
|
205
|
+
# Test deduplication: running same broken scenario does not duplicate antibody
|
|
206
|
+
receipt2 = self.engine.consolidate_task(
|
|
207
|
+
domain="concurrency",
|
|
208
|
+
task_id="task_red_team_harden_02",
|
|
209
|
+
broken_scenarios=broken_scenarios,
|
|
210
|
+
final_passed=True,
|
|
211
|
+
)
|
|
212
|
+
self.assertEqual(receipt2["antibodies_added"], 0)
|
|
213
|
+
self.assertEqual(receipt2["total_antibodies"], 2)
|
|
214
|
+
|
|
215
|
+
def test_specialized_heuristics_from_lessons(self) -> None:
|
|
216
|
+
"""Verify lessons are extracted into specialized domain heuristics."""
|
|
217
|
+
lessons = [
|
|
218
|
+
"Always enforce WebGPU fallback to WebGL2 for headless CI environments",
|
|
219
|
+
{"heuristic": "Pre-calculate APCA Lc >= 75 contrast before rendering text"},
|
|
220
|
+
]
|
|
221
|
+
receipt = self.engine.consolidate_task(
|
|
222
|
+
domain="design_3d",
|
|
223
|
+
task_id="task_design_lessons_01",
|
|
224
|
+
lessons=lessons,
|
|
225
|
+
final_passed=True,
|
|
226
|
+
)
|
|
227
|
+
self.assertEqual(receipt["heuristics_added"], 2)
|
|
228
|
+
self.assertEqual(receipt["total_heuristics"], 2)
|
|
229
|
+
|
|
230
|
+
lobe = self.engine._load_or_create_lobe(CorticalDomain.DESIGN_3D)
|
|
231
|
+
self.assertIn("Always enforce WebGPU fallback to WebGL2 for headless CI environments", lobe.specialized_heuristics)
|
|
232
|
+
self.assertIn("Pre-calculate APCA Lc >= 75 contrast before rendering text", lobe.specialized_heuristics)
|
|
233
|
+
|
|
234
|
+
def test_recall_cortical_context(self) -> None:
|
|
235
|
+
"""Verify recall_cortical_context formats a high-signal markdown block."""
|
|
236
|
+
# Add an antibody and activate
|
|
237
|
+
self.engine.consolidate_task(
|
|
238
|
+
domain="rust",
|
|
239
|
+
task_id="task_recall_test",
|
|
240
|
+
broken_scenarios=[
|
|
241
|
+
{
|
|
242
|
+
"scenario_id": "unbounded_channel",
|
|
243
|
+
"hypothesis": "What happens under 1M msgs?",
|
|
244
|
+
"error_message": "OutOfMemoryError",
|
|
245
|
+
"prescribed_defense": "Enforce bounded channel with permit backpressure",
|
|
246
|
+
"severity": "HIGH",
|
|
247
|
+
}
|
|
248
|
+
],
|
|
249
|
+
lessons=["Zero-cost abstractions must compile to 0 heap allocations"],
|
|
250
|
+
co_activated_nodes=["tokio", "concurrency_fuzz"],
|
|
251
|
+
final_passed=True,
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
memory_block = self.engine.recall_cortical_context("rust", max_antibodies=3)
|
|
255
|
+
self.assertIn("### 🧠 Cortical Lobe Memory: `RUST`", memory_block)
|
|
256
|
+
self.assertIn("🛡️ Immunological Heuristic Antibodies", memory_block)
|
|
257
|
+
self.assertIn("Enforce bounded channel with permit backpressure", memory_block)
|
|
258
|
+
self.assertIn("Zero-cost abstractions must compile to 0 heap allocations", memory_block)
|
|
259
|
+
self.assertIn("Strongly-Wired Synaptic Companion Tools", memory_block)
|
|
260
|
+
self.assertIn("tokio", memory_block)
|
|
261
|
+
|
|
262
|
+
def test_coder_fleet_dispatcher_routing(self) -> None:
|
|
263
|
+
"""Verify CoderFleetDispatcher correctly dispatches all 4 cortical actions."""
|
|
264
|
+
dispatcher = CoderFleetDispatcher(plasticity_engine=self.engine)
|
|
265
|
+
|
|
266
|
+
# 1. cortical_activate_lobe
|
|
267
|
+
res_act = dispatcher.dispatch("cortical_activate_lobe", {"domain": "python", "co_activated_nodes": ["asyncio"]})
|
|
268
|
+
self.assertTrue(res_act["success"])
|
|
269
|
+
self.assertEqual(res_act["action"], "cortical_activate_lobe")
|
|
270
|
+
self.assertIsInstance(res_act["result"], CorticalLobe)
|
|
271
|
+
|
|
272
|
+
# 2. cortical_consolidate_task
|
|
273
|
+
res_cons = dispatcher.dispatch(
|
|
274
|
+
"cortical_consolidate_task",
|
|
275
|
+
{
|
|
276
|
+
"domain": "python",
|
|
277
|
+
"task_id": "task_fleet_01",
|
|
278
|
+
"final_passed": True,
|
|
279
|
+
"co_activated_nodes": ["asyncio", "typing"],
|
|
280
|
+
},
|
|
281
|
+
)
|
|
282
|
+
self.assertTrue(res_cons["success"])
|
|
283
|
+
self.assertEqual(res_cons["result"]["status"], "CONSOLIDATED")
|
|
284
|
+
|
|
285
|
+
# 3. cortical_recall_context
|
|
286
|
+
res_rec = dispatcher.dispatch("cortical_recall_context", {"domain": "python", "max_antibodies": 2})
|
|
287
|
+
self.assertTrue(res_rec["success"])
|
|
288
|
+
self.assertIn("Cortical Lobe Memory: `PYTHON`", res_rec["result"])
|
|
289
|
+
|
|
290
|
+
# 4. cortical_inspect_matrix
|
|
291
|
+
res_mat = dispatcher.dispatch("cortical_inspect_matrix", {})
|
|
292
|
+
self.assertTrue(res_mat["success"])
|
|
293
|
+
self.assertIsInstance(res_mat["result"], dict)
|
|
294
|
+
|
|
295
|
+
# 5. cortical_define_lobe
|
|
296
|
+
res_def = dispatcher.dispatch(
|
|
297
|
+
"cortical_define_lobe",
|
|
298
|
+
{
|
|
299
|
+
"name": "solidity_evm",
|
|
300
|
+
"description": "Smart contract reentrancy defenses and EVM gas profiling",
|
|
301
|
+
"initial_heuristics": ["Follow Checks-Effects-Interactions pattern strictly"],
|
|
302
|
+
"initial_synaptic_weights": {"reentrancy_guard": 0.95},
|
|
303
|
+
},
|
|
304
|
+
)
|
|
305
|
+
self.assertTrue(res_def["success"])
|
|
306
|
+
self.assertEqual(res_def["action"], "cortical_define_lobe")
|
|
307
|
+
self.assertIsInstance(res_def["result"], CorticalLobe)
|
|
308
|
+
self.assertEqual(res_def["result"].name, "solidity_evm")
|
|
309
|
+
|
|
310
|
+
# 6. cortical_list_lobes
|
|
311
|
+
res_list = dispatcher.dispatch("cortical_list_lobes", {})
|
|
312
|
+
self.assertTrue(res_list["success"])
|
|
313
|
+
self.assertEqual(res_list["action"], "cortical_list_lobes")
|
|
314
|
+
self.assertIsInstance(res_list["result"], list)
|
|
315
|
+
names = [l["name"] for l in res_list["result"]]
|
|
316
|
+
self.assertIn("solidity_evm", names)
|
|
317
|
+
|
|
318
|
+
def test_define_cortical_lobe_custom_sprouting(self) -> None:
|
|
319
|
+
"""Verify dynamic open-ended sprouting of a customizable cortical lobe from scratch."""
|
|
320
|
+
heuristics = [
|
|
321
|
+
"Always pass an explicit Allocator; never hide heap allocation inside structs",
|
|
322
|
+
"Use comptime assertions to eliminate invalid type configurations at build time",
|
|
323
|
+
]
|
|
324
|
+
weights = {"std_mem": 0.88, "comptime": 0.95, "c_interop": 0.70}
|
|
325
|
+
lobe = self.engine.define_cortical_lobe(
|
|
326
|
+
name="zig_systems",
|
|
327
|
+
description="Low-level Zig memory management, comptime, and C-interop",
|
|
328
|
+
initial_heuristics=heuristics,
|
|
329
|
+
initial_synaptic_weights=weights,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
self.assertEqual(lobe.name, "zig_systems")
|
|
333
|
+
self.assertEqual(lobe.description, "Low-level Zig memory management, comptime, and C-interop")
|
|
334
|
+
self.assertEqual(lobe.domain, "zig_systems")
|
|
335
|
+
self.assertEqual(lobe.activation_count, 1)
|
|
336
|
+
self.assertEqual(len(lobe.specialized_heuristics), 2)
|
|
337
|
+
self.assertAlmostEqual(lobe.synaptic_weights["comptime"], 0.95, places=2)
|
|
338
|
+
|
|
339
|
+
# Verify disk persistence
|
|
340
|
+
lobe_file = self.cortex_path / "zig_systems.md"
|
|
341
|
+
self.assertTrue(lobe_file.exists())
|
|
342
|
+
loaded = CorticalLobe.load_from_disk(lobe_file)
|
|
343
|
+
self.assertEqual(loaded.name, "zig_systems")
|
|
344
|
+
self.assertEqual(loaded.description, "Low-level Zig memory management, comptime, and C-interop")
|
|
345
|
+
self.assertEqual(len(loaded.specialized_heuristics), 2)
|
|
346
|
+
self.assertAlmostEqual(loaded.synaptic_weights["comptime"], 0.95, places=2)
|
|
347
|
+
|
|
348
|
+
# Verify matrix integration
|
|
349
|
+
matrix = self.engine.get_synaptic_matrix()
|
|
350
|
+
self.assertIn("zig_systems", matrix)
|
|
351
|
+
self.assertIn("comptime", matrix["zig_systems"])
|
|
352
|
+
self.assertAlmostEqual(matrix["zig_systems"]["comptime"], 0.95, places=2)
|
|
353
|
+
|
|
354
|
+
def test_activate_lobe_auto_sprouting(self) -> None:
|
|
355
|
+
"""Verify activate_lobe automatically sprouts a novel lobe when it does not exist."""
|
|
356
|
+
lobe_file = self.cortex_path / "elixir_otp.md"
|
|
357
|
+
self.assertFalse(lobe_file.exists())
|
|
358
|
+
|
|
359
|
+
# Auto-sprout with explicit description
|
|
360
|
+
lobe = self.engine.activate_lobe(
|
|
361
|
+
domain_or_name="elixir_otp",
|
|
362
|
+
description="Actor-model concurrency, supervision trees, and GenServer invariants",
|
|
363
|
+
co_activated_nodes=["gen_server", "supervision_tree"],
|
|
364
|
+
)
|
|
365
|
+
self.assertTrue(lobe_file.exists())
|
|
366
|
+
self.assertEqual(lobe.name, "elixir_otp")
|
|
367
|
+
self.assertEqual(lobe.description, "Actor-model concurrency, supervision trees, and GenServer invariants")
|
|
368
|
+
self.assertEqual(lobe.activation_count, 1)
|
|
369
|
+
self.assertIn("gen_server", lobe.synaptic_weights)
|
|
370
|
+
|
|
371
|
+
# Auto-sprout with default description fallback
|
|
372
|
+
lobe_bio = self.engine.activate_lobe("bioinformatics_genomics")
|
|
373
|
+
self.assertEqual(lobe_bio.name, "bioinformatics_genomics")
|
|
374
|
+
self.assertIn("Custom cortical lobe for bioinformatics_genomics", lobe_bio.description)
|
|
375
|
+
|
|
376
|
+
# Subsequent activation increments count
|
|
377
|
+
lobe2 = self.engine.activate_lobe("elixir_otp", co_activated_nodes=["gen_server"])
|
|
378
|
+
self.assertEqual(lobe2.activation_count, 2)
|
|
379
|
+
|
|
380
|
+
def test_list_cortical_lobes(self) -> None:
|
|
381
|
+
"""Verify list_cortical_lobes discovers and returns metadata for all available lobes."""
|
|
382
|
+
# Create baseline and custom lobes
|
|
383
|
+
self.engine.activate_lobe("rust")
|
|
384
|
+
self.engine.define_cortical_lobe(
|
|
385
|
+
name="kubernetes_operators",
|
|
386
|
+
description="Reconciliation loop invariants and CRD controllers",
|
|
387
|
+
initial_heuristics=["Always use idempotent reconcile loops"],
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
lobes = self.engine.list_cortical_lobes()
|
|
391
|
+
self.assertIsInstance(lobes, list)
|
|
392
|
+
names = [l["name"] for l in lobes]
|
|
393
|
+
self.assertIn("rust", names)
|
|
394
|
+
self.assertIn("kubernetes_operators", names)
|
|
395
|
+
|
|
396
|
+
k8s_meta = next(l for l in lobes if l["name"] == "kubernetes_operators")
|
|
397
|
+
self.assertEqual(k8s_meta["description"], "Reconciliation loop invariants and CRD controllers")
|
|
398
|
+
self.assertEqual(k8s_meta["heuristic_count"], 1)
|
|
399
|
+
self.assertTrue(Path(k8s_meta["file_path"]).exists())
|
|
400
|
+
|
|
401
|
+
def test_task_consolidation_and_antibodies_custom_lobe(self) -> None:
|
|
402
|
+
"""Verify task consolidation, Hebbian weight updating, and antibody synthesis in a custom lobe."""
|
|
403
|
+
broken_scenarios = [
|
|
404
|
+
{
|
|
405
|
+
"scenario_id": "simd_tile_misalignment",
|
|
406
|
+
"hypothesis": "What happens if SIMD vector width does not evenly divide tensor shape?",
|
|
407
|
+
"error_message": "AlignmentError: unaligned memory access in vector register load",
|
|
408
|
+
"reproduction_code": "mojo_kernel.execute(tensor_shape=(13, 17))",
|
|
409
|
+
"prescribed_defense": "Enforce dynamic tail padding and vectorized mask loading",
|
|
410
|
+
"severity": "CRITICAL",
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
|
|
414
|
+
receipt = self.engine.consolidate_task(
|
|
415
|
+
domain="mojo_kernels",
|
|
416
|
+
task_id="task_mojo_vectorization_01",
|
|
417
|
+
broken_scenarios=broken_scenarios,
|
|
418
|
+
final_passed=True,
|
|
419
|
+
lessons=["Always utilize compile-time SIMD width querying via sys.info.simdwidthof"],
|
|
420
|
+
co_activated_nodes=["autotune", "vectorize"],
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
self.assertEqual(receipt["status"], "CONSOLIDATED")
|
|
424
|
+
self.assertEqual(receipt["domain"], "mojo_kernels")
|
|
425
|
+
self.assertEqual(receipt["name"], "mojo_kernels")
|
|
426
|
+
self.assertEqual(receipt["antibodies_added"], 1)
|
|
427
|
+
self.assertEqual(receipt["heuristics_added"], 1)
|
|
428
|
+
|
|
429
|
+
lobe = self.engine._load_or_create_lobe("mojo_kernels")
|
|
430
|
+
self.assertEqual(len(lobe.antibodies), 1)
|
|
431
|
+
self.assertEqual(lobe.antibodies[0].antibody_id, "ab_mojo_kernels_simd_tile_misalignment")
|
|
432
|
+
self.assertEqual(lobe.antibodies[0].domain, "mojo_kernels")
|
|
433
|
+
|
|
434
|
+
# Verify recall reflects custom lobe
|
|
435
|
+
context = self.engine.recall_cortical_context("mojo_kernels")
|
|
436
|
+
self.assertIn("### 🧠 Cortical Lobe Memory: `MOJO_KERNELS`", context)
|
|
437
|
+
self.assertIn("What happens if SIMD vector width", context)
|
|
438
|
+
self.assertIn("Enforce dynamic tail padding and vectorized mask loading", context)
|
|
439
|
+
self.assertIn("compile-time SIMD width querying", context)
|
|
440
|
+
|
|
441
|
+
def test_continuous_activity_dependent_activation_metrics(self) -> None:
|
|
442
|
+
"""Verify continuous A_j scaling with activation_metrics and A_domain computation."""
|
|
443
|
+
receipt = self.engine.consolidate_task(
|
|
444
|
+
domain="python",
|
|
445
|
+
task_id="task_metrics_01",
|
|
446
|
+
final_passed=True,
|
|
447
|
+
co_activated_nodes=["asyncio", "typing", "celery"],
|
|
448
|
+
activation_metrics={"asyncio": 100.0, "typing": 50.0, "celery": 5.0},
|
|
449
|
+
)
|
|
450
|
+
signals = receipt["activation_signals"]
|
|
451
|
+
# Max metric is 100.0, denom is 100.0
|
|
452
|
+
# asyncio: 100/100 = 1.0 -> min(1.0, max(0.15, 1.0)) = 1.0
|
|
453
|
+
# typing: 50/100 = 0.50 -> min(1.0, max(0.15, 0.50)) = 0.50
|
|
454
|
+
# celery: 5/100 = 0.05 -> min(1.0, max(0.15, 0.05)) = 0.15 (floored at 0.15)
|
|
455
|
+
self.assertAlmostEqual(signals["asyncio"], 1.0, places=3)
|
|
456
|
+
self.assertAlmostEqual(signals["typing"], 0.50, places=3)
|
|
457
|
+
self.assertAlmostEqual(signals["celery"], 0.15, places=3)
|
|
458
|
+
|
|
459
|
+
# Domain activation with 3 nodes: min(1.0, max(0.30, 0.40 + 0.10 * 3)) = 0.70
|
|
460
|
+
self.assertAlmostEqual(receipt["A_domain"], 0.70, places=3)
|
|
461
|
+
|
|
462
|
+
def test_bcm_asymmetric_plasticity_ltd_vs_ltp(self) -> None:
|
|
463
|
+
"""Verify BCM plasticity: LTD on failure (ΔW < 0) vs LTP on success (ΔW > 0)."""
|
|
464
|
+
# Set up an initial node weight in concurrency lobe
|
|
465
|
+
lobe = self.engine._load_or_create_lobe("concurrency")
|
|
466
|
+
lobe.synaptic_weights["broken_pathway"] = 0.60
|
|
467
|
+
initial_w = lobe.synaptic_weights["broken_pathway"]
|
|
468
|
+
|
|
469
|
+
# 1. Synaptic Depression (LTD) on final_passed=False: strictly decreases weight
|
|
470
|
+
receipt_fail = self.engine.consolidate_task(
|
|
471
|
+
domain="concurrency",
|
|
472
|
+
task_id="task_ltd_01",
|
|
473
|
+
final_passed=False,
|
|
474
|
+
co_activated_nodes=["broken_pathway"],
|
|
475
|
+
)
|
|
476
|
+
self.assertEqual(receipt_fail["plasticity_mode"], "LTD")
|
|
477
|
+
w_after_fail = receipt_fail["synaptic_weights"]["broken_pathway"]
|
|
478
|
+
self.assertLess(w_after_fail, initial_w, f"LTD must decrease weight: {w_after_fail} >= {initial_w}")
|
|
479
|
+
# Expected LTD delta: -0.15 * A_domain (0.50) * A_node (0.90) = -0.0675
|
|
480
|
+
expected_ltd_delta = - 0.15 * 0.50 * 0.90
|
|
481
|
+
self.assertAlmostEqual(w_after_fail, initial_w + expected_ltd_delta, places=2)
|
|
482
|
+
|
|
483
|
+
# 2. Synaptic Potentiation (LTP) on final_passed=True: strictly increases weight
|
|
484
|
+
receipt_pass = self.engine.consolidate_task(
|
|
485
|
+
domain="concurrency",
|
|
486
|
+
task_id="task_ltp_01",
|
|
487
|
+
final_passed=True,
|
|
488
|
+
co_activated_nodes=["broken_pathway"],
|
|
489
|
+
)
|
|
490
|
+
self.assertEqual(receipt_pass["plasticity_mode"], "LTP")
|
|
491
|
+
w_after_pass = receipt_pass["synaptic_weights"]["broken_pathway"]
|
|
492
|
+
self.assertGreater(w_after_pass, w_after_fail, f"LTP must increase weight: {w_after_pass} <= {w_after_fail}")
|
|
493
|
+
# Expected LTP delta: +0.10 * A_domain (0.50) * A_node (0.90) = +0.045
|
|
494
|
+
expected_ltp_delta = 0.10 * 0.50 * 0.90
|
|
495
|
+
self.assertAlmostEqual(w_after_pass, w_after_fail + expected_ltp_delta, places=2)
|
|
496
|
+
|
|
497
|
+
def test_homeostatic_weight_bounding_ltd_floor(self) -> None:
|
|
498
|
+
"""Verify synaptic depression (LTD) strictly respects the [0.05, 1.00] homeostatic floor."""
|
|
499
|
+
lobe = self.engine._load_or_create_lobe("research")
|
|
500
|
+
lobe.synaptic_weights["failing_path"] = 0.10
|
|
501
|
+
|
|
502
|
+
for i in range(15):
|
|
503
|
+
receipt = self.engine.consolidate_task(
|
|
504
|
+
domain="research",
|
|
505
|
+
task_id=f"fail_burst_{i}",
|
|
506
|
+
final_passed=False,
|
|
507
|
+
co_activated_nodes=["failing_path"],
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
final_w = receipt["synaptic_weights"]["failing_path"]
|
|
511
|
+
self.assertGreaterEqual(final_w, 0.05)
|
|
512
|
+
self.assertEqual(final_w, 0.05)
|
|
513
|
+
|
|
514
|
+
def test_automated_closed_loop_red_team_to_cortical_consolidation(self) -> None:
|
|
515
|
+
"""Verify full automated closed-loop RedTeam -> Remediation -> Cortical Consolidation."""
|
|
516
|
+
swarm = RedTeamSwarm(plasticity_engine=self.engine)
|
|
517
|
+
|
|
518
|
+
# Fragile target that breaks under adversarial probe
|
|
519
|
+
def fragile_target(payload: Any = None) -> str:
|
|
520
|
+
if payload is None or (isinstance(payload, str) and "\x00" in payload):
|
|
521
|
+
raise ValueError("Fatal unhandled payload corruption")
|
|
522
|
+
return "ok"
|
|
523
|
+
|
|
524
|
+
# 1. Swarm attack breaks fragile target -> auto-consolidates with LTD
|
|
525
|
+
report_break = swarm.run_full_review_cycle(
|
|
526
|
+
fragile_target,
|
|
527
|
+
target_name="crypto_service",
|
|
528
|
+
)
|
|
529
|
+
self.assertFalse(report_break.passed)
|
|
530
|
+
self.assertGreater(report_break.broken_count, 0)
|
|
531
|
+
|
|
532
|
+
# Verify LTD was automatically applied to crypto_service lobe
|
|
533
|
+
lobe = self.engine._load_or_create_lobe("crypto_service")
|
|
534
|
+
self.assertIn("test_harness", lobe.synaptic_weights)
|
|
535
|
+
self.assertIn("red_team_swarm", lobe.synaptic_weights)
|
|
536
|
+
# 0.30 baseline depressed by -0.15 * A_domain * A_node
|
|
537
|
+
self.assertLess(lobe.synaptic_weights["test_harness"], 0.30)
|
|
538
|
+
self.assertGreaterEqual(len(lobe.antibodies), 1)
|
|
539
|
+
|
|
540
|
+
# 2. Subagent remediates and hardens target
|
|
541
|
+
def hardened_target(payload: Any = None) -> str:
|
|
542
|
+
if payload is None:
|
|
543
|
+
return "ok_default"
|
|
544
|
+
if isinstance(payload, str):
|
|
545
|
+
return "ok_" + payload.replace("\x00", "")[:100]
|
|
546
|
+
return "ok_" + str(payload)[:100]
|
|
547
|
+
|
|
548
|
+
# 3. Swarm verifies remediation -> auto-consolidates with LTP and synthesizes verified antibody
|
|
549
|
+
all_fixed, report_fixed = swarm.verify_remediation(
|
|
550
|
+
target_callable=hardened_target,
|
|
551
|
+
prior_report=report_break,
|
|
552
|
+
)
|
|
553
|
+
self.assertTrue(all_fixed)
|
|
554
|
+
self.assertTrue(report_fixed.passed)
|
|
555
|
+
self.assertEqual(report_fixed.broken_count, 0)
|
|
556
|
+
|
|
557
|
+
# Verify LTP was automatically applied to remediating pathway
|
|
558
|
+
lobe_after = self.engine._load_or_create_lobe("crypto_service")
|
|
559
|
+
self.assertIn("mutation", lobe_after.synaptic_weights)
|
|
560
|
+
# 0.30 baseline potentiated by +0.10 * A_domain * A_node
|
|
561
|
+
self.assertGreater(lobe_after.synaptic_weights["mutation"], 0.30)
|
|
562
|
+
self.assertGreater(len(lobe_after.antibodies), 0)
|
|
563
|
+
self.assertGreater(len(lobe_after.specialized_heuristics), 0)
|
|
564
|
+
|
|
565
|
+
# Verify disk persistence
|
|
566
|
+
lobe_file = self.cortex_path / "crypto_service.md"
|
|
567
|
+
self.assertTrue(lobe_file.exists())
|
|
568
|
+
loaded_lobe = CorticalLobe.load_from_disk(lobe_file)
|
|
569
|
+
self.assertEqual(loaded_lobe.name, "crypto_service")
|
|
570
|
+
self.assertGreater(len(loaded_lobe.antibodies), 0)
|
|
571
|
+
|
|
572
|
+
def test_production_baseline_lobes_integrity(self) -> None:
|
|
573
|
+
"""Verify the repository's 5 production baseline lobes in skills/fable-mode/cortex/ are fully valid."""
|
|
574
|
+
repo_engine = HebbianPlasticityEngine() # Resolves to repo cortex dir
|
|
575
|
+
for domain in CorticalDomain:
|
|
576
|
+
lobe_path = repo_engine._get_lobe_path(domain)
|
|
577
|
+
lobe = CorticalLobe.load_from_disk(lobe_path)
|
|
578
|
+
self.assertEqual(lobe.domain, domain)
|
|
579
|
+
self.assertGreaterEqual(len(lobe.antibodies), 3, f"Lobe {domain.value} has fewer than 3 antibodies")
|
|
580
|
+
self.assertGreaterEqual(len(lobe.specialized_heuristics), 5, f"Lobe {domain.value} has fewer than 5 heuristics")
|
|
581
|
+
self.assertGreaterEqual(len(lobe.synaptic_weights), 5, f"Lobe {domain.value} has fewer than 5 synaptic weights")
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
if __name__ == "__main__":
|
|
585
|
+
unittest.main()
|