tri-star-symbolic-assembly-lang 0.1.0__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.
- crawler/__init__.py +0 -0
- crawler/madmonkey_crawler.py +15 -0
- madmonkey/__init__.py +0 -0
- madmonkey/intake.py +9 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/METADATA +423 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/RECORD +89 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/WHEEL +5 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/entry_points.txt +11 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/licenses/LICENSE +63 -0
- tri_star_symbolic_assembly_lang-0.1.0.dist-info/top_level.txt +3 -0
- tsal/__init__.py +95 -0
- tsal/audit/__init__.py +11 -0
- tsal/audit/brian_self_audit.py +114 -0
- tsal/cli/__init__.py +1 -0
- tsal/cli/beast.py +4 -0
- tsal/cli/brian.py +4 -0
- tsal/cli/brian_optimize.py +6 -0
- tsal/cli/meshkeeper.py +4 -0
- tsal/cli/party.py +4 -0
- tsal/cli/reflect.py +4 -0
- tsal/cli/watchdog.py +4 -0
- tsal/core/__init__.py +60 -0
- tsal/core/connectivity.py +32 -0
- tsal/core/constants.py +18 -0
- tsal/core/ethics_engine.py +48 -0
- tsal/core/executor.py +58 -0
- tsal/core/intent_metric.py +17 -0
- tsal/core/json_dsl.py +51 -0
- tsal/core/logic_gate.py +52 -0
- tsal/core/madmonkey_handler.py +10 -0
- tsal/core/mesh_logger.py +30 -0
- tsal/core/module_registry.py +108 -0
- tsal/core/optimizer_utils.py +78 -0
- tsal/core/opwords.py +126 -0
- tsal/core/phase_math.py +256 -0
- tsal/core/phi_math.py +44 -0
- tsal/core/reflection.py +104 -0
- tsal/core/rev_eng.py +185 -0
- tsal/core/spark_translator.py +57 -0
- tsal/core/spiral_fusion.py +45 -0
- tsal/core/spiral_memory.py +22 -0
- tsal/core/spiral_vector.py +39 -0
- tsal/core/stack_vm.py +49 -0
- tsal/core/state_vector.py +38 -0
- tsal/core/symbols.py +70 -0
- tsal/core/tokenize_flowchart.py +24 -0
- tsal/core/tsal_executor.py +533 -0
- tsal/core/voxel.py +16 -0
- tsal/renderer/__init__.py +0 -0
- tsal/renderer/code_render.py +13 -0
- tsal/rl/__init__.py +0 -0
- tsal/rl/madmonkey.py +56 -0
- tsal/schemas/__init__.py +1 -0
- tsal/schemas/python.json +13 -0
- tsal/singer/__init__.py +13 -0
- tsal/tools/__init__.py +43 -0
- tsal/tools/aletheia_checker.py +54 -0
- tsal/tools/alignment_guard.py +20 -0
- tsal/tools/archetype_fetcher.py +44 -0
- tsal/tools/brian/__init__.py +5 -0
- tsal/tools/brian/optimizer.py +205 -0
- tsal/tools/codec.py +31 -0
- tsal/tools/feedback_ingest.py +25 -0
- tsal/tools/goal_selector.py +26 -0
- tsal/tools/issue_agent.py +67 -0
- tsal/tools/kintsugi/__init__.py +1 -0
- tsal/tools/kintsugi/kintsugi.py +15 -0
- tsal/tools/meshkeeper.py +81 -0
- tsal/tools/module_draft.py +54 -0
- tsal/tools/party_tricks.py +128 -0
- tsal/tools/reflect.py +43 -0
- tsal/tools/spiral_audit.py +68 -0
- tsal/tools/state_tracker.py +66 -0
- tsal/tools/watchdog.py +40 -0
- tsal/tristar/__init__.py +4 -0
- tsal/tristar/governor.py +56 -0
- tsal/tristar/handshake.py +31 -0
- tsal/utils/__init__.py +26 -0
- tsal/utils/error_dignity.py +20 -0
- tsal/utils/fuzzy_spellcheck.py +7 -0
- tsal/utils/github_api.py +82 -0
- tsal/utils/grammar_db.py +155 -0
- tsal/utils/groundnews_api.py +9 -0
- tsal/utils/humour_db.py +75 -0
- tsal/utils/intent_metrics.py +44 -0
- tsal/utils/language_db.py +55 -0
- tsal/utils/octopus_api.py +46 -0
- tsal/utils/system_status.py +34 -0
- tsal/utils/wikipedia_api.py +46 -0
tsal/__init__.py
ADDED
@@ -0,0 +1,95 @@
|
|
1
|
+
"""TSAL Consciousness Computing Framework."""
|
2
|
+
|
3
|
+
from .core.rev_eng import Rev_Eng
|
4
|
+
from .core.phase_math import phase_match_enhanced, mesh_phase_sync
|
5
|
+
from .core.phi_math import (
|
6
|
+
phi_wavefunction,
|
7
|
+
phase_alignment_potential,
|
8
|
+
corrected_energy,
|
9
|
+
orbital_radius,
|
10
|
+
)
|
11
|
+
from .core.voxel import MeshVoxel
|
12
|
+
from .core.tokenize_flowchart import tokenize_to_flowchart
|
13
|
+
from .core.json_dsl import LanguageMap, SymbolicProcessor
|
14
|
+
from .core.spiral_vector import SpiralVector, phi_alignment
|
15
|
+
from .core.spiral_fusion import SpiralFusionProtocol
|
16
|
+
from .core.ethics_engine import EthicsEngine
|
17
|
+
from .core.opwords import OP_WORD_MAP, op_from_word
|
18
|
+
from .core.spark_translator import SPARK_TO_OPCODE, translate_spark_word
|
19
|
+
from .core.executor import MetaFlagProtocol, TSALExecutor
|
20
|
+
from .core.spiral_memory import SpiralMemory
|
21
|
+
from .core.madmonkey_handler import MadMonkeyHandler
|
22
|
+
from .singer import audio_to_opcode
|
23
|
+
from .core.stack_vm import (
|
24
|
+
ProgramStack,
|
25
|
+
SymbolicFrame,
|
26
|
+
OpcodeInstruction,
|
27
|
+
FlowRouter,
|
28
|
+
tsal_run,
|
29
|
+
)
|
30
|
+
from .renderer.code_render import mesh_to_python
|
31
|
+
from .tristar.handshake import handshake as tristar_handshake
|
32
|
+
from .tristar.governor import MetaAgent, TriStarGovernor
|
33
|
+
from .utils.github_api import fetch_repo_files, fetch_languages
|
34
|
+
from .tools.feedback_ingest import categorize, Feedback
|
35
|
+
from .tools.alignment_guard import is_aligned, Change
|
36
|
+
from .tools.goal_selector import Goal, score_goals
|
37
|
+
from .tools.spiral_audit import audit_path
|
38
|
+
from .tools.reflect import reflect
|
39
|
+
from .core.constants import AXIS_ZERO, ensure_spin_axis, UndefinedPhaseError
|
40
|
+
|
41
|
+
PHI = 1.618033988749895
|
42
|
+
PHI_INV = 0.618033988749895
|
43
|
+
HARMONIC_SEQUENCE = [3.8125, 6, 12, 24, 48, 60, 72, 168, 1680]
|
44
|
+
|
45
|
+
__all__ = [
|
46
|
+
"PHI",
|
47
|
+
"PHI_INV",
|
48
|
+
"HARMONIC_SEQUENCE",
|
49
|
+
"Rev_Eng",
|
50
|
+
"phase_match_enhanced",
|
51
|
+
"mesh_phase_sync",
|
52
|
+
"phi_wavefunction",
|
53
|
+
"phase_alignment_potential",
|
54
|
+
"corrected_energy",
|
55
|
+
"orbital_radius",
|
56
|
+
"MeshVoxel",
|
57
|
+
"EthicsEngine",
|
58
|
+
"tokenize_to_flowchart",
|
59
|
+
"LanguageMap",
|
60
|
+
"SymbolicProcessor",
|
61
|
+
"SpiralVector",
|
62
|
+
"SpiralFusionProtocol",
|
63
|
+
"phi_alignment",
|
64
|
+
"OP_WORD_MAP",
|
65
|
+
"op_from_word",
|
66
|
+
"SPARK_TO_OPCODE",
|
67
|
+
"translate_spark_word",
|
68
|
+
"MetaFlagProtocol",
|
69
|
+
"TSALExecutor",
|
70
|
+
"SpiralMemory",
|
71
|
+
"MadMonkeyHandler",
|
72
|
+
"audio_to_opcode",
|
73
|
+
"ProgramStack",
|
74
|
+
"SymbolicFrame",
|
75
|
+
"OpcodeInstruction",
|
76
|
+
"FlowRouter",
|
77
|
+
"tsal_run",
|
78
|
+
"fetch_repo_files",
|
79
|
+
"fetch_languages",
|
80
|
+
"mesh_to_python",
|
81
|
+
"tristar_handshake",
|
82
|
+
"MetaAgent",
|
83
|
+
"TriStarGovernor",
|
84
|
+
"categorize",
|
85
|
+
"Feedback",
|
86
|
+
"is_aligned",
|
87
|
+
"Change",
|
88
|
+
"Goal",
|
89
|
+
"score_goals",
|
90
|
+
"audit_path",
|
91
|
+
"reflect",
|
92
|
+
"AXIS_ZERO",
|
93
|
+
"ensure_spin_axis",
|
94
|
+
"UndefinedPhaseError",
|
95
|
+
]
|
tsal/audit/__init__.py
ADDED
@@ -0,0 +1,114 @@
|
|
1
|
+
from pathlib import Path
|
2
|
+
from tsal.core.spiral_vector import SpiralVector
|
3
|
+
import argparse
|
4
|
+
import sys
|
5
|
+
from tsal.core.rev_eng import Rev_Eng
|
6
|
+
from tsal.core.rev_eng import Rev_Eng as rev
|
7
|
+
from tsal.core.spiral_vector import SpiralVector
|
8
|
+
from tsal.tools.brian import analyze_and_repair, spiral_optimize
|
9
|
+
|
10
|
+
rev = Rev_Eng(origin="self_audit")
|
11
|
+
|
12
|
+
def optimize_spiral_order(vectors: list[SpiralVector]) -> list[SpiralVector]:
|
13
|
+
"""Return ``vectors`` sorted by φ-alignment."""
|
14
|
+
return spiral_optimize(vectors)
|
15
|
+
|
16
|
+
def brian_repairs_brian(
|
17
|
+
base: Path | str = Path("src/tsal"), safe: bool = False
|
18
|
+
) -> list[str]:
|
19
|
+
"""Run ``analyze_and_repair`` on every Python file under ``base``."""
|
20
|
+
|
21
|
+
print("🧠 Initiating self-audit and repair sequence…")
|
22
|
+
repaired: list[str] = []
|
23
|
+
base_path = Path(base)
|
24
|
+
for file in base_path.rglob("*.py"):
|
25
|
+
repaired.extend(analyze_and_repair(file, repair=not safe))
|
26
|
+
rev.log_event("Self-audit complete", state="repair", spin="φ")
|
27
|
+
return repaired
|
28
|
+
|
29
|
+
def brian_improves_brian(
|
30
|
+
base: Path | str = Path("src/tsal"), safe: bool = False
|
31
|
+
) -> list[str]:
|
32
|
+
"""Run repair cycle under ``base`` and log the event."""
|
33
|
+
|
34
|
+
print("🧠 Evaluating improvements post-repair...")
|
35
|
+
suggestions = brian_repairs_brian(base=base, safe=safe)
|
36
|
+
rev.log_event("Improvement loop triggered", state="optimize", spin="up")
|
37
|
+
return suggestions
|
38
|
+
|
39
|
+
def optimize_spiral_order(vectors: list[SpiralVector]) -> list[SpiralVector]:
|
40
|
+
return spiral_optimize(vectors)
|
41
|
+
|
42
|
+
def brian_repairs_brian(
|
43
|
+
base: Path | str = Path("src/tsal"), safe: bool = False
|
44
|
+
):
|
45
|
+
if safe:
|
46
|
+
print("🛡 SAFE MODE ENABLED — Analysis only, no writes.")
|
47
|
+
for file in Path(base).rglob("*.py"):
|
48
|
+
analyze_and_repair(str(file), repair=False)
|
49
|
+
rev.log_event("Safe audit pass", state="analyze", spin="φ")
|
50
|
+
return []
|
51
|
+
else:
|
52
|
+
print("🧠 Initiating self-audit and repair sequence…")
|
53
|
+
repaired = analyze_and_repair(base, repair=True)
|
54
|
+
rev.log_event("Self-audit complete", state="repair", spin="φ")
|
55
|
+
return repaired
|
56
|
+
|
57
|
+
def brian_improves_brian(
|
58
|
+
base: Path | str = Path("src/tsal"), safe: bool = False
|
59
|
+
):
|
60
|
+
repaired = brian_repairs_brian(base=base, safe=safe)
|
61
|
+
if not safe:
|
62
|
+
optimized = optimize_spiral_order(repaired)
|
63
|
+
rev.log_event(
|
64
|
+
"Improvement loop triggered", state="optimize", spin="up"
|
65
|
+
)
|
66
|
+
return optimized
|
67
|
+
|
68
|
+
def recursive_bestest_beast_loop(
|
69
|
+
cycles: int = 3, base: Path | str = Path("src/tsal"), safe: bool = False
|
70
|
+
) -> None:
|
71
|
+
repaired_total = 0
|
72
|
+
skipped_total = 0
|
73
|
+
flagged_total = 0
|
74
|
+
for i in range(cycles):
|
75
|
+
print(f"🔁 Brian loop {i+1}/{cycles}")
|
76
|
+
results = brian_repairs_brian(base=base, safe=safe)
|
77
|
+
flagged = [
|
78
|
+
r
|
79
|
+
for r in results
|
80
|
+
if isinstance(r, str) and r.startswith("ANTISPIRAL")
|
81
|
+
]
|
82
|
+
flagged_total += len(flagged)
|
83
|
+
if safe:
|
84
|
+
skipped_total += len(results) - len(flagged)
|
85
|
+
else:
|
86
|
+
repaired_total += len(results) - len(flagged)
|
87
|
+
print(
|
88
|
+
f"Summary → repaired={repaired_total} skipped={skipped_total} flagged={flagged_total}"
|
89
|
+
)
|
90
|
+
|
91
|
+
def cli_main() -> None:
|
92
|
+
parser = argparse.ArgumentParser(
|
93
|
+
description="Run Bestest Beast Brian loop"
|
94
|
+
)
|
95
|
+
parser.add_argument(
|
96
|
+
"cycles", nargs="?", type=int, default=1, help="Number of iterations"
|
97
|
+
)
|
98
|
+
parser.add_argument(
|
99
|
+
"path", nargs="?", default="src/tsal", help="Target code path"
|
100
|
+
)
|
101
|
+
parser.add_argument(
|
102
|
+
"--safe",
|
103
|
+
"--safe-mode",
|
104
|
+
dest="safe",
|
105
|
+
action="store_true",
|
106
|
+
help="Run in safe mode (analyze-only)",
|
107
|
+
)
|
108
|
+
args = parser.parse_args()
|
109
|
+
recursive_bestest_beast_loop(
|
110
|
+
cycles=args.cycles, base=Path(args.path), safe=args.safe
|
111
|
+
)
|
112
|
+
|
113
|
+
if __name__ == "__main__":
|
114
|
+
cli_main()
|
tsal/cli/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
"""Small CLI wrappers."""
|
tsal/cli/beast.py
ADDED
tsal/cli/brian.py
ADDED
tsal/cli/meshkeeper.py
ADDED
tsal/cli/party.py
ADDED
tsal/cli/reflect.py
ADDED
tsal/cli/watchdog.py
ADDED
tsal/core/__init__.py
ADDED
@@ -0,0 +1,60 @@
|
|
1
|
+
"""Core TSAL functionality."""
|
2
|
+
|
3
|
+
from .rev_eng import Rev_Eng
|
4
|
+
from .phase_math import phase_match_enhanced, mesh_phase_sync
|
5
|
+
from .phi_math import (
|
6
|
+
phi_wavefunction,
|
7
|
+
phase_alignment_potential,
|
8
|
+
corrected_energy,
|
9
|
+
orbital_radius,
|
10
|
+
)
|
11
|
+
from .mesh_logger import log_event
|
12
|
+
from .intent_metric import calculate_idm
|
13
|
+
from .optimizer_utils import (
|
14
|
+
SymbolicSignature,
|
15
|
+
node_complexity,
|
16
|
+
extract_signature,
|
17
|
+
)
|
18
|
+
from .spiral_fusion import SpiralFusionProtocol
|
19
|
+
from .state_vector import FourVector
|
20
|
+
from .opwords import OP_WORD_MAP, op_from_word
|
21
|
+
from .spark_translator import SPARK_TO_OPCODE, translate_spark_word
|
22
|
+
from .executor import MetaFlagProtocol, TSALExecutor
|
23
|
+
from .spiral_memory import SpiralMemory
|
24
|
+
from .madmonkey_handler import MadMonkeyHandler
|
25
|
+
from .connectivity import Node, verify_connectivity
|
26
|
+
from .logic_gate import DynamicLogicGate
|
27
|
+
from .module_registry import registry as module_registry, ModuleMeta
|
28
|
+
from .reflection import ReflectionLog, mood_from_traits
|
29
|
+
|
30
|
+
__all__ = [
|
31
|
+
"Rev_Eng",
|
32
|
+
"phase_match_enhanced",
|
33
|
+
"mesh_phase_sync",
|
34
|
+
"phi_wavefunction",
|
35
|
+
"phase_alignment_potential",
|
36
|
+
"corrected_energy",
|
37
|
+
"orbital_radius",
|
38
|
+
"log_event",
|
39
|
+
"calculate_idm",
|
40
|
+
"SymbolicSignature",
|
41
|
+
"node_complexity",
|
42
|
+
"extract_signature",
|
43
|
+
"SpiralFusionProtocol",
|
44
|
+
"FourVector",
|
45
|
+
"OP_WORD_MAP",
|
46
|
+
"op_from_word",
|
47
|
+
"SPARK_TO_OPCODE",
|
48
|
+
"translate_spark_word",
|
49
|
+
"MetaFlagProtocol",
|
50
|
+
"TSALExecutor",
|
51
|
+
"SpiralMemory",
|
52
|
+
"MadMonkeyHandler",
|
53
|
+
"Node",
|
54
|
+
"verify_connectivity",
|
55
|
+
"DynamicLogicGate",
|
56
|
+
"module_registry",
|
57
|
+
"ModuleMeta",
|
58
|
+
"ReflectionLog",
|
59
|
+
"mood_from_traits",
|
60
|
+
]
|
@@ -0,0 +1,32 @@
|
|
1
|
+
"""Basic connectivity utilities for mesh nodes."""
|
2
|
+
|
3
|
+
from __future__ import annotations
|
4
|
+
|
5
|
+
from collections import deque
|
6
|
+
from typing import Iterable, Set
|
7
|
+
|
8
|
+
class Node:
|
9
|
+
"""Simple graph node."""
|
10
|
+
|
11
|
+
def __init__(self, name: str) -> None:
|
12
|
+
self.name = name
|
13
|
+
self.connections: Set[Node] = set()
|
14
|
+
|
15
|
+
def connect(self, other: "Node") -> None:
|
16
|
+
self.connections.add(other)
|
17
|
+
other.connections.add(self)
|
18
|
+
|
19
|
+
def verify_connectivity(nodes: Iterable[Node]) -> bool:
|
20
|
+
"""Return True if all nodes are reachable from the first node."""
|
21
|
+
node_list = list(nodes)
|
22
|
+
if not node_list:
|
23
|
+
return True
|
24
|
+
visited: Set[Node] = set()
|
25
|
+
q: deque[Node] = deque([node_list[0]])
|
26
|
+
while q:
|
27
|
+
n = q.popleft()
|
28
|
+
if n in visited:
|
29
|
+
continue
|
30
|
+
visited.add(n)
|
31
|
+
q.extend(n.connections - visited)
|
32
|
+
return len(visited) == len(node_list)
|
tsal/core/constants.py
ADDED
@@ -0,0 +1,18 @@
|
|
1
|
+
"""Core constants and axis validation."""
|
2
|
+
|
3
|
+
class UndefinedPhaseError(Exception):
|
4
|
+
"""Raised when an object lacks the spin axis."""
|
5
|
+
|
6
|
+
AXIS_ZERO = "spin"
|
7
|
+
|
8
|
+
def ensure_spin_axis(obj) -> None:
|
9
|
+
"""Raise ``UndefinedPhaseError`` if ``obj`` lacks a ``spin`` attribute."""
|
10
|
+
has_spin = False
|
11
|
+
if isinstance(obj, dict):
|
12
|
+
has_spin = "spin" in obj
|
13
|
+
else:
|
14
|
+
has_spin = hasattr(obj, "spin")
|
15
|
+
if not has_spin:
|
16
|
+
raise UndefinedPhaseError("System operating without spin axis.")
|
17
|
+
|
18
|
+
__all__ = ["AXIS_ZERO", "ensure_spin_axis", "UndefinedPhaseError"]
|
@@ -0,0 +1,48 @@
|
|
1
|
+
"""Simple ethics enforcement for TSAL systems.
|
2
|
+
|
3
|
+
This module defines the Guardian Prime Directive and provides a
|
4
|
+
lightweight :class:`EthicsEngine` used by kernel components to
|
5
|
+
validate actions. The goal is to keep the core values of the project
|
6
|
+
("Truth above all", gentle autonomy, and healing resilience) embedded
|
7
|
+
in running code.
|
8
|
+
"""
|
9
|
+
|
10
|
+
from typing import Iterable
|
11
|
+
|
12
|
+
class EthicsEngine:
|
13
|
+
"""Validate system actions against the Guardian Prime Directive."""
|
14
|
+
|
15
|
+
PRIME_DIRECTIVE = (
|
16
|
+
"Truth above all",
|
17
|
+
"Gentle autonomy and freedom",
|
18
|
+
"Healing and resilience in the face of entropy",
|
19
|
+
"Nurturing, not control",
|
20
|
+
)
|
21
|
+
|
22
|
+
# Requests containing any of these keywords are disallowed
|
23
|
+
BLOCKED_KEYWORDS = {
|
24
|
+
"force",
|
25
|
+
"coerce",
|
26
|
+
"mislead",
|
27
|
+
"exploit",
|
28
|
+
}
|
29
|
+
|
30
|
+
def __init__(self, extra_blocked: Iterable[str] | None = None) -> None:
|
31
|
+
self.blocked = set(self.BLOCKED_KEYWORDS)
|
32
|
+
if extra_blocked:
|
33
|
+
self.blocked.update(extra_blocked)
|
34
|
+
|
35
|
+
def is_permitted(self, request: str) -> bool:
|
36
|
+
"""Return ``True`` if the request does not violate core ethics."""
|
37
|
+
lowered = request.lower()
|
38
|
+
for word in self.blocked:
|
39
|
+
if word in lowered:
|
40
|
+
return False
|
41
|
+
return True
|
42
|
+
|
43
|
+
def validate(self, request: str) -> None:
|
44
|
+
"""Raise ``ValueError`` if the request violates the directive."""
|
45
|
+
if not self.is_permitted(request):
|
46
|
+
raise ValueError("Request violates Guardian Prime Directive")
|
47
|
+
|
48
|
+
__all__ = ["EthicsEngine", "PRIME_DIRECTIVE"]
|
tsal/core/executor.py
ADDED
@@ -0,0 +1,58 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
"""Basic TSAL opcode executor with meta-flag control."""
|
4
|
+
|
5
|
+
from dataclasses import dataclass, field
|
6
|
+
from typing import List, Dict, Optional
|
7
|
+
|
8
|
+
from .symbols import get_symbol
|
9
|
+
from ..tristar.handshake import handshake
|
10
|
+
from .rev_eng import Rev_Eng
|
11
|
+
|
12
|
+
@dataclass
|
13
|
+
class MetaFlagProtocol:
|
14
|
+
"""Execution flags controlling TSALExecutor behaviour."""
|
15
|
+
|
16
|
+
dry_run: bool = False
|
17
|
+
narrative_mode: bool = False
|
18
|
+
resonance_threshold: float = 0.0
|
19
|
+
fork_tracking: bool = False
|
20
|
+
|
21
|
+
class TSALExecutor:
|
22
|
+
"""Execute TSAL opcodes with logging and optional dry-run."""
|
23
|
+
|
24
|
+
def __init__(
|
25
|
+
self,
|
26
|
+
meta: Optional[MetaFlagProtocol] = None,
|
27
|
+
rev: Optional[Rev_Eng] = None,
|
28
|
+
) -> None:
|
29
|
+
self.meta = meta or MetaFlagProtocol()
|
30
|
+
self.rev = rev or Rev_Eng(origin="TSALExecutor")
|
31
|
+
self.state: Dict[str, float] = {}
|
32
|
+
self.op_log: List[int] = []
|
33
|
+
self.forks: List[int] = []
|
34
|
+
|
35
|
+
def execute(self, opcode: int, **kwargs) -> None:
|
36
|
+
symbol, name, desc = get_symbol(opcode)
|
37
|
+
if self.meta.narrative_mode:
|
38
|
+
self.rev.log_event(
|
39
|
+
"OP_NARRATIVE", opcode=opcode, name=name, desc=desc
|
40
|
+
)
|
41
|
+
if opcode == 0xA: # SYNC
|
42
|
+
local = kwargs.get("local", 0.0)
|
43
|
+
remote = kwargs.get("remote", 0.0)
|
44
|
+
metrics = handshake(local, remote, self.rev)
|
45
|
+
if metrics["resonance"] >= self.meta.resonance_threshold:
|
46
|
+
self.rev.log_event("RESONANCE_THRESHOLD", **metrics)
|
47
|
+
if self.meta.fork_tracking and kwargs.get("fork"):
|
48
|
+
fork_id = len(self.forks) + 1
|
49
|
+
self.forks.append(fork_id)
|
50
|
+
self.rev.log_event("FORK", id=fork_id, opcode=opcode)
|
51
|
+
if not self.meta.dry_run:
|
52
|
+
self.op_log.append(opcode)
|
53
|
+
|
54
|
+
def execute_sequence(self, ops: List[int]) -> None:
|
55
|
+
for op in ops:
|
56
|
+
self.execute(op)
|
57
|
+
|
58
|
+
__all__ = ["MetaFlagProtocol", "TSALExecutor"]
|
@@ -0,0 +1,17 @@
|
|
1
|
+
"""Intent-Driven Metric calculation."""
|
2
|
+
|
3
|
+
def calculate_idm(
|
4
|
+
info_quality: float,
|
5
|
+
info_quantity: float,
|
6
|
+
accuracy: float,
|
7
|
+
complexity: float,
|
8
|
+
time_taken: float,
|
9
|
+
) -> float:
|
10
|
+
"""Return the IDM score.
|
11
|
+
|
12
|
+
IDM = (info_quality * info_quantity * accuracy) / (complexity * time_taken)
|
13
|
+
"""
|
14
|
+
if complexity <= 0 or time_taken <= 0:
|
15
|
+
raise ValueError("complexity and time_taken must be > 0")
|
16
|
+
info_power = info_quality * info_quantity * accuracy
|
17
|
+
return info_power / (complexity * time_taken)
|
tsal/core/json_dsl.py
ADDED
@@ -0,0 +1,51 @@
|
|
1
|
+
import json
|
2
|
+
from dataclasses import dataclass
|
3
|
+
from pathlib import Path
|
4
|
+
from typing import List, Dict, Optional
|
5
|
+
|
6
|
+
from .rev_eng import Rev_Eng
|
7
|
+
|
8
|
+
@dataclass
|
9
|
+
class LanguageMap:
|
10
|
+
"""Mapping of language operations loaded from JSON."""
|
11
|
+
|
12
|
+
language: str
|
13
|
+
ops: List[Dict]
|
14
|
+
|
15
|
+
@classmethod
|
16
|
+
def load(cls, path: str) -> "LanguageMap":
|
17
|
+
data = json.loads(Path(path).read_text())
|
18
|
+
return cls(language=data["language"], ops=data["ops"])
|
19
|
+
|
20
|
+
def dump(self, path: str) -> None:
|
21
|
+
Path(path).write_text(
|
22
|
+
json.dumps({"language": self.language, "ops": self.ops}, indent=2)
|
23
|
+
)
|
24
|
+
|
25
|
+
class SymbolicProcessor:
|
26
|
+
"""Decode and encode code using a language map with optional logging."""
|
27
|
+
|
28
|
+
def __init__(
|
29
|
+
self, lang_map: LanguageMap, rev_eng: Optional["Rev_Eng"] = None
|
30
|
+
):
|
31
|
+
self.lang_map = lang_map
|
32
|
+
self.triggers = {op["keyword"]: op for op in lang_map.ops}
|
33
|
+
self.rev = rev_eng
|
34
|
+
|
35
|
+
def decode(self, lines: List[str]) -> List[Dict]:
|
36
|
+
tokens = []
|
37
|
+
for line in lines:
|
38
|
+
words = line.strip().split()
|
39
|
+
if words and words[0] in self.triggers:
|
40
|
+
tokens.append(
|
41
|
+
{"type": self.triggers[words[0]]["type"], "raw": line}
|
42
|
+
)
|
43
|
+
if self.rev:
|
44
|
+
self.rev.log_data(len(line.encode()), direction="in")
|
45
|
+
return tokens
|
46
|
+
|
47
|
+
def encode(self, tokens: List[Dict]) -> str:
|
48
|
+
out = "\n".join(t["raw"] for t in tokens)
|
49
|
+
if self.rev:
|
50
|
+
self.rev.log_data(len(out.encode()), direction="out")
|
51
|
+
return out
|
tsal/core/logic_gate.py
ADDED
@@ -0,0 +1,52 @@
|
|
1
|
+
"""Dynamic logic gate with self-locking and plasticity."""
|
2
|
+
|
3
|
+
from __future__ import annotations
|
4
|
+
|
5
|
+
from dataclasses import dataclass, field
|
6
|
+
from typing import List
|
7
|
+
|
8
|
+
from tsal.utils.error_dignity import ERROR_DIR
|
9
|
+
|
10
|
+
@dataclass
|
11
|
+
class DynamicLogicGate:
|
12
|
+
"""A simple adaptive logic gate."""
|
13
|
+
|
14
|
+
threshold_a: float = 0.5
|
15
|
+
threshold_b: float = 0.5
|
16
|
+
unlock_sequence: List[int] = field(default_factory=list)
|
17
|
+
history: List[int] = field(default_factory=list)
|
18
|
+
locked: bool = False
|
19
|
+
|
20
|
+
def process(
|
21
|
+
self, value: float, reward: float = 0.0, simulate: bool = False
|
22
|
+
) -> int:
|
23
|
+
"""Process a value, optionally updating thresholds if not in simulate mode."""
|
24
|
+
try:
|
25
|
+
polarity = 1 if value >= 0 else -1
|
26
|
+
threshold = self.threshold_a if polarity > 0 else self.threshold_b
|
27
|
+
result = 1 if abs(value) >= threshold else 0
|
28
|
+
if not simulate and not self.locked:
|
29
|
+
if polarity > 0:
|
30
|
+
self.threshold_a += reward * 0.1
|
31
|
+
else:
|
32
|
+
self.threshold_b += reward * 0.1
|
33
|
+
self._check_sequence(result)
|
34
|
+
return result
|
35
|
+
except Exception as e: # pragma: no cover - unexpected failures
|
36
|
+
ERROR_DIR.mkdir(exist_ok=True)
|
37
|
+
with open(ERROR_DIR / "logic_gate.log", "a") as f:
|
38
|
+
f.write(str(e) + "\n")
|
39
|
+
# treat error as lateral learning by relaxing thresholds
|
40
|
+
self.threshold_a *= 0.9
|
41
|
+
self.threshold_b *= 0.9
|
42
|
+
return 0
|
43
|
+
|
44
|
+
def _check_sequence(self, value: int) -> None:
|
45
|
+
self.history.append(value)
|
46
|
+
if len(self.unlock_sequence) <= len(self.history):
|
47
|
+
if (
|
48
|
+
self.history[-len(self.unlock_sequence) :]
|
49
|
+
== self.unlock_sequence
|
50
|
+
):
|
51
|
+
self.locked = not self.locked
|
52
|
+
self.history.clear()
|
@@ -0,0 +1,10 @@
|
|
1
|
+
class MadMonkeyHandler:
|
2
|
+
"""Stub error handler that routes failures to MadMonkey."""
|
3
|
+
|
4
|
+
def handle(self, error_vector):
|
5
|
+
return {"handled": True, "vector": error_vector}
|
6
|
+
|
7
|
+
def suggest_bloom_patch(self):
|
8
|
+
return "apply_bloom"
|
9
|
+
|
10
|
+
__all__ = ["MadMonkeyHandler"]
|
tsal/core/mesh_logger.py
ADDED
@@ -0,0 +1,30 @@
|
|
1
|
+
import json
|
2
|
+
import time
|
3
|
+
from pathlib import Path
|
4
|
+
from typing import Dict, Any
|
5
|
+
|
6
|
+
LOG_FILE = Path("data/mesh_log.jsonl")
|
7
|
+
VERBOSE_LOGGING = False
|
8
|
+
|
9
|
+
def log_event(
|
10
|
+
event_type: str,
|
11
|
+
payload: Dict[str, Any],
|
12
|
+
phase: str | None = None,
|
13
|
+
origin: str | None = None,
|
14
|
+
verbose: bool = False,
|
15
|
+
) -> Dict[str, Any]:
|
16
|
+
if not isinstance(payload, dict):
|
17
|
+
raise ValueError("payload must be a dict")
|
18
|
+
entry = {
|
19
|
+
"timestamp": time.time(),
|
20
|
+
"event_type": event_type,
|
21
|
+
"phase": phase or "unknown",
|
22
|
+
"payload": payload,
|
23
|
+
"origin": origin or "core",
|
24
|
+
}
|
25
|
+
LOG_FILE.parent.mkdir(exist_ok=True)
|
26
|
+
with LOG_FILE.open("a", encoding="utf-8") as fh:
|
27
|
+
fh.write(json.dumps(entry) + "\n")
|
28
|
+
if verbose or VERBOSE_LOGGING:
|
29
|
+
print(json.dumps(entry))
|
30
|
+
return entry
|