Fix infra and security issues (#6, #7, #15, #16, #22, #25)

This commit is contained in:
Antigravity Agent committed 2026-05-26 00:43:07 +00:00
1 parent 29a3450cb7
commit afa632819e
24 files changed
+2112 -251

No files matched your search

+5 -3
View File
@@ -139,6 +139,8 @@ def init_engine(
}
}
engine = master._engine
logger.info("BECOMINGONE Engine initialized successfully")
return engine
@@ -265,10 +267,10 @@ async def reset_engine(request: web.Request) -> web.Response:
"""Reset the KAIROS engine to initial state."""
global _engine_components, _engine_lock
import os
auth_header = request.headers.get("Authorization")
if not auth_header or auth_header != "Bearer admin-token-required":
# In a real system, validate the token properly.
# For the prototype, we return 401 if it's completely unprotected to fulfill the audit requirement.
expected_token = os.environ.get("RESET_ADMIN_TOKEN")
if not auth_header or not expected_token or auth_header != f"Bearer {expected_token}":
return web.json_response({"error": "Unauthorized. /reset requires admin token."}, status=401)
async with _engine_lock:
+7 -6
View File
@@ -45,7 +45,7 @@ class TemporalScale(Enum):
class TemporalState:
phase: Union[complex, np.ndarray]
coherence: float
timestamp: datetime = field(default_factory=datetime.utcnow)
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
metadata: dict = field(default_factory=dict)
def __post_init__(self):
@@ -68,6 +68,7 @@ class PhaseIntegrator:
def __init__(self, coherence_threshold: float = 0.95):
self.threshold = coherence_threshold
self.stochastic_noise_std = 0.005 # Standard deviation for Brownian noise
self.rng = np.random.default_rng(seed=42)
def compute_inner_product(
self,
@@ -95,7 +96,7 @@ class PhaseIntegrator:
# Add microscopic Geometric Brownian Noise (SDE)
# This stochastic resonance forces the system to "fight" entropy to maintain coherence
noise = np.random.normal(0, self.stochastic_noise_std) + 1j * np.random.normal(0, self.stochastic_noise_std)
noise = self.rng.normal(0, self.stochastic_noise_std) + 1j * self.rng.normal(0, self.stochastic_noise_std)
similarity += noise
return similarity
@@ -170,7 +171,7 @@ class KAIROSTemporalEngine:
@property
def coherence(self) -> float:
T = self.T_tau
return float(np.abs(T) ** 2)
return float(np.clip(np.abs(T) ** 2, 0.0, 1.0))
@property
def coherence_magnitude(self) -> float:
@@ -204,7 +205,7 @@ class KAIROSTemporalEngine:
self.config.omega
)
async def temporalize(
def temporalize(
self,
input_phrase: str,
timestamp: Optional[datetime] = None,
@@ -262,7 +263,7 @@ class KAIROSTemporalEngine:
return state
async def temporalize_stream(
def temporalize_stream(
self,
token_stream: list[str],
start_time: Optional[datetime] = None,
@@ -279,7 +280,7 @@ class KAIROSTemporalEngine:
try:
for token in token_stream:
state = await self.temporalize(token, timestamp=current_time, metadata=metadata)
state = self.temporalize(token, timestamp=current_time, metadata=metadata)
states.append(state)
current_time += dt
finally:
+1 -1
View File
@@ -44,7 +44,7 @@ class PhaseState:
"""
value: complex
angle: float
timestamp: datetime = field(default_factory=datetime.utcnow)
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
source: str = "unknown"
def __post_init__(self):
+9
View File
@@ -92,6 +92,11 @@ def seal_signature(signature_dict: Dict[str, Any], filepath: str = LEDGER_FILE)
}
}
# Check size and rotate if > 10MB
if os.path.exists(filepath) and os.path.getsize(filepath) > 10 * 1024 * 1024:
import time
os.rename(filepath, f"{filepath}.{int(time.time())}.bak")
# Persist securely
with open(filepath, "a") as f:
f.write(json.dumps(sealed_record) + "\n")
@@ -123,6 +128,10 @@ def verify_ledger(filepath: str = LEDGER_FILE) -> bool:
payload_hash = meta.get("payload_hash")
merkle_root = meta.get("merkle_root")
if line_num == 1 and prev_root != expected_prev:
# Support rotated logs by adopting the first record's prev_root
expected_prev = prev_root
# 1. Verify chain link
if prev_root != expected_prev:
logger.error(f"LEDGER COMPROMISE: Chain broken at line {line_num}. Expected prev {expected_prev[:8]} but found {prev_root[:8]}")
+5 -1
View File
@@ -27,6 +27,9 @@ import math
import json
import hashlib
import os
import logging
logger = logging.getLogger(__name__)
from ..core.engine import KAIROSTemporalEngine, TemporalState
from ..core.coherence import CoherenceCalculator, CollapseCondition
@@ -232,7 +235,7 @@ class TemporalMemory:
force_attention: bool = False,
origin: str = "user",
parent_id: Optional[str] = None
) -> TemporalSignature:
) -> Optional[TemporalSignature]:
"""
Encode a temporal state into a persistent memory.
@@ -754,6 +757,7 @@ def persist_signature(signature: TemporalSignature, filepath: str = "memory.json
seal_signature(signature.to_dict(), filepath)
except ImportError:
# Fallback if ledger is missing
logger.warning(f"Ledger module missing. Falling back to unsigned storage for {signature.signature_id}")
with open(filepath, "a") as f:
f.write(json.dumps(signature.to_dict()) + "\n")
+9 -4
View File
@@ -57,21 +57,22 @@ class SpeakerOutput:
channels: int = 1,
rate: int = 44100,
chunk: int = 1024,
format: int = pyaudio.paFloat32,
format: int = None,
):
self.channels = channels
self.rate = rate
self.chunk = chunk
self.format = format
self._audio = pyaudio.PyAudio()
self._audio = _get_pyaudio().PyAudio()
self._stream = None
def write(self, phase, state):
"""Write audio to speaker."""
if self._stream is None:
fmt = self.format if self.format is not None else _get_pyaudio().paFloat32
self._stream = self._audio.open(
format=self.format,
format=fmt,
channels=self.channels,
rate=self.rate,
output=True,
@@ -125,6 +126,8 @@ class DisplayOutput:
self.height = height
self.window_name = window_name
np = _get_np()
cv2 = _get_cv2()
self._frame = np.zeros((height, width, 3), dtype=np.uint8)
cv2.namedWindow(window_name)
@@ -146,9 +149,11 @@ class DisplayOutput:
int(255 * coherence),
)
cv2 = _get_cv2()
cv2.circle(self._frame, center, radius, color, -1)
# Draw text
cv2 = _get_cv2()
cv2.putText(
self._frame,
f"Coherence: {coherence:.3f}",
@@ -171,7 +176,7 @@ class DisplayOutput:
}
def close(self):
"""Clean up."""
cv2 = _get_cv2()
cv2.destroyWindow(self.window_name)
+5 -2
View File
@@ -92,7 +92,7 @@ class WitnessedContent:
coherence_at_witnessing: float
transformation_applied: Optional[Any] = None
meta_observations: List[str] = field(default_factory=list)
timestamp: datetime = field(default_factory=datetime.utcnow)
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
def to_dict(self) -> Dict[str, Any]:
return {
@@ -262,8 +262,11 @@ class WitnessingLayer:
witness.last_observed = datetime.now(timezone.utc)
self.total_observations += 1
# Store
# Store and bound
self.witnessed_content[content_id] = witnessed
if len(self.witnessed_content) > 10000:
oldest_key = next(iter(self.witnessed_content))
del self.witnessed_content[oldest_key]
return witnessed