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,815 @@
|
|
|
1
|
+
"""System 3 meta-cognitive deliberation, evolutionary, and dialectical action handlers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import collections
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("fable-engine.actions.system3")
|
|
15
|
+
|
|
16
|
+
from fable_engine.session import (
|
|
17
|
+
ACTIVE_SESSIONS,
|
|
18
|
+
PHASES,
|
|
19
|
+
SESSIONS_DIR,
|
|
20
|
+
SILENT_DELIBERATION_REMINDER,
|
|
21
|
+
FableSession,
|
|
22
|
+
SessionState,
|
|
23
|
+
_validate_session_name,
|
|
24
|
+
_validate_time_budget,
|
|
25
|
+
get_or_load_session,
|
|
26
|
+
)
|
|
27
|
+
# System 3 classes are lazily imported inside each handler to ensure near-instantaneous server startup
|
|
28
|
+
|
|
29
|
+
def _handle_system3_dialectical_synthesis(arguments: Dict[str, Any]) -> str:
|
|
30
|
+
from fable_v2.system3 import ThesisCandidate, AntithesisCritique, Contradiction, TRIZPrinciple, TRIZContradictionResolver, DialecticalSynthesizer
|
|
31
|
+
action = arguments.get("action", "").strip().lower()
|
|
32
|
+
session_name = arguments.get("session_name", "").strip()
|
|
33
|
+
session: Optional[FableSession] = None
|
|
34
|
+
if not session_name:
|
|
35
|
+
return "Error: 'session_name' is required for action 'system3_dialectical_synthesis'."
|
|
36
|
+
thesis_title = arguments.get("thesis_title") or arguments.get("title") or "Architectural Thesis"
|
|
37
|
+
thesis_desc = arguments.get("thesis_description") or arguments.get("description") or arguments.get("thesis") or "Primary architectural candidate."
|
|
38
|
+
antithesis_title = arguments.get("antithesis_title") or arguments.get("critique_title") or arguments.get("critique") or "Adversarial Critique"
|
|
39
|
+
|
|
40
|
+
raw_contradictions = arguments.get("contradictions") or arguments.get("contradiction_list") or []
|
|
41
|
+
parsed_contradictions = []
|
|
42
|
+
if isinstance(raw_contradictions, str):
|
|
43
|
+
try:
|
|
44
|
+
loaded = json.loads(raw_contradictions)
|
|
45
|
+
if isinstance(loaded, list):
|
|
46
|
+
raw_contradictions = loaded
|
|
47
|
+
elif isinstance(loaded, dict):
|
|
48
|
+
raw_contradictions = [loaded]
|
|
49
|
+
except Exception:
|
|
50
|
+
raw_contradictions = [
|
|
51
|
+
{"improving_parameter": "performance", "worsening_parameter": "safety", "description": line.strip(), "severity": 0.7}
|
|
52
|
+
for line in raw_contradictions.splitlines() if line.strip()
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
if isinstance(raw_contradictions, list):
|
|
56
|
+
for idx, c in enumerate(raw_contradictions):
|
|
57
|
+
if isinstance(c, dict):
|
|
58
|
+
parsed_contradictions.append(Contradiction(
|
|
59
|
+
contradiction_id=c.get("contradiction_id", f"c_{idx+1:03d}"),
|
|
60
|
+
improving_parameter=c.get("improving_parameter", "performance"),
|
|
61
|
+
worsening_parameter=c.get("worsening_parameter", "safety"),
|
|
62
|
+
description=c.get("description", "Architectural trade-off"),
|
|
63
|
+
severity=float(c.get("severity", 0.7)),
|
|
64
|
+
))
|
|
65
|
+
elif isinstance(c, str):
|
|
66
|
+
parsed_contradictions.append(Contradiction(
|
|
67
|
+
contradiction_id=f"c_{idx+1:03d}",
|
|
68
|
+
improving_parameter="performance",
|
|
69
|
+
worsening_parameter="safety",
|
|
70
|
+
description=c,
|
|
71
|
+
severity=0.7,
|
|
72
|
+
))
|
|
73
|
+
|
|
74
|
+
failure_modes = arguments.get("failure_modes") or []
|
|
75
|
+
if isinstance(failure_modes, str):
|
|
76
|
+
try:
|
|
77
|
+
failure_modes = json.loads(failure_modes)
|
|
78
|
+
except Exception:
|
|
79
|
+
failure_modes = [f.strip() for f in failure_modes.splitlines() if f.strip()]
|
|
80
|
+
|
|
81
|
+
thesis = ThesisCandidate(
|
|
82
|
+
thesis_id=f"th_{session_name}_{int(time.time()*1000)%10000}",
|
|
83
|
+
title=thesis_title,
|
|
84
|
+
description=thesis_desc,
|
|
85
|
+
)
|
|
86
|
+
critique = AntithesisCritique(
|
|
87
|
+
critique_id=f"cr_{session_name}_{int(time.time()*1000)%10000}",
|
|
88
|
+
thesis_id=thesis.thesis_id,
|
|
89
|
+
title=antithesis_title,
|
|
90
|
+
contradictions=parsed_contradictions,
|
|
91
|
+
failure_modes=failure_modes if isinstance(failure_modes, list) else [str(failure_modes)],
|
|
92
|
+
severity_score=float(arguments.get("severity_score", 0.75)),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
max_rounds = int(arguments.get("max_debate_rounds", 4))
|
|
96
|
+
threshold = float(arguments.get("target_residual_threshold", 0.15))
|
|
97
|
+
|
|
98
|
+
synthesizer = DialecticalSynthesizer()
|
|
99
|
+
synthesis = synthesizer.synthesize(
|
|
100
|
+
thesis, critique, max_debate_rounds=max_rounds, target_residual_threshold=threshold
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
session = get_or_load_session(session_name)
|
|
104
|
+
session.system3_syntheses.append(synthesis.to_dict())
|
|
105
|
+
|
|
106
|
+
session.log_refinement_cycle(
|
|
107
|
+
refinement_type="system3_dialectical_synthesis",
|
|
108
|
+
focus_area=f"{thesis_title} vs {antithesis_title}",
|
|
109
|
+
critique_or_bottleneck=f"Contradictions: {len(parsed_contradictions)} parameter conflicts analyzed.",
|
|
110
|
+
architectural_refinement=synthesis.pareto_improvement_claim,
|
|
111
|
+
)
|
|
112
|
+
session.save()
|
|
113
|
+
|
|
114
|
+
principles_list = "\n".join([f"- **TRIZ Principle #{p.number} ({p.name})**: {p.description}" for p in synthesis.transcended_principles]) or "- No principles transcended."
|
|
115
|
+
contra_list = "\n".join([f"- `{c.improving_parameter}` vs `{c.worsening_parameter}`: {c.description} (Severity: {c.severity})" for c in synthesis.resolved_contradictions]) or "- None declared."
|
|
116
|
+
|
|
117
|
+
return (
|
|
118
|
+
f"### ⚡ System 3 Dialectical Synthesis Emerged\n\n"
|
|
119
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
120
|
+
f"- **Synthesis Title**: **{synthesis.title}** (`{synthesis.synthesis_id}`)\n"
|
|
121
|
+
f"- **Debate Rounds Executed**: `{synthesis.debate_rounds_executed}`\n"
|
|
122
|
+
f"- **Initial Contradiction Severity**: `{synthesis.initial_contradiction_score:.2f}`\n"
|
|
123
|
+
f"- **Residual Contradiction Severity**: `{synthesis.residual_contradiction_score:.2f}`\n"
|
|
124
|
+
f"- **Convergence Achieved**: `{'✅ YES' if synthesis.convergence_achieved else '⚠️ PARTIAL'}`\n\n"
|
|
125
|
+
f"#### 🧬 Transcended TRIZ Inventive Principles:\n{principles_list}\n\n"
|
|
126
|
+
f"#### ⚔️ Resolved Contradictions:\n{contra_list}\n\n"
|
|
127
|
+
f"#### 🏛️ Synthesized Architectural Blueprint:\n{synthesis.synthesized_architecture}\n\n"
|
|
128
|
+
f"> [!TIP]\n"
|
|
129
|
+
f"> {synthesis.pareto_improvement_claim}"
|
|
130
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _handle_system3_causal_simulate(arguments: Dict[str, Any]) -> str:
|
|
135
|
+
from fable_v2.system3 import CausalDAG, CausalNode, CausalEdge, CausalNodeType
|
|
136
|
+
action = arguments.get("action", "").strip().lower()
|
|
137
|
+
session_name = arguments.get("session_name", "").strip()
|
|
138
|
+
session: Optional[FableSession] = None
|
|
139
|
+
if not session_name:
|
|
140
|
+
return "Error: 'session_name' is required for action 'system3_causal_simulate'."
|
|
141
|
+
model_name = arguments.get("model_name", "System3CausalModel")
|
|
142
|
+
nodes_input = arguments.get("nodes", [])
|
|
143
|
+
edges_input = arguments.get("edges", [])
|
|
144
|
+
interventions_input = arguments.get("interventions", {})
|
|
145
|
+
target_metric = arguments.get("target_metric")
|
|
146
|
+
|
|
147
|
+
if isinstance(nodes_input, str):
|
|
148
|
+
try:
|
|
149
|
+
nodes_input = json.loads(nodes_input)
|
|
150
|
+
except Exception:
|
|
151
|
+
nodes_input = []
|
|
152
|
+
if isinstance(edges_input, str):
|
|
153
|
+
try:
|
|
154
|
+
edges_input = json.loads(edges_input)
|
|
155
|
+
except Exception:
|
|
156
|
+
edges_input = []
|
|
157
|
+
if isinstance(interventions_input, str):
|
|
158
|
+
try:
|
|
159
|
+
interventions_input = json.loads(interventions_input)
|
|
160
|
+
except Exception:
|
|
161
|
+
interventions_input = {}
|
|
162
|
+
|
|
163
|
+
dag = CausalDAG(name=model_name)
|
|
164
|
+
for n in nodes_input:
|
|
165
|
+
if isinstance(n, dict):
|
|
166
|
+
dag.add_node(
|
|
167
|
+
node_id=n.get("node_id", n.get("id")),
|
|
168
|
+
name=n.get("name"),
|
|
169
|
+
node_type=CausalNodeType(n.get("node_type", "endogenous")),
|
|
170
|
+
value=float(n.get("value", 0.0)),
|
|
171
|
+
default_value=float(n["default_value"]) if "default_value" in n else None,
|
|
172
|
+
min_value=float(n["min_value"]) if "min_value" in n else None,
|
|
173
|
+
max_value=float(n["max_value"]) if "max_value" in n else None,
|
|
174
|
+
description=n.get("description", ""),
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
for e in edges_input:
|
|
178
|
+
if isinstance(e, dict):
|
|
179
|
+
dag.add_edge(
|
|
180
|
+
source=e["source"],
|
|
181
|
+
target=e["target"],
|
|
182
|
+
weight=float(e.get("weight", 1.0)),
|
|
183
|
+
relation_type=e.get("relation_type", "linear"),
|
|
184
|
+
description=e.get("description", ""),
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
is_acyclic, cycle = dag.check_acyclicity()
|
|
188
|
+
if not is_acyclic:
|
|
189
|
+
return f"Error: Graph contains a cycle: {' -> '.join(cycle)}. Causal models must be valid DAGs."
|
|
190
|
+
|
|
191
|
+
topo_order = dag.topological_sort()
|
|
192
|
+
factual_values = dag.compute_forward()
|
|
193
|
+
|
|
194
|
+
interv_res = None
|
|
195
|
+
if interventions_input and isinstance(interventions_input, dict):
|
|
196
|
+
interv_map = {k: float(v) for k, v in interventions_input.items()}
|
|
197
|
+
interv_res = dag.do_intervention(interv_map)
|
|
198
|
+
|
|
199
|
+
brittleness_rep = None
|
|
200
|
+
if target_metric and target_metric in dag.nodes:
|
|
201
|
+
brittleness_rep = dag.evaluate_brittleness(target_metric)
|
|
202
|
+
|
|
203
|
+
session = get_or_load_session(session_name)
|
|
204
|
+
new_graph_entry = {
|
|
205
|
+
"dag": dag.to_dict(),
|
|
206
|
+
"nodes": dag.to_dict().get("nodes", []),
|
|
207
|
+
"edges": dag.to_dict().get("edges", []),
|
|
208
|
+
"topological_order": topo_order,
|
|
209
|
+
"factual_values": factual_values,
|
|
210
|
+
"intervention": interv_res.to_dict() if interv_res else None,
|
|
211
|
+
"brittleness": brittleness_rep.to_dict() if brittleness_rep else None,
|
|
212
|
+
"timestamp": time.time(),
|
|
213
|
+
}
|
|
214
|
+
if len(session.system3_causal_graphs) == 1 and session.system3_causal_graphs[0].get("dag", {}).get("name") == f"Session_{session.session_name}_DAG":
|
|
215
|
+
session.system3_causal_graphs[0] = new_graph_entry
|
|
216
|
+
else:
|
|
217
|
+
session.system3_causal_graphs.append(new_graph_entry)
|
|
218
|
+
session.save()
|
|
219
|
+
|
|
220
|
+
lines = [
|
|
221
|
+
f"### 🌐 System 3 Pearl's Do-Calculus & Causal Simulation\n\n",
|
|
222
|
+
f"- **Model**: `{dag.name}` ({len(dag.nodes)} nodes, {len(dag.edges)} directed causal edges)\n",
|
|
223
|
+
f"- **Topological Order**: `{' -> '.join(topo_order)}`\n",
|
|
224
|
+
]
|
|
225
|
+
|
|
226
|
+
if interv_res:
|
|
227
|
+
lines.append(f"\n#### ✂️ Pearl's Do-Operator Intervention: `do({interv_res.interventions})`\n")
|
|
228
|
+
lines.append(f"- **Severed Edges**: `{len(interv_res.severed_edges)}` ({interv_res.severed_edges})\n")
|
|
229
|
+
lines.append(f"- **Impacted Nodes**: `{', '.join(interv_res.impacted_nodes)}`\n\n")
|
|
230
|
+
lines.append("| Node | Factual Value | Counterfactual Value | Delta (Δ) |\n")
|
|
231
|
+
lines.append("|---|---|---|---|\n")
|
|
232
|
+
for nid in topo_order:
|
|
233
|
+
f_val = interv_res.original_values.get(nid, 0.0)
|
|
234
|
+
cf_val = interv_res.counterfactual_values.get(nid, 0.0)
|
|
235
|
+
delta = interv_res.deltas.get(nid, 0.0)
|
|
236
|
+
delta_str = f"+{delta:.4f}" if delta > 0 else f"{delta:.4f}"
|
|
237
|
+
lines.append(f"| `{nid}` | {f_val:.4f} | **{cf_val:.4f}** | `{delta_str}` |\n")
|
|
238
|
+
|
|
239
|
+
if brittleness_rep:
|
|
240
|
+
lines.append(f"\n#### 🔬 Structural Brittleness Report (`{brittleness_rep.target_metric}`)\n")
|
|
241
|
+
lines.append(f"- **Overall Brittleness Score**: `{brittleness_rep.overall_brittleness_score:.4f}` / 1.0\n")
|
|
242
|
+
spof_str = ", ".join(brittleness_rep.single_points_of_failure) if brittleness_rep.single_points_of_failure else "None (Resilient)"
|
|
243
|
+
lines.append(f"- **Single Points of Failure**: `{spof_str}`\n")
|
|
244
|
+
for rec in brittleness_rep.recommendations:
|
|
245
|
+
lines.append(f"- 💡 {rec}\n")
|
|
246
|
+
|
|
247
|
+
if session.execution_locked:
|
|
248
|
+
lines.append(SILENT_DELIBERATION_REMINDER)
|
|
249
|
+
|
|
250
|
+
return "".join(lines)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _handle_system3_evolve_paradigms(arguments: Dict[str, Any]) -> str:
|
|
254
|
+
from fable_v2.system3 import CognitiveGenome, CognitiveGenePool
|
|
255
|
+
action = arguments.get("action", "").strip().lower()
|
|
256
|
+
session_name = arguments.get("session_name", "").strip()
|
|
257
|
+
session: Optional[FableSession] = None
|
|
258
|
+
if not session_name:
|
|
259
|
+
return "Error: 'session_name' is required for action 'system3_evolve_paradigms'."
|
|
260
|
+
generations = int(arguments.get("generations", 3))
|
|
261
|
+
pop_size = int(arguments.get("population_size", 12))
|
|
262
|
+
mutation_rate = float(arguments.get("mutation_rate", 0.15))
|
|
263
|
+
crossover_rate = float(arguments.get("crossover_rate", 0.80))
|
|
264
|
+
seed_paradigms = arguments.get("seed_paradigms")
|
|
265
|
+
if isinstance(seed_paradigms, str):
|
|
266
|
+
try:
|
|
267
|
+
seed_paradigms = json.loads(seed_paradigms)
|
|
268
|
+
except Exception:
|
|
269
|
+
seed_paradigms = None
|
|
270
|
+
|
|
271
|
+
weights = arguments.get("objective_weights")
|
|
272
|
+
if isinstance(weights, str):
|
|
273
|
+
try:
|
|
274
|
+
weights = json.loads(weights)
|
|
275
|
+
except Exception:
|
|
276
|
+
weights = None
|
|
277
|
+
|
|
278
|
+
pool = CognitiveGenePool(
|
|
279
|
+
population_size=pop_size,
|
|
280
|
+
mutation_rate=mutation_rate,
|
|
281
|
+
crossover_rate=crossover_rate,
|
|
282
|
+
)
|
|
283
|
+
pool.initialize_population(seed_paradigms=seed_paradigms)
|
|
284
|
+
|
|
285
|
+
for _ in range(generations):
|
|
286
|
+
pool.evolve_generation()
|
|
287
|
+
|
|
288
|
+
pareto_frontier = pool.get_pareto_frontier()
|
|
289
|
+
best_genome = pool.get_best_genome(weights)
|
|
290
|
+
|
|
291
|
+
session = get_or_load_session(session_name)
|
|
292
|
+
session.system3_gene_pools.append(pool.to_dict())
|
|
293
|
+
|
|
294
|
+
session.log_refinement_cycle(
|
|
295
|
+
refinement_type="system3_evolutionary_optimization",
|
|
296
|
+
focus_area=f"10D Pareto Frontier Search across {generations} generations",
|
|
297
|
+
critique_or_bottleneck=f"Optimized {pop_size} genomes across 10 dimensions.",
|
|
298
|
+
architectural_refinement=f"Evolved top paradigm '{best_genome.paradigm_name}' with scalar fitness {best_genome.compute_scalar_fitness(weights):.4f}.",
|
|
299
|
+
)
|
|
300
|
+
session.save()
|
|
301
|
+
|
|
302
|
+
table_rows = []
|
|
303
|
+
for g in pareto_frontier[:5]:
|
|
304
|
+
f = g.fitness_scores
|
|
305
|
+
table_rows.append(
|
|
306
|
+
f"| `{g.genome_id}` | **{g.paradigm_name[:24]}** | `{f.get('latency',0):.2f}` | "
|
|
307
|
+
f"`{f.get('throughput',0):.2f}` | `{f.get('memory_efficiency',0):.2f}` | "
|
|
308
|
+
f"`{f.get('fault_tolerance',0):.2f}` | `{f.get('modularity',0):.2f}` | "
|
|
309
|
+
f"`{f.get('security',0):.2f}` | `{f.get('token_compaction',0):.2f}` | `{g.compute_scalar_fitness(weights):.4f}` |"
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
table_str = "\n".join(table_rows)
|
|
313
|
+
|
|
314
|
+
return (
|
|
315
|
+
f"### 🧬 System 3 Evolutionary Paradigm Engine\n\n"
|
|
316
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
317
|
+
f"- **Generations Evolved**: `{pool.generation_count}` (Population: `{len(pool.population)}`)\n"
|
|
318
|
+
f"- **Rank 1 Pareto Frontier Size**: `{len(pareto_frontier)}` non-dominated solutions\n"
|
|
319
|
+
f"- **Top Archetype**: **{best_genome.paradigm_name}** (`{best_genome.genome_id}`)\n\n"
|
|
320
|
+
f"#### 🏆 Top Rank 1 Non-Dominated Pareto Frontier:\n"
|
|
321
|
+
f"| ID | Paradigm | Lat | Tput | Mem | Fault | Mod | Sec | Token | Score |\n"
|
|
322
|
+
f"|---|---|---|---|---|---|---|---|---|---|\n"
|
|
323
|
+
f"{table_str}\n\n"
|
|
324
|
+
f"#### 🧬 Winning Gene Allocation (`{best_genome.genome_id}`):\n"
|
|
325
|
+
+ "\n".join([f"- **{k}**: `{v}`" for k, v in best_genome.genes.items()])
|
|
326
|
+
+ f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _handle_system3_induce_axioms(arguments: Dict[str, Any]) -> str:
|
|
331
|
+
from fable_v2.system3 import NeuroSymbolicAxiom, AxiomProvenance, AxiomStatus, MetaProofInducer
|
|
332
|
+
action = arguments.get("action", "").strip().lower()
|
|
333
|
+
session_name = arguments.get("session_name", "").strip()
|
|
334
|
+
session: Optional[FableSession] = None
|
|
335
|
+
if not session_name:
|
|
336
|
+
return "Error: 'session_name' is required for action 'system3_induce_axioms'."
|
|
337
|
+
session = get_or_load_session(session_name)
|
|
338
|
+
domain = arguments.get("domain", "architecture")
|
|
339
|
+
|
|
340
|
+
inducer = MetaProofInducer()
|
|
341
|
+
axioms = inducer.induce_axioms_from_session(
|
|
342
|
+
receipts=[],
|
|
343
|
+
evidence=[],
|
|
344
|
+
session_telemetry=session.get_telemetry(),
|
|
345
|
+
domain_hints=[domain],
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
for ax in axioms:
|
|
349
|
+
session.system3_axioms.append(ax.to_dict())
|
|
350
|
+
if not any(i.get("name") == ax.name for i in session.invariants):
|
|
351
|
+
session.record_invariant(
|
|
352
|
+
invariant_name=ax.name,
|
|
353
|
+
formal_statement=ax.symbolic_expression,
|
|
354
|
+
proof_or_rationale=ax.proof_sketch or ax.natural_language,
|
|
355
|
+
domain=ax.domain if ax.domain in ("architecture", "design", "coding") else "architecture",
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
session.save()
|
|
359
|
+
|
|
360
|
+
axiom_blocks = []
|
|
361
|
+
for ax in axioms:
|
|
362
|
+
axiom_blocks.append(
|
|
363
|
+
f"#### 📜 `{ax.axiom_id}`: **{ax.name}** `[{ax.domain.upper()}]`\n"
|
|
364
|
+
f"- **Symbolic Expression**: `{ax.symbolic_expression}`\n"
|
|
365
|
+
f"- **Natural Language**: {ax.natural_language}\n"
|
|
366
|
+
f"- **Epistemic Confidence**: `{ax.confidence * 100:.1f}%` (`{ax.status.value.upper()}`)\n"
|
|
367
|
+
f"- **Proof Rationale**: {ax.proof_sketch}\n"
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
return (
|
|
371
|
+
f"### 📐 System 3 Neuro-Symbolic Invariant Induction\n\n"
|
|
372
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
373
|
+
f"- **Axioms Induced**: `{len(axioms)}`\n"
|
|
374
|
+
f"- **Auto-Recorded Invariants**: `{len(session.invariants)}` total in session\n\n"
|
|
375
|
+
+ "\n".join(axiom_blocks)
|
|
376
|
+
+ f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _handle_system3_meta_reflect(arguments: Dict[str, Any]) -> str:
|
|
381
|
+
from fable_v2.system3 import CognitiveBiasType, CognitiveBiasFinding, CognitiveBiasDetector, System3Executive
|
|
382
|
+
action = arguments.get("action", "").strip().lower()
|
|
383
|
+
session_name = arguments.get("session_name", "").strip()
|
|
384
|
+
session: Optional[FableSession] = None
|
|
385
|
+
if not session_name:
|
|
386
|
+
return "Error: 'session_name' is required for action 'system3_meta_reflect'."
|
|
387
|
+
session = get_or_load_session(session_name)
|
|
388
|
+
focus_area = arguments.get("focus_area", "Full Deliberation Trace")
|
|
389
|
+
|
|
390
|
+
executive = System3Executive()
|
|
391
|
+
report = executive.meta_reflect(session.to_dict())
|
|
392
|
+
|
|
393
|
+
session.system3_reflections.append(report)
|
|
394
|
+
|
|
395
|
+
bias_summary = f"{len(report['bias_findings'])} biases flagged" if report['bias_findings'] else "0 biases detected (Clean)"
|
|
396
|
+
session.log_refinement_cycle(
|
|
397
|
+
refinement_type="system3_meta_reflection",
|
|
398
|
+
focus_area=focus_area,
|
|
399
|
+
critique_or_bottleneck=f"Meta-cognitive audit: {bias_summary}. Contradiction density: {report['contradiction_density']:.2f}.",
|
|
400
|
+
architectural_refinement=f"Shifted cognitive gear to {report['cognitive_gear']}. Updated search heuristics temperature: {report['updated_search_heuristics']['exploration_temperature']}.",
|
|
401
|
+
)
|
|
402
|
+
session.save()
|
|
403
|
+
|
|
404
|
+
bias_lines = []
|
|
405
|
+
for b in report["bias_findings"]:
|
|
406
|
+
bias_lines.append(
|
|
407
|
+
f"- ⚠️ **{b['bias_type'].upper()}** (Severity: `{b['severity']}` in *{b['detected_in']}*):\n"
|
|
408
|
+
f" - *Evidence*: {b['evidence_trail']}\n"
|
|
409
|
+
f" - *Mitigation*: {b['mitigation_strategy']}"
|
|
410
|
+
)
|
|
411
|
+
bias_block = "\n".join(bias_lines) if bias_lines else "✅ Zero cognitive biases detected. Epistemic reasoning is well-calibrated."
|
|
412
|
+
|
|
413
|
+
directives_block = "\n".join([f"- 🎯 {d}" for d in report["directives"]])
|
|
414
|
+
|
|
415
|
+
return (
|
|
416
|
+
f"### 🧠 System 3 Meta-Cognitive Deliberation Audit\n\n"
|
|
417
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
418
|
+
f"- **Recommended Cognitive Gear**: `{report['cognitive_gear'].upper()}`\n"
|
|
419
|
+
f"- **Contradiction Density**: `{report['contradiction_density']:.2f}`\n"
|
|
420
|
+
f"- **Arbitration Rationale**: {report['arbitration_rationale']}\n\n"
|
|
421
|
+
f"#### 🔍 Cognitive Bias Diagnostics:\n{bias_block}\n\n"
|
|
422
|
+
f"#### 🚀 System 3 Executive Directives:\n{directives_block}\n\n"
|
|
423
|
+
f"#### ⚙️ Dynamic Search Heuristics:\n"
|
|
424
|
+
f"- **Exploration Temperature**: `{report['updated_search_heuristics']['exploration_temperature']}`\n"
|
|
425
|
+
f"- **Pruning Cutoff Threshold**: `{report['updated_search_heuristics']['pruning_threshold']}`\n"
|
|
426
|
+
f"- **Max Branching Factor**: `{report['updated_search_heuristics']['max_branching_factor']}`\n"
|
|
427
|
+
f"- **Falsification Intensity**: `{report['updated_search_heuristics']['falsification_intensity']}`"
|
|
428
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _handle_system3_tri_level_orchestrate(arguments: Dict[str, Any]) -> str:
|
|
433
|
+
from fable_v2.system3 import TriLevelArbitrator, CognitiveGear, SearchHeuristicConfig, DynamicSearchHeuristicRewriter
|
|
434
|
+
action = arguments.get("action", "").strip().lower()
|
|
435
|
+
session_name = arguments.get("session_name", "").strip()
|
|
436
|
+
session: Optional[FableSession] = None
|
|
437
|
+
if not session_name:
|
|
438
|
+
return "Error: 'session_name' is required for action 'system3_tri_level_orchestrate'."
|
|
439
|
+
complexity = float(arguments.get("task_complexity", 0.75))
|
|
440
|
+
density = float(arguments.get("contradiction_density", 0.60))
|
|
441
|
+
failures = int(arguments.get("failure_count", 0))
|
|
442
|
+
uncertainty = float(arguments.get("epistemic_uncertainty", 0.40))
|
|
443
|
+
|
|
444
|
+
arbitrator = TriLevelArbitrator()
|
|
445
|
+
decision = arbitrator.arbitrate(
|
|
446
|
+
task_complexity=complexity,
|
|
447
|
+
contradiction_density=density,
|
|
448
|
+
failure_count=failures,
|
|
449
|
+
epistemic_uncertainty=uncertainty,
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
session = get_or_load_session(session_name)
|
|
453
|
+
session.system3_orchestrations.append({
|
|
454
|
+
"decision": decision,
|
|
455
|
+
"timestamp": time.time(),
|
|
456
|
+
"inputs": {
|
|
457
|
+
"complexity": complexity,
|
|
458
|
+
"density": density,
|
|
459
|
+
"failures": failures,
|
|
460
|
+
"uncertainty": uncertainty,
|
|
461
|
+
}
|
|
462
|
+
})
|
|
463
|
+
session.save()
|
|
464
|
+
|
|
465
|
+
directives_str = "\n".join([f"- {d}" for d in decision["directives"]])
|
|
466
|
+
|
|
467
|
+
return (
|
|
468
|
+
f"### 🎛️ System 3 Tri-Level Cognitive Arbitration\n\n"
|
|
469
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
470
|
+
f"- **Recommended Operating Gear**: `⚙️ {decision['recommended_gear'].upper()}`\n"
|
|
471
|
+
f"- **Composite Difficulty Index**: `{decision['composite_difficulty']:.3f}` / 1.0\n"
|
|
472
|
+
f"- **Arbitration Rationale**: {decision['rationale']}\n\n"
|
|
473
|
+
f"#### 🧭 Prescribed Cognitive Action Directives:\n{directives_str}"
|
|
474
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _handle_system3_hyperbolic_embed(arguments: Dict[str, Any]) -> str:
|
|
479
|
+
from fable_v2.system3 import PoincareBall, HyperbolicPoint, HyperbolicTreeEmbedder
|
|
480
|
+
action = arguments.get("action", "").strip().lower()
|
|
481
|
+
session_name = arguments.get("session_name", "").strip()
|
|
482
|
+
session: Optional[FableSession] = None
|
|
483
|
+
if not session_name:
|
|
484
|
+
return "Error: 'session_name' is required for action 'system3_hyperbolic_embed'."
|
|
485
|
+
tree_input = arguments.get("tree")
|
|
486
|
+
if tree_input is None:
|
|
487
|
+
return "Error: 'tree' is required for action 'system3_hyperbolic_embed'."
|
|
488
|
+
if isinstance(tree_input, str):
|
|
489
|
+
try:
|
|
490
|
+
tree_input = json.loads(tree_input)
|
|
491
|
+
except Exception:
|
|
492
|
+
return "Error: Failed to parse 'tree' as JSON."
|
|
493
|
+
|
|
494
|
+
root_id = arguments.get("root_id")
|
|
495
|
+
dimension = int(arguments.get("dimension", 2))
|
|
496
|
+
curvature = float(arguments.get("curvature", 1.0))
|
|
497
|
+
base_step = float(arguments.get("base_step", 1.0))
|
|
498
|
+
node_labels = arguments.get("node_labels")
|
|
499
|
+
if isinstance(node_labels, str):
|
|
500
|
+
try:
|
|
501
|
+
node_labels = json.loads(node_labels)
|
|
502
|
+
except Exception:
|
|
503
|
+
node_labels = None
|
|
504
|
+
|
|
505
|
+
embedder = HyperbolicTreeEmbedder(dimension=dimension, curvature=curvature, base_step_distance=base_step)
|
|
506
|
+
result = embedder.embed_hierarchy(tree=tree_input, root_id=root_id, node_labels=node_labels)
|
|
507
|
+
|
|
508
|
+
session = get_or_load_session(session_name)
|
|
509
|
+
session.system3_hyperbolic_embeddings.append(result.to_dict())
|
|
510
|
+
|
|
511
|
+
session.log_refinement_cycle(
|
|
512
|
+
refinement_type="system3_hyperbolic_embedding",
|
|
513
|
+
focus_area=f"Hierarchical Poincaré Manifold Embedding ({result.total_nodes} nodes, depth {result.tree_depth})",
|
|
514
|
+
critique_or_bottleneck=f"Embedded hierarchy into {dimension}D Poincaré ball with curvature c={curvature:.2f}.",
|
|
515
|
+
architectural_refinement=(
|
|
516
|
+
f"Manifold tree embedding verified: avg_distortion={result.average_distortion:.4f}, "
|
|
517
|
+
f"max_distortion={result.max_distortion:.4f}, stress={result.stress:.4f}, "
|
|
518
|
+
f"exponential capacity ratio={result.hierarchical_capacity_ratio:.2f}x."
|
|
519
|
+
),
|
|
520
|
+
)
|
|
521
|
+
session.save()
|
|
522
|
+
|
|
523
|
+
node_table = []
|
|
524
|
+
for nid, node in list(result.nodes.items())[:10]:
|
|
525
|
+
coords_str = f"({', '.join([f'{c:.4f}' for c in node.coords])})"
|
|
526
|
+
node_table.append(
|
|
527
|
+
f"| `{node.node_id}` | **{node.label[:20]}** | `{node.depth}` | `{node.subtree_size}` | `{coords_str}` |"
|
|
528
|
+
)
|
|
529
|
+
node_table_str = "\n".join(node_table)
|
|
530
|
+
|
|
531
|
+
return (
|
|
532
|
+
f"### 🌐 System 3 Poincaré Hyperbolic Manifold Embedding\n\n"
|
|
533
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
534
|
+
f"- **Manifold**: Poincaré Ball $\\mathbb{{B}}^{{{result.dimension}}}_{{c={result.curvature:.2f}}}$\n"
|
|
535
|
+
f"- **Hierarchy**: Root `{result.root_id}` ({result.total_nodes} nodes, max depth `{result.tree_depth}`)\n"
|
|
536
|
+
f"- **Mean Metric Distortion**: `{result.average_distortion:.4f}` (Max: `{result.max_distortion:.4f}`)\n"
|
|
537
|
+
f"- **Metric Stress Metric**: `{result.stress:.4f}`\n"
|
|
538
|
+
f"- **Hyperbolic Volume Expansion Ratio**: `{result.hierarchical_capacity_ratio:.2f}x` vs Euclidean $\\mathbb{{R}}^{{{result.dimension}}}$\n\n"
|
|
539
|
+
f"#### 📍 Top Embedded Nodes in $\\mathbb{{B}}^{{{result.dimension}}}$:\n"
|
|
540
|
+
f"| Node ID | Label | Depth | Subtree | Poincaré Coordinates |\n"
|
|
541
|
+
f"|---|---|---|---|---|\n"
|
|
542
|
+
f"{node_table_str}\n"
|
|
543
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _handle_system3_kripke_verify(arguments: Dict[str, Any]) -> str:
|
|
548
|
+
from fable_v2.system3 import KripkeStructure, KripkeWorld, KripkeModelChecker
|
|
549
|
+
action = arguments.get("action", "").strip().lower()
|
|
550
|
+
session_name = arguments.get("session_name", "").strip()
|
|
551
|
+
session: Optional[FableSession] = None
|
|
552
|
+
if not session_name:
|
|
553
|
+
return "Error: 'session_name' is required for action 'system3_kripke_verify'."
|
|
554
|
+
formula = arguments.get("formula", "").strip()
|
|
555
|
+
if not formula:
|
|
556
|
+
return "Error: 'formula' is required for action 'system3_kripke_verify'."
|
|
557
|
+
model_name = arguments.get("model_name", "System3KripkeModel")
|
|
558
|
+
worlds_input = arguments.get("worlds", [])
|
|
559
|
+
transitions_input = arguments.get("transitions", [])
|
|
560
|
+
initial_world = arguments.get("initial_world")
|
|
561
|
+
|
|
562
|
+
if isinstance(worlds_input, str):
|
|
563
|
+
try:
|
|
564
|
+
worlds_input = json.loads(worlds_input)
|
|
565
|
+
except Exception:
|
|
566
|
+
worlds_input = []
|
|
567
|
+
if isinstance(transitions_input, str):
|
|
568
|
+
try:
|
|
569
|
+
transitions_input = json.loads(transitions_input)
|
|
570
|
+
except Exception:
|
|
571
|
+
transitions_input = []
|
|
572
|
+
|
|
573
|
+
structure = KripkeStructure(name=model_name)
|
|
574
|
+
for w in worlds_input:
|
|
575
|
+
if isinstance(w, dict):
|
|
576
|
+
structure.add_world(
|
|
577
|
+
world_id=w.get("world_id", w.get("id")),
|
|
578
|
+
propositions=w.get("propositions", w.get("props", [])),
|
|
579
|
+
name=w.get("name", ""),
|
|
580
|
+
is_initial=w.get("is_initial", False),
|
|
581
|
+
metadata=w.get("metadata", {}),
|
|
582
|
+
)
|
|
583
|
+
elif isinstance(w, str):
|
|
584
|
+
structure.add_world(world_id=w)
|
|
585
|
+
|
|
586
|
+
if isinstance(transitions_input, dict):
|
|
587
|
+
for src, targets in transitions_input.items():
|
|
588
|
+
for tgt in (targets if isinstance(targets, list) else [targets]):
|
|
589
|
+
structure.add_transition(src, tgt)
|
|
590
|
+
elif isinstance(transitions_input, list):
|
|
591
|
+
for t in transitions_input:
|
|
592
|
+
if isinstance(t, dict) and "source" in t and "target" in t:
|
|
593
|
+
structure.add_transition(t["source"], t["target"])
|
|
594
|
+
elif isinstance(t, (list, tuple)) and len(t) >= 2:
|
|
595
|
+
structure.add_transition(str(t[0]), str(t[1]))
|
|
596
|
+
|
|
597
|
+
checker = KripkeModelChecker(structure)
|
|
598
|
+
res = checker.check(formula=formula, initial_world=initial_world)
|
|
599
|
+
|
|
600
|
+
session = get_or_load_session(session_name)
|
|
601
|
+
session.system3_kripke_verifications.append(res.to_dict())
|
|
602
|
+
|
|
603
|
+
session.log_refinement_cycle(
|
|
604
|
+
refinement_type="system3_kripke_verification",
|
|
605
|
+
focus_area=f"Modal / CTL Verification: {res.formula}",
|
|
606
|
+
critique_or_bottleneck=f"Evaluated Kripke model '{structure.name}' ({res.total_worlds} worlds).",
|
|
607
|
+
architectural_refinement=(
|
|
608
|
+
f"Model checking result: {'✅ SATISFIED' if res.is_satisfied else '❌ VIOLATED'}. "
|
|
609
|
+
f"Satisfied worlds: {len(res.satisfied_worlds)}/{res.total_worlds}. "
|
|
610
|
+
f"Witness/Counterexample: {res.witness_path or res.counterexample_path}."
|
|
611
|
+
),
|
|
612
|
+
)
|
|
613
|
+
session.save()
|
|
614
|
+
|
|
615
|
+
trace_block = ""
|
|
616
|
+
if res.counterexample_path:
|
|
617
|
+
trace_block = f"\n#### ❌ Counterexample Violation Trace:\n`{' -> '.join(res.counterexample_path)}`\n"
|
|
618
|
+
elif res.witness_path:
|
|
619
|
+
trace_block = f"\n#### ✅ Witness Path:\n`{' -> '.join(res.witness_path)}`\n"
|
|
620
|
+
|
|
621
|
+
return (
|
|
622
|
+
f"### 🛡️ System 3 Kripke Modal Model Verification\n\n"
|
|
623
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
624
|
+
f"- **Model**: `{structure.name}` ({res.total_worlds} worlds)\n"
|
|
625
|
+
f"- **Formula**: `{res.formula}`\n"
|
|
626
|
+
f"- **Status**: `{'✅ SATISFIED' if res.is_satisfied else '❌ VIOLATED'}` at initial world `{res.initial_world}`\n"
|
|
627
|
+
f"- **Satisfied Worlds**: `{', '.join(res.satisfied_worlds) if res.satisfied_worlds else 'None'}`\n"
|
|
628
|
+
f"- **Violated Worlds**: `{', '.join(res.violated_worlds) if res.violated_worlds else 'None'}`\n"
|
|
629
|
+
f"{trace_block}\n"
|
|
630
|
+
f"> [!TIP]\n"
|
|
631
|
+
f"> {res.details}"
|
|
632
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _handle_system3_active_inference(arguments: Dict[str, Any]) -> str:
|
|
637
|
+
from fable_v2.system3 import ActiveInferenceEngine, GenerativeModel, Policy, create_default_architecture_pomdp
|
|
638
|
+
action = arguments.get("action", "").strip().lower()
|
|
639
|
+
session_name = arguments.get("session_name", "").strip()
|
|
640
|
+
session: Optional[FableSession] = None
|
|
641
|
+
if not session_name:
|
|
642
|
+
return "Error: 'session_name' is required for action 'system3_active_inference'."
|
|
643
|
+
obs = arguments.get("observation", "HIGH_THROUGHPUT_CLEAN").strip()
|
|
644
|
+
gamma = float(arguments.get("gamma", 16.0))
|
|
645
|
+
policies_input = arguments.get("policies")
|
|
646
|
+
if isinstance(policies_input, str):
|
|
647
|
+
try:
|
|
648
|
+
policies_input = json.loads(policies_input)
|
|
649
|
+
except Exception:
|
|
650
|
+
policies_input = None
|
|
651
|
+
|
|
652
|
+
parsed_policies = []
|
|
653
|
+
if policies_input and isinstance(policies_input, list):
|
|
654
|
+
for p in policies_input:
|
|
655
|
+
if isinstance(p, dict) and "policy_id" in p and "actions" in p:
|
|
656
|
+
parsed_policies.append(Policy.from_dict(p))
|
|
657
|
+
elif isinstance(p, str):
|
|
658
|
+
parsed_policies.append(Policy(policy_id=f"pol_{p}", actions=[p]))
|
|
659
|
+
|
|
660
|
+
# Check if custom model components provided
|
|
661
|
+
states = arguments.get("states")
|
|
662
|
+
observations = arguments.get("observations")
|
|
663
|
+
actions = arguments.get("actions")
|
|
664
|
+
a_mat = arguments.get("a_matrix")
|
|
665
|
+
b_mats = arguments.get("b_matrices")
|
|
666
|
+
c_pref = arguments.get("c_preferences")
|
|
667
|
+
d_prior = arguments.get("d_prior")
|
|
668
|
+
|
|
669
|
+
if all(x is not None for x in [states, observations, actions, a_mat, b_mats, c_pref, d_prior]):
|
|
670
|
+
if isinstance(states, str): states = json.loads(states)
|
|
671
|
+
if isinstance(observations, str): observations = json.loads(observations)
|
|
672
|
+
if isinstance(actions, str): actions = json.loads(actions)
|
|
673
|
+
if isinstance(a_mat, str): a_mat = json.loads(a_mat)
|
|
674
|
+
if isinstance(b_mats, str): b_mats = json.loads(b_mats)
|
|
675
|
+
if isinstance(c_pref, str): c_pref = json.loads(c_pref)
|
|
676
|
+
if isinstance(d_prior, str): d_prior = json.loads(d_prior)
|
|
677
|
+
gen_model = GenerativeModel(
|
|
678
|
+
states=states,
|
|
679
|
+
observations=observations,
|
|
680
|
+
actions=actions,
|
|
681
|
+
a_matrix=a_mat,
|
|
682
|
+
b_matrices=b_mats,
|
|
683
|
+
c_preferences=c_pref,
|
|
684
|
+
d_prior=d_prior,
|
|
685
|
+
)
|
|
686
|
+
else:
|
|
687
|
+
gen_model = create_default_architecture_pomdp()
|
|
688
|
+
|
|
689
|
+
engine = ActiveInferenceEngine(generative_model=gen_model, policy_precision_gamma=gamma)
|
|
690
|
+
report = engine.select_action(observation=obs, candidate_policies=parsed_policies)
|
|
691
|
+
|
|
692
|
+
session = get_or_load_session(session_name)
|
|
693
|
+
session.system3_active_inferences.append(report.to_dict())
|
|
694
|
+
|
|
695
|
+
session.log_refinement_cycle(
|
|
696
|
+
refinement_type="system3_active_inference",
|
|
697
|
+
focus_area=f"Free Energy Minimization for observation '{obs}'",
|
|
698
|
+
critique_or_bottleneck=(
|
|
699
|
+
f"Variational Free Energy F={report.variational_free_energy_f:.4f} "
|
|
700
|
+
f"(Complexity KL={report.complexity_kl:.4f}, Accuracy={report.accuracy_log_likelihood:.4f})."
|
|
701
|
+
),
|
|
702
|
+
architectural_refinement=(
|
|
703
|
+
f"Selected optimal policy '{report.selected_policy.policy_id}' ({report.selected_action}) "
|
|
704
|
+
f"with Expected Free Energy G={report.selected_policy.expected_free_energy_g:.4f}, "
|
|
705
|
+
f"Information Gain={report.selected_policy.epistemic_information_gain:.4f}, "
|
|
706
|
+
f"Goal Utility={report.selected_policy.pragmatic_goal_utility:.4f}."
|
|
707
|
+
),
|
|
708
|
+
)
|
|
709
|
+
session.save()
|
|
710
|
+
|
|
711
|
+
policy_table = []
|
|
712
|
+
for p in report.evaluated_policies:
|
|
713
|
+
opt_mark = "🏆 OPTIMAL" if p.is_optimal else ""
|
|
714
|
+
policy_table.append(
|
|
715
|
+
f"| `{p.policy_id}` | `{p.actions}` | `{p.expected_free_energy_g:.4f}` | "
|
|
716
|
+
f"`{p.risk_pragmatic_divergence:.4f}` | `{p.ambiguity_expected_entropy:.4f}` | "
|
|
717
|
+
f"`{p.epistemic_information_gain:.4f}` | `{p.pragmatic_goal_utility:.4f}` | "
|
|
718
|
+
f"`{p.probability * 100:.1f}%` | {opt_mark} |"
|
|
719
|
+
)
|
|
720
|
+
pol_table_str = "\n".join(policy_table)
|
|
721
|
+
|
|
722
|
+
belief_table = "\n".join([f"- **{k}**: `{v * 100:.1f}%`" for k, v in report.belief_state.items()])
|
|
723
|
+
|
|
724
|
+
return (
|
|
725
|
+
f"### ⚡ System 3 Friston Active Inference & Variational Free Energy\n\n"
|
|
726
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
727
|
+
f"- **Ingested Observation**: `{report.current_observation}`\n"
|
|
728
|
+
f"- **Variational Free Energy (F)**: `{report.variational_free_energy_f:.4f}` (Surprisal Bound)\n"
|
|
729
|
+
f" - *Complexity (KL)*: `{report.complexity_kl:.4f}`\n"
|
|
730
|
+
f" - *Accuracy (Log-Likelihood)*: `{report.accuracy_log_likelihood:.4f}`\n"
|
|
731
|
+
f"- **Selected Policy**: **{report.selected_policy.policy_id}** -> Action: `🎯 {report.selected_action}`\n\n"
|
|
732
|
+
f"#### 🧠 Updated Hidden State Belief Distribution $q(s)$:\n{belief_table}\n\n"
|
|
733
|
+
f"#### 📊 Evaluated Policy Landscape ($G(\\pi) = \\text{{Risk}} + \\text{{Ambiguity}}$):\n"
|
|
734
|
+
f"| Policy ID | Actions | EFE ($G$) | Risk | Ambiguity | Epistemic Info Gain | Goal Utility | Prob | Status |\n"
|
|
735
|
+
f"|---|---|---|---|---|---|---|---|---|\n"
|
|
736
|
+
f"{pol_table_str}\n"
|
|
737
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _handle_system3_proof_oracle(arguments: Dict[str, Any]) -> str:
|
|
742
|
+
from fable_v2.system3 import ProofOracle, CurryHowardVerifier, UndecidabilityDetector, TacticsEngine, ProofStatus, FormalProofResult, Prop, Implies, And, App, Pair, Fst, Snd, Inl, Inr, Case, Refl, Abort
|
|
743
|
+
action = arguments.get("action", "").strip().lower()
|
|
744
|
+
session_name = arguments.get("session_name", "").strip()
|
|
745
|
+
session: Optional[FableSession] = None
|
|
746
|
+
if not session_name:
|
|
747
|
+
return "Error: 'session_name' is required for action 'system3_proof_oracle'."
|
|
748
|
+
claim = arguments.get("claim")
|
|
749
|
+
if not claim:
|
|
750
|
+
return "Error: 'claim' is required for action 'system3_proof_oracle'."
|
|
751
|
+
|
|
752
|
+
context = arguments.get("context")
|
|
753
|
+
if isinstance(context, str):
|
|
754
|
+
try:
|
|
755
|
+
context = json.loads(context)
|
|
756
|
+
except Exception:
|
|
757
|
+
context = None
|
|
758
|
+
|
|
759
|
+
axioms = arguments.get("axioms")
|
|
760
|
+
if isinstance(axioms, str):
|
|
761
|
+
try:
|
|
762
|
+
axioms = json.loads(axioms)
|
|
763
|
+
except Exception:
|
|
764
|
+
axioms = None
|
|
765
|
+
|
|
766
|
+
oracle = ProofOracle()
|
|
767
|
+
res = oracle.verify_proposition(claim=claim, context=context, axioms=axioms)
|
|
768
|
+
|
|
769
|
+
session = get_or_load_session(session_name)
|
|
770
|
+
session.system3_proof_oracle_verifications.append(res.to_dict())
|
|
771
|
+
|
|
772
|
+
# Auto-record invariant if proved and sound
|
|
773
|
+
if res.status == ProofStatus.DECIDABLE_PROVED and res.is_sound:
|
|
774
|
+
inv_name = f"INV-ORACLE: {str(claim)[:32]}"
|
|
775
|
+
if not any(i.get("name") == inv_name for i in session.invariants):
|
|
776
|
+
session.record_invariant(
|
|
777
|
+
invariant_name=inv_name,
|
|
778
|
+
formal_statement=res.proposition,
|
|
779
|
+
proof_or_rationale=f"Curry-Howard Constructive Proof Term: {res.proof_term_repr}",
|
|
780
|
+
domain="architecture",
|
|
781
|
+
)
|
|
782
|
+
|
|
783
|
+
session.log_refinement_cycle(
|
|
784
|
+
refinement_type="system3_proof_oracle",
|
|
785
|
+
focus_area=f"Curry-Howard Constructive Proof: {res.proposition}",
|
|
786
|
+
critique_or_bottleneck=f"Evaluated status: {res.status.value.upper()}.",
|
|
787
|
+
architectural_refinement=(
|
|
788
|
+
f"Proof Oracle verdict: {res.status.value.upper()} (Sound: {res.is_sound}). "
|
|
789
|
+
f"Proof Term: {res.proof_term_repr or 'None'}."
|
|
790
|
+
),
|
|
791
|
+
)
|
|
792
|
+
session.save()
|
|
793
|
+
|
|
794
|
+
steps_str = "\n".join([f"- {s}" for s in res.verification_steps])
|
|
795
|
+
undec_str = ""
|
|
796
|
+
if res.undecidability_diagnostics:
|
|
797
|
+
undec_str = (
|
|
798
|
+
f"\n#### 🛑 Gödelian Boundary Diagnostics:\n"
|
|
799
|
+
f"- **Boundary Type**: `{res.undecidability_diagnostics.get('boundary_type')}`\n"
|
|
800
|
+
f"- **Explanation**: {res.undecidability_diagnostics.get('explanation')}\n"
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
return (
|
|
804
|
+
f"### 📜 System 3 Gödelian Auto-Formalizing Proof Oracle\n\n"
|
|
805
|
+
f"- **Session**: `{session.session_name}`\n"
|
|
806
|
+
f"- **Proposition**: `{res.proposition}`\n"
|
|
807
|
+
f"- **Decision Status**: `{'✅ ' if res.status == ProofStatus.DECIDABLE_PROVED else '⚡ ' if res.status == ProofStatus.DECIDABLE_REFUTED else '🛑 '}{res.status.value.upper()}`\n"
|
|
808
|
+
f"- **Soundness Verified**: `{'✅ TRUE' if res.is_sound else '❌ UNVERIFIED'}`\n"
|
|
809
|
+
+ (f"- **Constructive Proof Term**: `{res.proof_term_repr}`\n" if res.proof_term_repr else "")
|
|
810
|
+
+ f"{undec_str}\n"
|
|
811
|
+
f"#### 🔍 Verification Trace:\n{steps_str}\n"
|
|
812
|
+
f"{SILENT_DELIBERATION_REMINDER if session.execution_locked else ''}"
|
|
813
|
+
)
|
|
814
|
+
|
|
815
|
+
|