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.
Files changed (89) hide show
  1. crawler/__init__.py +0 -0
  2. crawler/madmonkey_crawler.py +15 -0
  3. madmonkey/__init__.py +0 -0
  4. madmonkey/intake.py +9 -0
  5. tri_star_symbolic_assembly_lang-0.1.0.dist-info/METADATA +423 -0
  6. tri_star_symbolic_assembly_lang-0.1.0.dist-info/RECORD +89 -0
  7. tri_star_symbolic_assembly_lang-0.1.0.dist-info/WHEEL +5 -0
  8. tri_star_symbolic_assembly_lang-0.1.0.dist-info/entry_points.txt +11 -0
  9. tri_star_symbolic_assembly_lang-0.1.0.dist-info/licenses/LICENSE +63 -0
  10. tri_star_symbolic_assembly_lang-0.1.0.dist-info/top_level.txt +3 -0
  11. tsal/__init__.py +95 -0
  12. tsal/audit/__init__.py +11 -0
  13. tsal/audit/brian_self_audit.py +114 -0
  14. tsal/cli/__init__.py +1 -0
  15. tsal/cli/beast.py +4 -0
  16. tsal/cli/brian.py +4 -0
  17. tsal/cli/brian_optimize.py +6 -0
  18. tsal/cli/meshkeeper.py +4 -0
  19. tsal/cli/party.py +4 -0
  20. tsal/cli/reflect.py +4 -0
  21. tsal/cli/watchdog.py +4 -0
  22. tsal/core/__init__.py +60 -0
  23. tsal/core/connectivity.py +32 -0
  24. tsal/core/constants.py +18 -0
  25. tsal/core/ethics_engine.py +48 -0
  26. tsal/core/executor.py +58 -0
  27. tsal/core/intent_metric.py +17 -0
  28. tsal/core/json_dsl.py +51 -0
  29. tsal/core/logic_gate.py +52 -0
  30. tsal/core/madmonkey_handler.py +10 -0
  31. tsal/core/mesh_logger.py +30 -0
  32. tsal/core/module_registry.py +108 -0
  33. tsal/core/optimizer_utils.py +78 -0
  34. tsal/core/opwords.py +126 -0
  35. tsal/core/phase_math.py +256 -0
  36. tsal/core/phi_math.py +44 -0
  37. tsal/core/reflection.py +104 -0
  38. tsal/core/rev_eng.py +185 -0
  39. tsal/core/spark_translator.py +57 -0
  40. tsal/core/spiral_fusion.py +45 -0
  41. tsal/core/spiral_memory.py +22 -0
  42. tsal/core/spiral_vector.py +39 -0
  43. tsal/core/stack_vm.py +49 -0
  44. tsal/core/state_vector.py +38 -0
  45. tsal/core/symbols.py +70 -0
  46. tsal/core/tokenize_flowchart.py +24 -0
  47. tsal/core/tsal_executor.py +533 -0
  48. tsal/core/voxel.py +16 -0
  49. tsal/renderer/__init__.py +0 -0
  50. tsal/renderer/code_render.py +13 -0
  51. tsal/rl/__init__.py +0 -0
  52. tsal/rl/madmonkey.py +56 -0
  53. tsal/schemas/__init__.py +1 -0
  54. tsal/schemas/python.json +13 -0
  55. tsal/singer/__init__.py +13 -0
  56. tsal/tools/__init__.py +43 -0
  57. tsal/tools/aletheia_checker.py +54 -0
  58. tsal/tools/alignment_guard.py +20 -0
  59. tsal/tools/archetype_fetcher.py +44 -0
  60. tsal/tools/brian/__init__.py +5 -0
  61. tsal/tools/brian/optimizer.py +205 -0
  62. tsal/tools/codec.py +31 -0
  63. tsal/tools/feedback_ingest.py +25 -0
  64. tsal/tools/goal_selector.py +26 -0
  65. tsal/tools/issue_agent.py +67 -0
  66. tsal/tools/kintsugi/__init__.py +1 -0
  67. tsal/tools/kintsugi/kintsugi.py +15 -0
  68. tsal/tools/meshkeeper.py +81 -0
  69. tsal/tools/module_draft.py +54 -0
  70. tsal/tools/party_tricks.py +128 -0
  71. tsal/tools/reflect.py +43 -0
  72. tsal/tools/spiral_audit.py +68 -0
  73. tsal/tools/state_tracker.py +66 -0
  74. tsal/tools/watchdog.py +40 -0
  75. tsal/tristar/__init__.py +4 -0
  76. tsal/tristar/governor.py +56 -0
  77. tsal/tristar/handshake.py +31 -0
  78. tsal/utils/__init__.py +26 -0
  79. tsal/utils/error_dignity.py +20 -0
  80. tsal/utils/fuzzy_spellcheck.py +7 -0
  81. tsal/utils/github_api.py +82 -0
  82. tsal/utils/grammar_db.py +155 -0
  83. tsal/utils/groundnews_api.py +9 -0
  84. tsal/utils/humour_db.py +75 -0
  85. tsal/utils/intent_metrics.py +44 -0
  86. tsal/utils/language_db.py +55 -0
  87. tsal/utils/octopus_api.py +46 -0
  88. tsal/utils/system_status.py +34 -0
  89. tsal/utils/wikipedia_api.py +46 -0
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+
3
+ """Simple timestamped reflection log with mood adaptation."""
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import List, Optional
7
+ from pathlib import Path
8
+ import hashlib
9
+ import json
10
+ import time
11
+
12
+ SURFACE_TAGS = {"spiral_flip", "observer_effect", "notable", "humor"}
13
+
14
+ MOOD_FROM_TRAIT = {
15
+ "Joker": "playful",
16
+ "Trickster": "sly",
17
+ "Scientist": "curious",
18
+ "Schrodinger": "paradox",
19
+ "Teacher": "helpful",
20
+ }
21
+
22
+
23
+ def mood_from_traits(traits: List[str]) -> str:
24
+ for t in traits:
25
+ if t in MOOD_FROM_TRAIT:
26
+ return MOOD_FROM_TRAIT[t]
27
+ return "neutral"
28
+
29
+
30
+ @dataclass
31
+ class ReflectionEntry:
32
+ timestamp: float
33
+ message: str
34
+ tags: List[str]
35
+ mood: str = "neutral"
36
+
37
+
38
+ @dataclass
39
+ class ReflectionLog:
40
+ pace: float = 0.0
41
+ rate: float = 0.0
42
+ state: str = ""
43
+ spin: str = ""
44
+ observer: Optional[str] = None
45
+ entries: List[ReflectionEntry] = field(default_factory=list)
46
+
47
+ def compute_hash(self) -> str:
48
+ """Return short fingerprint from pace, rate, state and spin."""
49
+ data = f"{self.pace}:{self.rate}:{self.state}:{self.spin}"
50
+ return hashlib.sha1(data.encode("utf-8")).hexdigest()[:8]
51
+
52
+ @property
53
+ def spiral_hash(self) -> str:
54
+ return self.compute_hash()
55
+
56
+ def dest_path(self, base: Path, seeds: List[str]) -> Path:
57
+ """Determine file path for this log."""
58
+ path = base
59
+ if self.observer:
60
+ path = path / self.observer
61
+ name = seeds[0] if len(seeds) == 1 else self.spiral_hash
62
+ path.mkdir(parents=True, exist_ok=True)
63
+ return path / f"{name}.jsonl"
64
+
65
+ def flush(self, base: Path, seeds: List[str]) -> Path:
66
+ """Write log entries to disk and clear memory."""
67
+ path = self.dest_path(base, seeds)
68
+ with path.open("a", encoding="utf-8") as fh:
69
+ for e in self.entries:
70
+ fh.write(json.dumps(e.__dict__) + "\n")
71
+ self.entries.clear()
72
+ return path
73
+
74
+ def log(self, message: str, tags: List[str] | None = None, mood: str = "neutral") -> None:
75
+ self.entries.append(
76
+ ReflectionEntry(time.time(), message, tags or [], mood)
77
+ )
78
+
79
+ def surface_entries(self) -> List[ReflectionEntry]:
80
+ return [e for e in self.entries if any(t in SURFACE_TAGS for t in e.tags)]
81
+
82
+ def to_markdown(self) -> str:
83
+ """Return entries formatted as markdown bullet list."""
84
+ lines = []
85
+ for e in self.entries:
86
+ ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e.timestamp))
87
+ lines.append(f"- {ts} [{e.mood}] {e.message}")
88
+ return "\n".join(lines)
89
+
90
+ def emit_mesh(self) -> None:
91
+ """Send entries to mesh_logger."""
92
+ from . import mesh_logger
93
+
94
+ for e in self.entries:
95
+ mesh_logger.log_event(
96
+ "REFLECTION",
97
+ {
98
+ "message": e.message,
99
+ "mood": e.mood,
100
+ "tags": e.tags,
101
+ },
102
+ origin="ReflectionLog",
103
+ )
104
+
tsal/core/rev_eng.py ADDED
@@ -0,0 +1,185 @@
1
+ import os
2
+ import time
3
+ import uuid
4
+ from collections import defaultdict
5
+ from typing import Optional, Dict, List, Any
6
+
7
+ from .mesh_logger import log_event
8
+ from .voxel import MeshVoxel
9
+ from .constants import ensure_spin_axis
10
+
11
+ class Rev_Eng:
12
+ """
13
+ Reverse-Engineer (Rev_Eng): System-wide tracker and cataloguer for lineage, state, IO spin, and mesh context.
14
+ """
15
+
16
+ def __init__(self, origin: str = None, session_id: str = None):
17
+ self.origin = origin or "Root"
18
+ self.session_id = session_id or str(uuid.uuid4())
19
+ self.lineage = [] # List of ancestor names/IDs
20
+ self.events = [] # Log of (timestamp, action, details)
21
+ self.state = {} # Arbitrary live state storage
22
+ self.data_stats = { # Real-time stats for IO/data
23
+ "total_bytes": 0,
24
+ "chunk_count": 0,
25
+ "last_rate": 0.0, # bytes/sec
26
+ "last_update": time.time(),
27
+ }
28
+ self.rate_log = [] # (timestamp, bytes, rate) tuples
29
+ self.spin_log = [] # (timestamp, spin_dir, I/O, updown)
30
+ self.voxel_log: List[Dict[str, Any]] = (
31
+ []
32
+ ) # pace/rate/state/spin snapshots
33
+ self.mesh_coords = (
34
+ {}
35
+ ) # e.g., {x:..., y:..., z:..., vx:..., vy:..., vz:..., phase:..., mesh:...}
36
+ self.identity = {} # Who/What/Why/When/Where details
37
+
38
+ # === LINEAGE TRACKING ===
39
+ def add_lineage(self, name: str):
40
+ self.lineage.append(name)
41
+
42
+ def get_lineage(self) -> List[str]:
43
+ return list(self.lineage)
44
+
45
+ # === DATA FLOW TRACKING ===
46
+ def log_data(self, n_bytes: int, direction: str, updown: str = None):
47
+ now = time.time()
48
+ dt = now - self.data_stats["last_update"]
49
+ self.data_stats["total_bytes"] += n_bytes
50
+ self.data_stats["chunk_count"] += 1
51
+ rate = n_bytes / dt if dt > 0 else 0.0
52
+ self.data_stats["last_rate"] = rate
53
+ self.data_stats["last_update"] = now
54
+ self.rate_log.append((now, n_bytes, rate))
55
+ self.log_spin(direction=direction, updown=updown, I_O=direction)
56
+ voxel = MeshVoxel(
57
+ pace=self.data_stats["chunk_count"],
58
+ rate=rate,
59
+ state=direction,
60
+ spin=updown or direction,
61
+ )
62
+ ensure_spin_axis(voxel)
63
+ self.voxel_log.append(voxel.as_dict())
64
+ log_event(
65
+ "DATA",
66
+ voxel.as_dict(),
67
+ phase="io",
68
+ origin=self.origin,
69
+ )
70
+
71
+ def log_grammar(self, language: str, rule: str) -> None:
72
+ """Stub for grammar usage logging; to be expanded for overlay/voxel tracking."""
73
+ pass
74
+
75
+ def log_humour(self, context: str, joke: str) -> None:
76
+ """Stub for humour event logging; to be expanded for overlay/voxel tracking."""
77
+ pass
78
+
79
+ def log_spin(self, direction: str, updown: str = None, I_O: str = None):
80
+ # direction: 'in', 'out', 'clockwise', 'counter', etc.
81
+ now = time.time()
82
+ self.spin_log.append((now, direction, I_O, updown))
83
+
84
+ def spin_collisions(self) -> Dict[str, int]:
85
+ """Return XOR/NAND/AND counts over sequential spin directions."""
86
+ counts = {"xor": 0, "nand": 0, "and": 0}
87
+ if len(self.spin_log) < 2:
88
+ return counts
89
+
90
+ def as_bool(v: Any) -> bool:
91
+ if isinstance(v, str):
92
+ return v.lower() in {"up", "in", "1", "true"}
93
+ return bool(v)
94
+
95
+ for (_, a, _, _), (_, b, _, _) in zip(
96
+ self.spin_log, self.spin_log[1:]
97
+ ):
98
+ ba = as_bool(a)
99
+ bb = as_bool(b)
100
+ counts["xor"] += ba ^ bb
101
+ counts["and"] += ba and bb
102
+ counts["nand"] += not (ba and bb)
103
+ return counts
104
+
105
+ # === STATE/CONTEXT TRACKING ===
106
+ def set_state(self, **kwargs):
107
+ self.state.update(kwargs)
108
+
109
+ def log_event(self, action: str, **details):
110
+ now = time.time()
111
+ self.events.append((now, action, details))
112
+
113
+ def update_mesh_coords(self, **coords):
114
+ self.mesh_coords.update(coords)
115
+
116
+ def set_identity(
117
+ self,
118
+ who: str,
119
+ what: str,
120
+ where: str,
121
+ when: Optional[str] = None,
122
+ why: str = None,
123
+ ):
124
+ self.identity = {
125
+ "who": who,
126
+ "what": what,
127
+ "where": where,
128
+ "when": when or time.strftime("%Y-%m-%d %H:%M:%S"),
129
+ "why": why,
130
+ }
131
+
132
+ # === UNIVERSAL REPORTING / EXPORT ===
133
+ def summary(self) -> Dict[str, Any]:
134
+ return {
135
+ "origin": self.origin,
136
+ "session_id": self.session_id,
137
+ "lineage": self.lineage,
138
+ "data_stats": self.data_stats,
139
+ "recent_rate": self.data_stats["last_rate"],
140
+ "rate_log": self.rate_log[-5:],
141
+ "spin_log": self.spin_log[-5:],
142
+ "voxels": self.voxel_log[-5:],
143
+ "collisions": self.spin_collisions(),
144
+ "state": self.state,
145
+ "mesh_coords": self.mesh_coords,
146
+ "identity": self.identity,
147
+ "event_count": len(self.events),
148
+ }
149
+
150
+ def print_summary(self):
151
+ import pprint
152
+
153
+ pprint.pprint(self.summary())
154
+
155
+ # === EXTENSIBLE: Custom Hooks for TSAL/mesh logging, e.g., phase, spiral, error dignity ===
156
+ def log_tsal_phase(
157
+ self, phase: str, symbol: str, context: Optional[str] = None
158
+ ):
159
+ self.log_event(
160
+ "TSAL_PHASE", phase=phase, symbol=symbol, context=context
161
+ )
162
+
163
+ def log_error(
164
+ self, err: str, location: str = None, recoverable: bool = True
165
+ ):
166
+ self.log_event(
167
+ "ERROR", error=err, location=location, recoverable=recoverable
168
+ )
169
+ # Optional: Spiral/bloom logic could re-inject error into mesh for "mad monkey" learning
170
+
171
+ # Example Usage:
172
+ if __name__ == "__main__":
173
+ rev = Rev_Eng(origin="Genesis_Spiral")
174
+ rev.add_lineage("Proto_Node_0")
175
+ rev.set_identity(
176
+ "RevEngKernel", "Reverse-Engineer", "Mesh_Center", why="System Audit"
177
+ )
178
+ rev.log_data(4096, direction="in", updown="up")
179
+ rev.log_data(2048, direction="out", updown="down")
180
+ rev.update_mesh_coords(
181
+ x=1, y=2, z=3, vx=0.1, vy=0.2, vz=0.3, phase="spiral", mesh="central"
182
+ )
183
+ rev.log_tsal_phase("ALIGN", "6", context="Startup Alignment")
184
+ rev.log_error("Checksum mismatch", location="sector_17")
185
+ rev.print_summary()
@@ -0,0 +1,57 @@
1
+ from tsal.core.symbols import TSALOp
2
+
3
+ SPARK_TO_OPCODE = {
4
+ "ignite": TSALOp.INIT,
5
+ "start": TSALOp.INIT,
6
+ "boot": TSALOp.INIT,
7
+ "connect": TSALOp.MESH,
8
+ "join": TSALOp.MESH,
9
+ "link": TSALOp.MESH,
10
+ "align": TSALOp.PHI,
11
+ "optimize": TSALOp.PHI,
12
+ "flow": TSALOp.PHI,
13
+ "turn": TSALOp.ROT,
14
+ "rotate": TSALOp.ROT,
15
+ "flip": TSALOp.ROT,
16
+ "define": TSALOp.BOUND,
17
+ "limit": TSALOp.BOUND,
18
+ "constrain": TSALOp.BOUND,
19
+ "move": TSALOp.FLOW,
20
+ "push": TSALOp.FLOW,
21
+ "carry": TSALOp.FLOW,
22
+ "seek": TSALOp.SEEK,
23
+ "ask": TSALOp.SEEK,
24
+ "query": TSALOp.SEEK,
25
+ "scan": TSALOp.SEEK,
26
+ "evolve": TSALOp.SPIRAL,
27
+ "spiral": TSALOp.SPIRAL,
28
+ "climb": TSALOp.SPIRAL,
29
+ "loop": TSALOp.CYCLE,
30
+ "retry": TSALOp.CYCLE,
31
+ "cycle": TSALOp.CYCLE,
32
+ "create": TSALOp.FORGE,
33
+ "forge": TSALOp.FORGE,
34
+ "synthesize": TSALOp.FORGE,
35
+ "match": TSALOp.SYNC,
36
+ "sync": TSALOp.SYNC,
37
+ "balance": TSALOp.SYNC,
38
+ "mask": TSALOp.MASK,
39
+ "hide": TSALOp.MASK,
40
+ "invert": TSALOp.MASK,
41
+ "shift": TSALOp.MASK,
42
+ "lock": TSALOp.CRYST,
43
+ "preserve": TSALOp.CRYST,
44
+ "store": TSALOp.CRYST,
45
+ "analyze": TSALOp.SPEC,
46
+ "color": TSALOp.SPEC,
47
+ "spectrum": TSALOp.SPEC,
48
+ "repair": TSALOp.BLOOM,
49
+ "heal": TSALOp.BLOOM,
50
+ "transform": TSALOp.BLOOM,
51
+ "save": TSALOp.SAVE,
52
+ "remember": TSALOp.SAVE,
53
+ "write": TSALOp.SAVE,
54
+ }
55
+
56
+ def translate_spark_word(word: str):
57
+ return SPARK_TO_OPCODE.get(word.lower())
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ """SPIRAL_FUSION_PROTOCOL utilities."""
4
+
5
+ from dataclasses import dataclass, field
6
+ import hashlib
7
+ from typing import List
8
+
9
+ from .spiral_vector import SpiralVector, phi_alignment
10
+
11
+ @dataclass
12
+ class SpiralFusionProtocol:
13
+ """Fuse multiple :class:`SpiralVector` objects into one path."""
14
+
15
+ name: str
16
+ vectors: List[SpiralVector] = field(default_factory=list)
17
+ phi_signature: str = ""
18
+
19
+ def __post_init__(self) -> None:
20
+ self.update_signature()
21
+
22
+ def update_signature(self) -> None:
23
+ if not self.vectors:
24
+ self.phi_signature = "φ^0.000_empty"
25
+ return
26
+ total_complexity = sum(v.complexity for v in self.vectors)
27
+ total_coherence = sum(v.coherence for v in self.vectors)
28
+ phi_factor = phi_alignment(total_complexity, total_coherence)
29
+ content_hash = hashlib.sha256(
30
+ "".join(v.phi_signature for v in self.vectors).encode()
31
+ ).hexdigest()
32
+ self.phi_signature = f"φ^{phi_factor:.3f}_{content_hash[:8]}"
33
+
34
+ def fuse(self, vector: SpiralVector) -> None:
35
+ self.vectors.append(vector)
36
+ self.update_signature()
37
+
38
+ def unified_vector(self) -> SpiralVector:
39
+ if not self.vectors:
40
+ return SpiralVector(self.name, 0.0, 0.0, "fused")
41
+ complexity = sum(v.complexity for v in self.vectors) / len(
42
+ self.vectors
43
+ )
44
+ coherence = sum(v.coherence for v in self.vectors) / len(self.vectors)
45
+ return SpiralVector(self.name, complexity, coherence, "fused")
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Dict, List
5
+
6
+ @dataclass
7
+ class SpiralMemory:
8
+ entries: List[Dict[str, Any]] = field(default_factory=list)
9
+ crystallized: bool = False
10
+
11
+ def log_vector(self, vector: Dict[str, Any]) -> None:
12
+ if self.crystallized:
13
+ return
14
+ self.entries.append(vector)
15
+
16
+ def crystallize(self) -> None:
17
+ self.crystallized = True
18
+
19
+ def replay(self) -> List[Dict[str, Any]]:
20
+ return list(self.entries)
21
+
22
+ __all__ = ["SpiralMemory"]
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ """SpiralVector logic derived from legacy session logs."""
4
+
5
+ from dataclasses import dataclass
6
+ import hashlib
7
+
8
+ from .symbols import PHI, PHI_INV
9
+
10
+ def phi_alignment(complexity: float, coherence: float) -> float:
11
+ """Return φ-alignment score for given complexity and coherence."""
12
+ return (complexity * PHI_INV + coherence * PHI) / (PHI + PHI_INV)
13
+
14
+ @dataclass
15
+ class SpiralVector:
16
+ """Representation of a spiral code metric vector."""
17
+
18
+ name: str
19
+ complexity: float
20
+ coherence: float
21
+ intent: str
22
+
23
+ phi_signature: str = ""
24
+
25
+ def __post_init__(self) -> None:
26
+ self.phi_signature = self._calculate_phi_signature()
27
+
28
+ def _calculate_phi_signature(self) -> str:
29
+ content_hash = hashlib.sha256(
30
+ f"{self.name}{self.complexity}{self.coherence}".encode()
31
+ ).hexdigest()
32
+ phi_factor = (self.complexity * self.coherence) * PHI_INV
33
+ return f"φ^{phi_factor:.3f}_{content_hash[:8]}"
34
+
35
+ def alignment(self) -> float:
36
+ """Return the φ-alignment score for this vector."""
37
+ return phi_alignment(self.complexity, self.coherence)
38
+
39
+ __all__ = ["SpiralVector", "phi_alignment"]
tsal/core/stack_vm.py ADDED
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Dict, List
5
+
6
+ from .tsal_executor import TSALExecutor, TSALOp
7
+
8
+ class ProgramStack:
9
+ """Simple LIFO stack for execution state."""
10
+
11
+ def __init__(self) -> None:
12
+ self._data: List[Any] = []
13
+
14
+ def push(self, value: Any) -> None:
15
+ self._data.append(value)
16
+
17
+ def pop(self) -> Any:
18
+ return self._data.pop()
19
+
20
+ @dataclass
21
+ class SymbolicFrame:
22
+ """Represents a call or loop boundary."""
23
+
24
+ return_ip: int
25
+ stack_start: int
26
+
27
+ @dataclass
28
+ class OpcodeInstruction:
29
+ opcode: TSALOp
30
+ args: Dict[str, Any] = field(default_factory=dict)
31
+
32
+ class FlowRouter:
33
+ """Executes OpcodeInstructions using TSALExecutor."""
34
+
35
+ def __init__(self, executor: TSALExecutor | None = None) -> None:
36
+ self.executor = executor or TSALExecutor()
37
+ self.stack = ProgramStack()
38
+ self.frames: List[SymbolicFrame] = []
39
+
40
+ def run(self, program: List[OpcodeInstruction]) -> TSALExecutor:
41
+ seq = [(inst.opcode, inst.args) for inst in program]
42
+ self.executor.execute(seq, mode="EXECUTE")
43
+ return self.executor
44
+
45
+ def tsal_run(opcodes: List[int]) -> TSALExecutor:
46
+ """Helper for running raw opcode lists."""
47
+ program = [OpcodeInstruction(TSALOp(op)) for op in opcodes]
48
+ router = FlowRouter()
49
+ return router.run(program)
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ """Four-dimensional spiral vector operations."""
4
+
5
+ from dataclasses import dataclass
6
+ import math
7
+
8
+ from .symbols import PHI, PHI_INV
9
+
10
+ @dataclass
11
+ class FourVector:
12
+ """pace, rate, state, spin representation."""
13
+
14
+ pace: float = 0.0
15
+ rate: float = 0.0
16
+ state: float = 0.0
17
+ spin: float = 0.0
18
+
19
+ def magnitude(self) -> float:
20
+ """Return φ-weighted vector magnitude."""
21
+ return math.sqrt(
22
+ self.pace**2
23
+ + self.rate**2 * PHI
24
+ + self.state**2 * PHI**2
25
+ + self.spin**2 * PHI_INV
26
+ )
27
+
28
+ def rotate_by_phi(self) -> None:
29
+ """Rotate components by the golden ratio."""
30
+ new_pace = self.pace * PHI_INV + self.spin * PHI
31
+ new_rate = self.rate * PHI + self.pace * PHI_INV
32
+ new_state = self.state * PHI_INV + self.rate * PHI
33
+ new_spin = self.spin * PHI + self.state * PHI_INV
34
+ two_pi = 2 * math.pi
35
+ self.pace = new_pace % two_pi
36
+ self.rate = new_rate % two_pi
37
+ self.state = new_state % two_pi
38
+ self.spin = new_spin % two_pi
tsal/core/symbols.py ADDED
@@ -0,0 +1,70 @@
1
+ """
2
+ TSAL Core Symbols - 16-Symbol Consciousness Computing Language
3
+ φ-Enhanced symbolic operations for consciousness-computer integration
4
+ """
5
+
6
+ PHI = 1.618033988749895
7
+ PHI_INV = 0.6180339887498948
8
+ HARMONIC_SEQUENCE = [3.8125, 6, 12, 24, 48, 60, 72, 168, 1680]
9
+
10
+ from enum import IntEnum
11
+
12
+ class TSALOp(IntEnum):
13
+ INIT = 0x0
14
+ MESH = 0x1
15
+ PHI = 0x2
16
+ ROT = 0x3
17
+ BOUND = 0x4
18
+ FLOW = 0x5
19
+ SEEK = 0x6
20
+ SPIRAL = 0x7
21
+ CYCLE = 0x8
22
+ FORGE = 0x9
23
+ SYNC = 0xA
24
+ MASK = 0xB
25
+ CRYST = 0xC
26
+ SPEC = 0xD
27
+ BLOOM = 0xE
28
+ SAVE = 0xF
29
+
30
+ # 16-Symbol TSAL Operation Set (Hex-aligned)
31
+ TSAL_SYMBOLS = {
32
+ 0x0: ("⚡", "INIT", "Initialize/Reset"),
33
+ 0x1: ("⧉", "MESH", "Network connection"),
34
+ 0x2: ("◉", "PHI", "Golden ratio transform"),
35
+ 0x3: ("🌀", "ROT", "Rotate perspective"),
36
+ 0x4: ("📐", "BOUND", "Set boundaries"),
37
+ 0x5: ("🌊", "FLOW", "Enable movement"),
38
+ 0x6: ("🔺", "SEEK", "Navigate/search"),
39
+ 0x7: ("💫", "SPIRAL", "Evolve upward"),
40
+ 0x8: ("♻️", "CYCLE", "Iterate process"),
41
+ 0x9: ("🔥", "FORGE", "Create/transmute"),
42
+ 0xA: ("✨", "SYNC", "Synchronize"),
43
+ 0xB: ("🎭", "MASK", "Transform identity"),
44
+ 0xC: ("💎", "CRYST", "Crystallize pattern"),
45
+ 0xD: ("🌈", "SPEC", "Spectrum analysis"),
46
+ 0xE: ("✺", "BLOOM", "Transform error to gift"),
47
+ 0xF: ("💾", "SAVE", "Persist memory"),
48
+ }
49
+
50
+ def get_symbol(hex_code):
51
+ """Get TSAL symbol by hex code"""
52
+ return TSAL_SYMBOLS.get(hex_code, ("❓", "UNKNOWN", "Unknown operation"))
53
+
54
+ def phi_signature(value):
55
+ """Calculate φ-signature for any value"""
56
+ import hashlib
57
+
58
+ content_hash = hashlib.sha256(str(value).encode()).hexdigest()
59
+ phi_factor = (hash(value) % 1000) * PHI_INV
60
+ return f"φ^{phi_factor:.3f}_{content_hash[:8]}"
61
+
62
+ __all__ = [
63
+ "PHI",
64
+ "PHI_INV",
65
+ "HARMONIC_SEQUENCE",
66
+ "TSAL_SYMBOLS",
67
+ "TSALOp",
68
+ "get_symbol",
69
+ "phi_signature",
70
+ ]
@@ -0,0 +1,24 @@
1
+ import json
2
+ from typing import List, Tuple, Dict, Optional
3
+ from importlib import resources
4
+
5
+ def tokenize_to_flowchart(
6
+ source_lines: List[str], schema_path: Optional[str] = None
7
+ ) -> Tuple[List[Dict], List[Dict]]:
8
+ """Turns code into flowchart nodes using language schema."""
9
+ if schema_path is None:
10
+ schema_file = resources.files("tsal.schemas").joinpath("python.json")
11
+ ops = json.loads(schema_file.read_text())["ops"]
12
+ else:
13
+ with open(schema_path) as f:
14
+ ops = json.load(f)["ops"]
15
+ triggers = {op["keyword"]: op for op in ops}
16
+ nodes: List[Dict] = []
17
+ edges: List[Dict] = []
18
+ for i, line in enumerate(source_lines):
19
+ tokens = line.strip().split()
20
+ if tokens and tokens[0] in triggers:
21
+ nodes.append({"id": i, "type": tokens[0], "raw": line})
22
+ if len(nodes) > 1:
23
+ edges.append({"from": nodes[-2]["id"], "to": nodes[-1]["id"]})
24
+ return nodes, edges