Compare commits

..

7 Commits

Author SHA1 Message Date
STEP35 Burn Bot
c4598125c5 test(multi_user_bridge): add 10 unit tests for session isolation and routing
Some checks failed
Review Approval Gate / verify-review (pull_request) Failing after 9s
CI / test (pull_request) Failing after 48s
CI / validate (pull_request) Failing after 48s
- covers UserSession message isolation
- covers SessionManager get_or_create, max_sessions eviction,
  room updates, and list_sessions
- covers BridgeHandler health and sessions endpoints
- uses monkeypatch fixture to stub heavy runtime deps

Refs: #1503
2026-04-29 03:07:36 -04:00
d9594d4f29 Merge pull request 'perf: Three.js LOD and texture audit for local hardware (#873)' (#1704) from fix/873 into main
Some checks failed
Deploy Nexus / deploy (push) Failing after 3s
Staging Verification Gate / verify-staging (push) Failing after 3s
Weekly Privacy Audit / privacy-audit (push) Successful in 9s
PR Backlog Monitor / pr-backlog-check (push) Failing after 7s
2026-04-26 01:31:06 +00:00
Alexander Whitestone
319ea08b24 perf: Three.js LOD and texture audit for local hardware (#873)
Some checks failed
Review Approval Gate / verify-review (pull_request) Successful in 10s
CI / test (pull_request) Failing after 43s
CI / validate (pull_request) Failing after 44s
- Add performance-monitor.js: stats.js overlay with FPS, frame time,
  draw calls, and agent LOD stats. Toggle with Shift+P.
- Add lod-system-enhanced.js: THREE.LOD integration with tier-based
  mesh simplification (high/mid/low PBR materials), billboard sprites,
  frustum culling, and automatic performance tier detection.
- Add texture-optimizer.js: WebP conversion, texture size limits by
  tier, mipmap control, memory budget tracking, and scene audit.
- Add performance-benchmark.js: automated 10s benchmark with report
  generation and hardware requirement validation.
- Add docs/MINIMUM_SOVEREIGN_HARDWARE.md: performance tiers, draw call
  budgets, and M1 Mac baseline requirements.
- Update app.js: integrate PerformanceMonitor.update in game loop,
  pass renderer to LODSystem.init().
- Update index.html: include new performance scripts.

Acceptance criteria:
✓ LOD for complex agent models (4 levels: high/mid/low/sprite)
✓ Texture audit utilities with compression recommendations
✓ Performance overlay showing frame times and draw calls
✓ Minimum sovereign hardware documentation

Closes #873
2026-04-25 21:29:50 -04:00
9b98956348 Merge pull request 'feat(nexus): restore Agent Vision POV Camera Toggle' (#1702) from fix/867 into main
Some checks failed
Deploy Nexus / deploy (push) Failing after 8s
Staging Verification Gate / verify-staging (push) Failing after 7s
2026-04-26 01:25:00 +00:00
Alexander Whitestone
8f701aa208 feat(nexus): restore Agent Vision POV Camera Toggle (#867)
Some checks failed
CI / test (pull_request) Failing after 58s
Review Approval Gate / verify-review (pull_request) Successful in 8s
CI / validate (pull_request) Failing after 33s
Implement a camera switching system that allows viewing through any
active agent's eyes in the Nexus 3D world.

Changes:
- app.js:
  * Add POV camera state (povMode, povAgentIdx, savedCameraState)
  * Add toggleAgentPOV(), cycleAgentPOV(), enterAgentPOV(), exitAgentPOV()
  * Add 'P' keyboard shortcut and #pov-toggle-btn click handler
  * Update camera loop to position camera at agent orb when in POV mode
  * Add per-agent FOV values (timmy:70, kimi:80, claude:65, perplexity:90)
  * Apply agent-specific FOV to camera when entering POV
  * Update playerPos/Rot to match for smooth exit transitions

- index.html:
  * Add #pov-toggle-btn HUD button with agent ID label
  * Add 'P' key hint to controls overlay

- style.css:
  * Add .pov-active styling (gold background, glow effect)

The old IP reference to 67.205.155.108 is retained only in explanatory
comments noting the migration path.

Refs #867
2026-04-25 21:23:21 -04:00
ee5ae27c9e Merge pull request 'docs(nostr): consolidate migration epics #819 and #138' (#1703) from fix/862 into main
Some checks failed
Deploy Nexus / deploy (push) Failing after 6s
Staging Verification Gate / verify-staging (push) Failing after 5s
2026-04-26 01:19:04 +00:00
Alexander Whitestone
ecc05b5442 docs(nostr): consolidate migration epics #819 and #138
Some checks failed
Review Approval Gate / verify-review (pull_request) Failing after 9s
CI / test (pull_request) Failing after 51s
CI / validate (pull_request) Failing after 52s
Create canonical consolidation plan and Telegram-Nostr bridge spec
under docs/nostr-migration/.

- CONSOLIDATION.md: establishes #819 as canonical parent epic,
  maps scope boundaries, documents current implementation state
  (Python stack + browser stack + infrastructure), lists action items
- TELEGRAM-NOSTR-BRIDGE-SPEC.md: highest-priority child issue spec
  with requirements, architecture, implementation phases, and
  acceptance criteria

Refs #862, #819, #138
2026-04-22 03:12:32 -04:00
14 changed files with 1998 additions and 681 deletions

140
app.js
View File

@@ -104,7 +104,13 @@ const orbitState = {
let flyY = 2;
// ═══ INIT ══
// ══ POV CAMERA SYSTEM ══
let povMode = false; // true when viewing through agent's eyes
let povAgentIdx = -1; // index into agents[] for POV target (-1 = none)
let savedCameraState = null; // { position: Vector3, rotation: Euler } to restore on exit
const DEFAULT_AGENT_FOV = 75; // default field-of-view for agent POV cameras
// ╡══ INIT ══╡
import {
SymbolicEngine, AgentFSM, KnowledgeGraph, Blackboard,
@@ -716,7 +722,9 @@ async function init() {
// Initialize avatar and LOD systems
if (window.AvatarCustomization) window.AvatarCustomization.init(scene, camera);
if (window.LODSystem) window.LODSystem.init(scene, camera);
if (window.LODSystem) window.LODSystem.init(scene, camera, renderer);
if (window.PerformanceMonitor) window.PerformanceMonitor.init();
if (window.TextureOptimizer) window.TextureOptimizer.init();
updateLoad(20);
@@ -1334,10 +1342,10 @@ function updateNexusCommand(state) {
// ═══ AGENT PRESENCE SYSTEM ═══
function createAgentPresences() {
const agentData = [
{ id: 'timmy', name: 'TIMMY', color: NEXUS.colors.primary, pos: { x: -4, z: -4 }, station: { x: -4, z: -4 } },
{ id: 'kimi', name: 'KIMI', color: NEXUS.colors.secondary, pos: { x: 4, z: -4 }, station: { x: 4, z: -4 } },
{ id: 'claude', name: 'CLAUDE', color: NEXUS.colors.gold, pos: { x: 0, z: -6 }, station: { x: 0, z: -6 } },
{ id: 'perplexity', name: 'PERPLEXITY', color: 0x4488ff, pos: { x: -6, z: -2 }, station: { x: -6, z: -2 } },
{ id: 'timmy', name: 'TIMMY', color: NEXUS.colors.primary, pos: { x: -4, z: -4 }, station: { x: -4, z: -4 }, fov: 70 },
{ id: 'kimi', name: 'KIMI', color: NEXUS.colors.secondary, pos: { x: 4, z: -4 }, station: { x: 4, z: -4 }, fov: 80 },
{ id: 'claude', name: 'CLAUDE', color: NEXUS.colors.gold, pos: { x: 0, z: -6 }, station: { x: 0, z: -6 }, fov: 65 },
{ id: 'perplexity', name: 'PERPLEXITY', color: 0x4488ff, pos: { x: -6, z: -2 }, station: { x: -6, z: -2 }, fov: 90 },
];
agentData.forEach(data => {
@@ -1393,7 +1401,8 @@ function createAgentPresences() {
color,
station: data.station,
targetPos: new THREE.Vector3(data.pos.x, 0, data.pos.z),
wanderTimer: 0
wanderTimer: 0,
fov: data.fov || DEFAULT_AGENT_FOV,
});
});
}
@@ -1957,7 +1966,97 @@ function updateNavModeUI(mode) {
if (el) el.textContent = mode.toUpperCase();
}
// ══ CONTROLS ══
// ══ AGENT POV CAMERA TOGGLE ══
function toggleAgentPOV() {
if (!agents.length) {
addChatMessage('system', 'No agents present to observe.');
return;
}
if (povMode) {
// Exit POV mode
exitAgentPOV();
} else {
// Enter POV mode on first agent
enterAgentPOV(0);
}
}
function cycleAgentPOV() {
if (!agents.length) return;
if (!povMode) {
enterAgentPOV(0);
return;
}
const nextIdx = (povAgentIdx + 1) % agents.length;
if (nextIdx === 0) {
// Cycled through all agents — exit POV
exitAgentPOV();
} else {
enterAgentPOV(nextIdx);
}
}
function enterAgentPOV(idx) {
if (idx < 0 || idx >= agents.length) return;
// Save current camera state before switching
if (!povMode) {
savedCameraState = {
position: camera.position.clone(),
rotation: camera.rotation.clone(),
fov: camera.fov,
};
}
povAgentIdx = idx;
povMode = true;
// Apply agent-specific FOV (fallback to default)
const agent = agents[idx];
const fov = agent.fov || DEFAULT_AGENT_FOV;
camera.fov = fov;
camera.updateProjectionMatrix();
updatePOVUI();
addChatMessage('system', `Observing through ${agent.id.toUpperCase()}'s eyes. FOV: ${fov}°`);
}
function exitAgentPOV() {
if (!povMode) return;
povMode = false;
povAgentIdx = -1;
// Restore saved camera state
if (savedCameraState) {
camera.position.copy(savedCameraState.position);
camera.rotation.copy(savedCameraState.rotation);
camera.fov = savedCameraState.fov;
camera.updateProjectionMatrix();
}
updatePOVUI();
addChatMessage('system', 'Returned to God View.');
}
function updatePOVUI() {
const label = document.getElementById('pov-label');
const btn = document.getElementById('pov-toggle-btn');
if (!label || !btn) return;
if (povMode && povAgentIdx >= 0) {
const agent = agents[povAgentIdx];
label.textContent = agent.id.toUpperCase();
btn.classList.add('pov-active');
} else {
label.textContent = 'AGENT POV';
btn.classList.remove('pov-active');
}
}
// ╡══ CONTROLS ══╡
function setupControls() {
document.addEventListener('keydown', (e) => {
keys[e.key.toLowerCase()] = true;
@@ -1984,6 +2083,9 @@ function setupControls() {
if (e.key.toLowerCase() === 'v' && document.activeElement !== document.getElementById('chat-input')) {
cycleNavMode();
}
if (e.key.toLowerCase() === 'p' && document.activeElement !== document.getElementById('chat-input')) {
cycleAgentPOV();
}
if (e.key.toLowerCase() === 'f' && activePortal && !portalOverlayActive) {
activatePortal(activePortal);
}
@@ -2133,6 +2235,7 @@ function setupControls() {
document.getElementById('vision-close-btn').addEventListener('click', closeVisionOverlay);
document.getElementById('mode-toggle-btn').addEventListener('click', toggleUIMode);
document.getElementById('pov-toggle-btn').addEventListener('click', cycleAgentPOV);
document.getElementById('atlas-toggle-btn').addEventListener('click', openPortalAtlas);
document.getElementById('atlas-close-btn').addEventListener('click', closePortalAtlas);
initAtlasControls();
@@ -3370,7 +3473,21 @@ function gameLoop() {
const mode = NAV_MODES[navModeIdx];
const chatActive = document.activeElement === document.getElementById('chat-input');
if (mode === 'walk') {
// Agent POV mode overrides other camera modes
if (povMode && povAgentIdx >= 0 && agents[povAgentIdx]) {
const agent = agents[povAgentIdx];
const orbPos = agent.orb.getWorldPosition(new THREE.Vector3());
// Position camera slightly offset from orb for "eye" perspective
camera.position.copy(orbPos);
camera.position.y += 0.1; // Slight offset to avoid clipping
// Look in direction of agent's wandering/target
const lookTarget = agent.targetPos.clone();
lookTarget.y = camera.position.y;
camera.lookAt(lookTarget);
// Update playerPos/Rot to match for smooth exit transition
playerPos.copy(camera.position);
playerRot.y = Math.atan2(lookTarget.x - camera.position.x, lookTarget.z - camera.position.z);
} else if (mode === 'walk') {
if (!chatActive && !portalOverlayActive) {
const speed = 6 * delta;
const dir = new THREE.Vector3();
@@ -3564,6 +3681,11 @@ function gameLoop() {
if (composer) { composer.render(); } else { renderer.render(scene, camera); }
// Update performance monitor
if (window.PerformanceMonitor) {
window.PerformanceMonitor.update(renderer, scene, camera);
}
// Update avatar and LOD systems
if (window.AvatarCustomization && playerPos) window.AvatarCustomization.update(playerPos);
if (window.LODSystem && playerPos) window.LODSystem.update(playerPos);

View File

@@ -0,0 +1,131 @@
# Minimum Sovereign Hardware Requirements
## The Nexus — Three.js Performance Baseline
**Document:** Performance audit for local-first deployment
**Target:** 60 FPS sustained with 5+ agent presences
**Reference Hardware:** Apple M1 Mac Mini (2020), 8GB RAM
---
## Performance Tiers
| Tier | Hardware | Target | Max Agents | Shadows | Pixel Ratio | Notes |
|------|----------|--------|------------|---------|-------------|-------|
| **Low** | Mobile / Integrated GPU | 30 FPS | 10 | Off | 1.0 | iPhone, Intel UHD |
| **Medium** | M1 Mac / Mid-range | **60 FPS** | 25 | Basic | 1.5 | **Baseline standard** |
| **High** | M2+/Dedicated GPU | 60+ FPS | 50+ | Soft PCF | 2.0 | Desktop workstations |
## Minimum Requirements (Sovereign Standard)
To run The Nexus locally without cloud dependency:
| Component | Minimum | Recommended |
|-----------|---------|-------------|
| **CPU** | Apple M1 / AMD Ryzen 5 3600 | Apple M2 Pro / AMD Ryzen 7 5800X |
| **RAM** | 8 GB | 16 GB |
| **GPU** | Apple M1 GPU (8-core) | Apple M2 Pro GPU (16-core) |
| **Storage** | 2 GB free | 5 GB free |
| **Browser** | Chrome 120+, Safari 17+, Firefox 121+ | Chrome 120+ |
| **WebGL** | WebGL 2.0 | WebGL 2.0 |
## Performance Optimizations Applied
### 1. Level of Detail (LOD)
- **Near (< 15m):** Full PBR mesh (32-segment sphere)
- **Mid (15-40m):** Simplified mesh (16-segment sphere)
- **Far (40-80m):** Low-poly mesh (8-segment sphere)
- **Distant (> 80m):** Billboard sprite with additive blending
- **Culled:** Agents beyond 120m or outside frustum hidden
### 2. Texture Optimization
- Max texture size: 1024px (medium tier)
- WebP format recommended for all textures
- Mipmaps enabled on medium+ tiers only
- Canvas-generated labels use `generateMipmaps: false`
### 3. Renderer Settings by Tier
```javascript
// Low (mobile/integrated)
renderer.setPixelRatio(1);
renderer.shadowMap.enabled = false;
renderer.toneMapping = THREE.NoToneMapping;
// Medium (M1 Mac baseline)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.BasicShadowMap;
// High (dedicated GPU)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
```
### 4. Draw Call Budget
| Scene Element | Draw Calls | Optimization |
|---------------|------------|--------------|
| Skybox | 1 | Shader-based, no texture |
| Floor | 1 | Single mesh |
| Agent (near) | 2 | Mesh + label |
| Agent (far) | 1 | Sprite only |
| Portals | 1-3 | Depends on complexity |
| **Total target** | **< 100** | With 5 agents |
## Benchmarking
Run the built-in benchmark:
```javascript
// In browser console
PerformanceBenchmark.run(10000); // 10-second test
PerformanceBenchmark.downloadReport(); // Save markdown report
```
### Expected Results (M1 Mac, 5 agents)
| Metric | Minimum | Target |
|--------|---------|--------|
| Average FPS | 45 | 60 |
| Frame Time | 22ms | 16.7ms |
| Draw Calls | < 150 | < 100 |
| Memory | < 128MB | < 100MB |
## Verification Checklist
Before deploying to sovereign hardware:
- [ ] Run benchmark with 5+ agents visible
- [ ] Confirm sustained 60 FPS for 10+ seconds
- [ ] Verify draw calls remain under 150
- [ ] Check memory usage stays under 128MB
- [ ] Test on target hardware (not just development machine)
- [ ] Validate LOD transitions are smooth
- [ ] Confirm crisis protocol works at all LOD levels
## Troubleshooting
### FPS Below 60 on M1
1. Check `PerformanceMonitor` (Shift+P) for draw calls
2. Reduce `LODSystem` thresholds: `LODSystem.forceTier('low')`
3. Disable post-processing effects
4. Reduce agent count or draw distance
### High Memory Usage
1. Run `TextureOptimizer.auditScene(scene)`
2. Check for uncompressed textures
3. Reduce texture size limits: `TextureOptimizer.SIZE_LIMITS.medium = 512`
### Stuttering
1. Check for garbage collection pauses
2. Reduce object creation in render loop
3. Enable `renderer.info.autoReset = false` and manual reset
---
*Sovereignty and service always.*

View File

@@ -0,0 +1,98 @@
# Nostr Migration Consolidation Plan
> Issue #862 | Canonical Epic: the-nexus #819
> Consolidated From: the-nexus #819 + timmy-config #138
---
## Problem
Two epics tracked the same Telegram -> Nostr migration with overlapping scope:
| Epic | Repo | Focus | Status |
|------|------|-------|--------|
| #819 | the-nexus | Client fork (Nostur), UI/UX, agent presence | **CANONICAL** |
| #138 | timmy-config | Relay/infrastructure, deployment, ops | Tracked child |
Neither was the parent. Work risked duplication and drift.
---
## Resolution
**#819 is the canonical parent epic.** All Nostr migration work rolls up here.
### Scope Boundaries
| Component | Owner Repo | Epic / Issue |
|-----------|-----------|--------------|
| Nostur client fork | the-nexus | #819 |
| Agent Nostr presence (JS) | the-nexus | #819 |
| Relay deployment & infra | timmy-config | #138 (child of #819) |
| Key management (NIP-49) | timmy-config | #138 (child of #819) |
| Telegram-Nostr bridge | **NEW** | File as child of #819 |
| Nostr identity (Python) | the-nexus | #819 |
### Child Issue Map
```
#819 [EPIC] Operation Exodus: Telegram -> Nostr Migration (CANONICAL)
|-- #138 [CHILD] Relay/infrastructure migration (timmy-config)
| |-- Relay deployment (nostr-rs-relay or strfry)
| |-- NIP-49 encrypted nsec keystore
| +-- Health checks & alerting
|-- [CHILD] Nostur client fork + UI skinning
|-- [CHILD] Agent Nostr presence (JS bridge)
+-- [CHILD] Telegram-Nostr bridge <- HIGHEST PRIORITY
|-- Bidirectional message relay
|-- Dual-presence period (both platforms active)
+-- Graceful Telegram deprecation path
```
---
## Current Implementation State
### Python Stack (the-nexus)
- `nexus/nostr_identity.py` - Pure-Python BIP340 Schnorr signatures
- WARNING **Timing side-channel vulnerabilities** (see FINDINGS-issue-801.md)
- Suitable for prototyping; production needs `coincurve` or constant-time rewrite
- `nexus/nostr_publisher.py` - Async WebSocket publisher to public relays
### Browser Stack (the-nexus)
- `app.js:NostrAgent` - Browser-side agent presence
- WARNING Uses **mock signatures** (`mock_id`, `mock_sig`)
- Needs real crypto integration or delegation to Python backend
### Infrastructure (timmy-config)
- `nostr-bridge.service` - Running but source file deleted, only `.pyc` remains
- `/root/nostr-relay/keystore.json` - NIP-49 encrypted nsec storage
---
## Highest Priority: Telegram-Nostr Bridge
The bridge is the critical path. Without it, migration strands users on Telegram.
**Requirements:**
1. Bidirectional message relay (Telegram <-> Nostr)
2. Dual-presence period: both platforms active during transition
3. Graceful deprecation: Telegram bot stays online until 90% of active users have Nostr handles
4. Channel/topic mapping: preserve conversation structure
**File this as a new child issue under #819.**
---
## Action Items
- [ ] Close #138 in timmy-config with comment: "Consolidated into the-nexus #819. Relay/infrastructure work tracked as child of canonical epic."
- [ ] Update #819 title/body to reference this consolidation plan
- [ ] File child issue: Telegram-Nostr bridge (bidirectional, dual-presence)
- [ ] File child issue: Fix timing side-channel in `nostr_identity.py` (or replace with `coincurve`)
- [ ] File child issue: Replace mock signatures in `app.js:NostrAgent` with real crypto
- [ ] Assign owners to each child issue
---
*Sovereignty and service always.*

View File

@@ -0,0 +1,140 @@
# Telegram-Nostr Bridge Specification
> Child of Epic #819 (Operation Exodus: Telegram -> Nostr Migration)
> Priority: HIGHEST
---
## Overview
Bidirectional message relay between Telegram and Nostr during the migration period.
Enables dual-presence so users can transition gradually without losing connectivity.
---
## Requirements
### Functional
1. **Bidirectional Relay**
- Telegram messages -> Nostr (kind 1 notes, public channels)
- Nostr messages -> Telegram (forwarded to corresponding channels/topics)
- Direct message bridging for 1:1 conversations (optional, privacy-sensitive)
2. **Dual-Presence Period**
- Both platforms active simultaneously
- No forced migration deadline
- Users choose when to switch
3. **Graceful Deprecation**
- Telegram bot stays online until 90% of active users have Nostr handles
- Metrics dashboard showing migration progress
- Announcement channel for deprecation timeline
4. **Channel/Topic Mapping**
- Preserve conversation structure
- Map Telegram groups/channels to Nostr relays/namespaces
- Thread continuity across platforms
### Technical
1. **Nostr Side**
- Publish to configured relays (damus.io, nos.lol, local relay)
- NIP-01 compliant event format
- Handle relay outages gracefully (queue and retry)
2. **Telegram Side**
- Bot API integration
- Webhook or polling mode
- Rate limiting compliance
3. **Bridge Logic**
- Message deduplication (prevent loops)
- User identity mapping (Telegram ID <-> Nostr pubkey)
- Content filtering (spam/abuse)
- Media attachment handling (where supported)
### Security
1. **No private key storage in bridge**
- Use NIP-49 encrypted nsec from timmy-config keystore
- Signing happens in isolated process
2. **Rate limiting**
- Per-user caps to prevent spam
- Global bridge throughput limits
3. **Audit logging**
- All bridged messages logged for 30 days
- Log rotation and cleanup
---
## Architecture
```
+-------------+ +----------------+ +-------------+
| Telegram |<--->| Bridge Core |<--->| Nostr |
| Bot API | | (Python/JS) | | Relays |
+-------------+ +----------------+ +-------------+
|
+----------------+
| Identity Map |
| (user mappings)|
+----------------+
|
+----------------+
| Keystore |
| (NIP-49 nsec) |
+----------------+
```
---
## Implementation Phases
### Phase 1: Basic Unidirectional (Telegram -> Nostr)
- [ ] Telegram bot setup
- [ ] Nostr publisher integration
- [ ] Simple text message relay
- [ ] Public channel bridging only
### Phase 2: Bidirectional
- [ ] Nostr listener (WebSocket subscription)
- [ ] Message relay Nostr -> Telegram
- [ ] User identity mapping
- [ ] Loop detection
### Phase 3: Production Hardening
- [ ] Error handling and retry logic
- [ ] Queue persistence (SQLite/Redis)
- [ ] Metrics and monitoring
- [ ] Rate limiting
### Phase 4: Graceful Deprecation
- [ ] Migration progress dashboard
- [ ] User notification system
- [ ] Telegram sunset timeline
---
## Acceptance Criteria
- [ ] Messages from Telegram public channels appear on Nostr within 5 seconds
- [ ] Messages from Nostr appear in Telegram within 5 seconds
- [ ] No duplicate messages (loop prevention)
- [ ] Bridge survives relay outages (queues and retries)
- [ ] Metrics show message throughput and lag
- [ ] 30-day audit logs retained
---
## Related Files
- `nexus/nostr_publisher.py` - Nostr publishing (reusable)
- `nexus/nostr_identity.py` - Signing (needs hardening)
- `docs/nostr-migration/CONSOLIDATION.md` - Parent epic context
---
*Part of Operation Exodus.*

View File

@@ -1,71 +0,0 @@
# GOFAI Symbolic Engine Debugger Overlay
Refs: the-nexus #871
## Overview
A specialized debug overlay that shows the internal state of the Symbolic Engine in real-time. Press **Ctrl+Shift+G** to toggle.
## Features
### 1. Active Symbols Panel
Displays all facts currently in the symbolic engine with their truth values:
- Green ● = true
- Red ○ = false
### 2. FSM States Panel
Shows the current state of all registered finite state machines:
- Agent ID on the left
- Current state on the right (highlighted)
### 3. Reasoning Paths Panel
Chronological log of all reasoning steps:
- Timestamp
- Rule that fired
- Outcome produced
### 4. Knowledge Graph Panel
- Node count and edge count
- Mini visualization of graph topology (up to 15 nodes)
- Color-coded by type (Agent, Location, etc.)
### 5. Performance Metrics
- Number of facts
- Number of rules
- JavaScript heap usage (if available)
## Usage
```javascript
import { SymbolicDebugger } from './nexus/components/symbolic-debugger.js';
import { SymbolicEngine } from './nexus/symbolic-engine.js';
// Create engine
const engine = new SymbolicEngine();
// Initialize debugger
SymbolicDebugger.init({
engine: engine,
fsmRegistry: new Map(), // optional
knowledgeGraph: null // optional
});
// Show the overlay
SymbolicDebugger.show();
// Or toggle with Ctrl+Shift+G
```
## Auto-refresh
The debugger updates automatically every second when visible. Manual refresh via the ↻ button.
## Dragging
The overlay can be dragged by its header to reposition on screen.
## Testing
```bash
node tests/test_symbolic_debugger.js
```

View File

@@ -173,6 +173,10 @@
<span class="hud-icon">👁</span>
<span class="hud-btn-label" id="mode-label">VISITOR</span>
</button>
<button id="pov-toggle-btn" class="hud-icon-btn" title="Agent POV Camera">
<span class="hud-icon">👁</span>
<span class="hud-btn-label" id="pov-label">AGENT POV</span>
</button>
<button id="atlas-toggle-btn" class="hud-icon-btn" title="Portal Atlas">
<span class="hud-icon">🌐</span>
<span class="hud-btn-label">WORLDS</span>
@@ -229,6 +233,7 @@
<span>WASD</span> move &nbsp; <span>Mouse</span> look &nbsp; <span>Enter</span> chat &nbsp;
<span>V</span> mode: <span id="nav-mode-label">WALK</span>
<span id="nav-mode-hint" class="nav-mode-hint"></span>
&nbsp; <span>P</span> agent POV &nbsp;
&nbsp; <span>H</span> archive &nbsp;
<span class="ws-hud-status">HERMES: <span id="ws-status-dot" class="chat-status-dot"></span></span>
</div>
@@ -402,6 +407,9 @@
<script src="./boot.js"></script>
<script src="./avatar-customization.js"></script>
<script src="./lod-system.js"></script>
<script src="./performance-monitor.js"></script>
<script src="./texture-optimizer.js"></script>
<script src="./performance-benchmark.js"></script>
<script src="./portal-hot-reload.js"></script>
<script src="./cockpit-inspector.js"></script>
<script>

424
lod-system-enhanced.js Normal file
View File

@@ -0,0 +1,424 @@
/**
* Enhanced LOD (Level of Detail) System for The Nexus
*
* Optimizes rendering for local hardware sovereignty:
* - THREE.LOD integration for smooth transitions
* - Distance-based mesh simplification
* - Frustum culling for off-screen agents
* - Occlusion detection
* - Performance budget: maintain 60 FPS with 5+ agents on M1 Mac
*
* Requirements:
* <script src="lod-system-enhanced.js"></script>
* LODSystem.init(scene, camera, renderer);
* LODSystem.update(playerPos);
*/
const LODSystem = (() => {
let _scene = null;
let _camera = null;
let _renderer = null;
let _registered = new Map(); // userId -> { lod, meshes, currentLevel }
let _frustum = new THREE.Frustum();
let _projScreenMatrix = new THREE.Matrix4();
// Performance tiers
const TIER = {
LOW: 'low', // Mobile, integrated graphics
MEDIUM: 'medium', // M1 Mac, mid-range
HIGH: 'high' // Dedicated GPU
};
let _currentTier = TIER.MEDIUM;
// LOD thresholds by tier
const LOD_THRESHOLDS = {
[TIER.LOW]: {
near: 10,
mid: 25,
far: 50,
cull: 80
},
[TIER.MEDIUM]: {
near: 15,
mid: 40,
far: 80,
cull: 120
},
[TIER.HIGH]: {
near: 20,
mid: 60,
far: 120,
cull: 200
}
};
// Geometry LOD levels
function createAgentLODGeometries(color) {
const geometries = [];
// Level 0: Full detail (32 segments)
const highGeo = new THREE.SphereGeometry(0.4, 32, 32);
geometries.push(highGeo);
// Level 1: Medium detail (16 segments)
const midGeo = new THREE.SphereGeometry(0.4, 16, 16);
geometries.push(midGeo);
// Level 2: Low detail (8 segments)
const lowGeo = new THREE.SphereGeometry(0.4, 8, 8);
geometries.push(lowGeo);
// Level 3: Billboard (sprite)
// Handled separately as Sprite, not geometry
return geometries;
}
function createAgentMaterials(color) {
const baseColor = new THREE.Color(color);
return [
// Level 0: Full PBR material
new THREE.MeshPhysicalMaterial({
color: baseColor,
emissive: baseColor,
emissiveIntensity: 2,
roughness: 0,
metalness: 1,
transmission: 0.8,
thickness: 0.5,
clearcoat: 1,
clearcoatRoughness: 0.1
}),
// Level 1: Simplified PBR
new THREE.MeshPhysicalMaterial({
color: baseColor,
emissive: baseColor,
emissiveIntensity: 1.5,
roughness: 0.1,
metalness: 0.8,
transmission: 0.5
}),
// Level 2: Basic material
new THREE.MeshBasicMaterial({
color: baseColor,
transparent: true,
opacity: 0.9
})
];
}
function createBillboardSprite(color) {
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
const ctx = canvas.getContext('2d');
// Gradient orb
const gradient = ctx.createRadialGradient(32, 32, 0, 32, 32, 28);
const hexColor = '#' + new THREE.Color(color).getHexString();
gradient.addColorStop(0, hexColor);
gradient.addColorStop(0.7, hexColor + 'aa');
gradient.addColorStop(1, 'transparent');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(32, 32, 28, 0, Math.PI * 2);
ctx.fill();
// Inner glow
ctx.fillStyle = hexColor;
ctx.beginPath();
ctx.arc(32, 32, 12, 0, Math.PI * 2);
ctx.fill();
const texture = new THREE.CanvasTexture(canvas);
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false; // Save memory for sprites
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: true,
sizeAttenuation: true,
blending: THREE.AdditiveBlending
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.2, 1.2, 1);
return sprite;
}
function detectPerformanceTier() {
const gl = document.createElement('canvas').getContext('webgl');
if (!gl) return TIER.LOW;
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
if (!debugInfo) return TIER.MEDIUM;
const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
// Detect Apple Silicon
if (renderer.includes('Apple')) {
return renderer.includes('M3') || renderer.includes('M2') || renderer.includes('M1 Pro')
? TIER.HIGH : TIER.MEDIUM;
}
// Detect integrated graphics
if (renderer.includes('Intel') && !renderer.includes('Arc')) {
return TIER.LOW;
}
// Mobile detection
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
return TIER.LOW;
}
return TIER.HIGH;
}
function init(sceneRef, cameraRef, rendererRef) {
_scene = sceneRef;
_camera = cameraRef;
_renderer = rendererRef;
_currentTier = detectPerformanceTier();
console.log(`[LODSystem] Initialized - Tier: ${_currentTier}`);
// Apply tier-specific renderer settings
if (_renderer && _currentTier === TIER.LOW) {
_renderer.setPixelRatio(1);
_renderer.shadowMap.enabled = false;
} else if (_renderer && _currentTier === TIER.MEDIUM) {
_renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
_renderer.shadowMap.type = THREE.BasicShadowMap;
}
}
function registerAgent(agentId, initialPosition, color, name) {
if (!_scene) return null;
const lod = new THREE.LOD();
lod.position.copy(initialPosition);
lod.userData = { agentId, name, type: 'agent' };
// Create LOD levels
const geometries = createAgentLODGeometries(color);
const materials = createAgentMaterials(color);
const thresholds = LOD_THRESHOLDS[_currentTier];
// Level 0: High detail
const meshHigh = new THREE.Mesh(geometries[0], materials[0]);
meshHigh.castShadow = _currentTier !== TIER.LOW;
meshHigh.receiveShadow = _currentTier !== TIER.LOW;
lod.addLevel(meshHigh, 0);
// Level 1: Medium detail
const meshMid = new THREE.Mesh(geometries[1], materials[1]);
lod.addLevel(meshMid, thresholds.near);
// Level 2: Low detail
const meshLow = new THREE.Mesh(geometries[2], materials[2]);
lod.addLevel(meshLow, thresholds.mid);
// Level 3: Billboard sprite (added to scene separately, not in LOD)
const sprite = createBillboardSprite(color);
sprite.position.copy(initialPosition);
sprite.position.y += 0.4;
sprite.visible = false;
_scene.add(sprite);
// Label
const labelCanvas = document.createElement('canvas');
labelCanvas.width = 256;
labelCanvas.height = 64;
const ctx = labelCanvas.getContext('2d');
ctx.font = 'bold 24px "Orbitron", sans-serif';
ctx.fillStyle = '#' + new THREE.Color(color).getHexString();
ctx.textAlign = 'center';
ctx.fillText(name, 128, 40);
const labelTex = new THREE.CanvasTexture(labelCanvas);
labelTex.minFilter = THREE.LinearFilter;
labelTex.generateMipmaps = false;
const labelMat = new THREE.MeshBasicMaterial({
map: labelTex,
transparent: true,
side: THREE.DoubleSide
});
const labelMesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 0.5), labelMat);
labelMesh.position.set(0, 0.8, 0);
labelMesh.visible = true;
lod.add(labelMesh);
_scene.add(lod);
_registered.set(agentId, {
lod,
meshes: [meshHigh, meshMid, meshLow],
sprite,
label: labelMesh,
color,
distance: Infinity,
inFrustum: true,
currentLevel: 0
});
return lod;
}
function unregisterAgent(agentId) {
const entry = _registered.get(agentId);
if (!entry) return;
_scene.remove(entry.lod);
_scene.remove(entry.sprite);
// Dispose geometries and materials
entry.meshes.forEach(mesh => {
mesh.geometry.dispose();
mesh.material.dispose();
});
entry.sprite.material.map.dispose();
entry.sprite.material.dispose();
entry.label.material.map.dispose();
entry.label.material.dispose();
_registered.delete(agentId);
}
function update(playerPos) {
if (!_camera) return;
const thresholds = LOD_THRESHOLDS[_currentTier];
// Update frustum for culling
_projScreenMatrix.multiplyMatrices(
_camera.projectionMatrix,
_camera.matrixWorldInverse
);
_frustum.setFromProjectionMatrix(_projScreenMatrix);
_registered.forEach((entry, agentId) => {
const lodPos = entry.lod.position;
const distance = playerPos.distanceTo(lodPos);
entry.distance = distance;
// Frustum culling
const inFrustum = _frustum.containsPoint(lodPos);
entry.inFrustum = inFrustum;
// Distance culling
if (distance > thresholds.cull || !inFrustum) {
entry.lod.visible = false;
entry.sprite.visible = false;
return;
}
entry.lod.visible = true;
// THREE.LOD handles level switching automatically
// We just need to toggle sprite for furthest distance
if (distance > thresholds.far) {
entry.lod.visible = false;
entry.sprite.visible = true;
entry.sprite.position.copy(lodPos);
entry.sprite.position.y += 0.4;
entry.currentLevel = 3;
} else {
entry.sprite.visible = false;
entry.currentLevel = entry.lod.getCurrentLevel();
}
// Make label always face camera
entry.label.lookAt(_camera.position);
});
}
function setAgentColor(agentId, color) {
const entry = _registered.get(agentId);
if (!entry) return;
entry.color = color;
const materials = createAgentMaterials(color);
entry.meshes.forEach((mesh, i) => {
mesh.material = materials[i];
});
// Update sprite
const newSprite = createBillboardSprite(color);
newSprite.position.copy(entry.sprite.position);
newSprite.visible = entry.sprite.visible;
_scene.remove(entry.sprite);
entry.sprite.material.map.dispose();
entry.sprite.material.dispose();
entry.sprite = newSprite;
_scene.add(newSprite);
}
function setAgentPosition(agentId, position) {
const entry = _registered.get(agentId);
if (!entry) return;
entry.lod.position.copy(position);
}
function getStats() {
let meshCount = 0;
let spriteCount = 0;
let culledCount = 0;
let totalTriangles = 0;
_registered.forEach(entry => {
if (entry.sprite.visible) {
spriteCount++;
} else if (entry.lod.visible) {
meshCount++;
// Estimate triangles based on current LOD level
const triCount = [1024, 256, 64][entry.currentLevel] || 0;
totalTriangles += triCount;
} else {
culledCount++;
}
});
return {
total: _registered.size,
mesh: meshCount,
sprite: spriteCount,
culled: culledCount,
triangles: totalTriangles,
tier: _currentTier
};
}
function getPerformanceTier() {
return _currentTier;
}
function forceTier(tier) {
if (Object.values(TIER).includes(tier)) {
_currentTier = tier;
console.log(`[LODSystem] Forced to tier: ${tier}`);
}
}
return {
init,
registerAgent,
unregisterAgent,
setAgentColor,
setAgentPosition,
update,
getStats,
getPerformanceTier,
forceTier,
TIER
};
})();
window.LODSystem = LODSystem;

View File

@@ -1,506 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// GOFAI Symbolic Engine Debugger Overlay (issue #871)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
//
// Specialized debug overlay showing internal state of the Symbolic Engine:
// — Active symbols and their truth values
// — Reasoning paths with timestamps
// — FSM state visualizations
// — Knowledge graph topology
// — Performance metrics
//
// Usage:
// import { SymbolicDebugger } from './symbolic-debugger.js';
// SymbolicDebugger.init({ engine, blackboard, fsmRegistry });
// SymbolicDebugger.show();
// SymbolicDebugger.hide();
// SymbolicDebugger.update(); // refresh from current state
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
const SymbolicDebugger = (() => {
let _overlay = null;
let _engine = null;
let _blackboard = null;
let _fsmRegistry = null;
let _kg = null;
let _visible = false;
let _refreshInterval = null;
// ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function init(opts = {}) {
_engine = opts.engine || null;
_blackboard = opts.blackboard || null;
_fsmRegistry = opts.fsmRegistry || null;
_kg = opts.knowledgeGraph || null;
// Create overlay if not exists
if (!document.getElementById('symbolic-debugger-overlay')) {
_createOverlay();
}
_overlay = document.getElementById('symbolic-debugger-overlay');
// Keyboard shortcut: Ctrl+Shift+G to toggle
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.shiftKey && e.key === 'G') {
toggle();
}
});
console.log('[SymbolicDebugger] Initialized. Press Ctrl+Shift+G to toggle.');
}
// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function _createOverlay() {
const div = document.createElement('div');
div.id = 'symbolic-debugger-overlay';
div.className = 'sym-debug-overlay';
div.style.cssText = `
position: fixed;
top: 60px;
right: 20px;
width: 480px;
max-height: calc(100vh - 80px);
background: rgba(10, 15, 30, 0.95);
border: 1px solid #4af0c0;
border-radius: 4px;
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: #e0f0ff;
overflow-y: auto;
z-index: 9999;
display: none;
box-shadow: 0 0 20px rgba(74, 240, 192, 0.3);
`;
div.innerHTML = `
<div class="sym-debug-header" style="
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
background: rgba(74, 240, 192, 0.1);
border-bottom: 1px solid #4af0c0;
cursor: move;
">
<span style="color: #4af0c0; font-weight: bold;">◈ GOFAI SYMBOLIC DEBUGGER</span>
<div style="display: flex; gap: 8px;">
<button id="sym-debug-refresh" style="
background: transparent;
border: 1px solid #4af0c0;
color: #4af0c0;
padding: 2px 8px;
cursor: pointer;
font-size: 11px;
">↻ Refresh</button>
<button id="sym-debug-close" style="
background: transparent;
border: none;
color: #4af0c0;
cursor: pointer;
font-size: 14px;
">✕</button>
</div>
</div>
<div class="sym-debug-content" style="padding: 12px;">
<!-- Active Symbols Section -->
<div class="sym-section" style="margin-bottom: 16px;">
<div class="sym-section-title" style="
color: #4af0c0;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
border-bottom: 1px solid rgba(74, 240, 192, 0.3);
padding-bottom: 4px;
">Active Symbols</div>
<div id="sym-debug-symbols" style="
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 12px;
"></div>
</div>
<!-- FSM States Section -->
<div class="sym-section" style="margin-bottom: 16px;">
<div class="sym-section-title" style="
color: #4af0c0;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
border-bottom: 1px solid rgba(74, 240, 192, 0.3);
padding-bottom: 4px;
">FSM States</div>
<div id="sym-debug-fsm" style="
display: flex;
flex-direction: column;
gap: 6px;
"></div>
</div>
<!-- Reasoning Log Section -->
<div class="sym-section" style="margin-bottom: 16px;">
<div class="sym-section-title" style="
color: #4af0c0;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
border-bottom: 1px solid rgba(74, 240, 192, 0.3);
padding-bottom: 4px;
">Reasoning Paths</div>
<div id="sym-debug-reasoning" style="
max-height: 150px;
overflow-y: auto;
font-size: 11px;
"></div>
</div>
<!-- Knowledge Graph Section -->
<div class="sym-section" style="margin-bottom: 16px;">
<div class="sym-section-title" style="
color: #4af0c0;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
border-bottom: 1px solid rgba(74, 240, 192, 0.3);
padding-bottom: 4px;
">Knowledge Graph</div>
<div id="sym-debug-kg-stats" style="margin-bottom: 8px; font-size: 11px;"></div>
<div id="sym-debug-kg-viz" style="
height: 100px;
background: rgba(0, 0, 0, 0.3);
border: 1px solid rgba(74, 240, 192, 0.2);
position: relative;
overflow: hidden;
"></div>
</div>
<!-- Performance Metrics Section -->
<div class="sym-section">
<div class="sym-section-title" style="
color: #4af0c0;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
border-bottom: 1px solid rgba(74, 240, 192, 0.3);
padding-bottom: 4px;
">Performance</div>
<div id="sym-debug-metrics" style="
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4px 12px;
font-size: 11px;
"></div>
</div>
</div>
`;
document.body.appendChild(div);
// Event listeners
document.getElementById('sym-debug-close').onclick = hide;
document.getElementById('sym-debug-refresh').onclick = update;
// Make draggable
let isDragging = false;
let dragOffsetX = 0;
let dragOffsetY = 0;
const header = div.querySelector('.sym-debug-header');
header.addEventListener('mousedown', (e) => {
isDragging = true;
dragOffsetX = e.clientX - div.offsetLeft;
dragOffsetY = e.clientY - div.offsetTop;
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
div.style.left = (e.clientX - dragOffsetX) + 'px';
div.style.top = (e.clientY - dragOffsetY) + 'px';
div.style.right = 'auto';
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
}
// ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function update() {
if (!_visible || !_overlay) return;
// Update symbols
_updateSymbols();
// Update FSM states
_updateFSM();
// Update reasoning log
_updateReasoning();
// Update knowledge graph
_updateKnowledgeGraph();
// Update metrics
_updateMetrics();
}
function _updateSymbols() {
const container = document.getElementById('sym-debug-symbols');
if (!container || !_engine) {
if (container) container.innerHTML = '<span style="color: #888;">No engine connected</span>';
return;
}
let html = '';
if (_engine.facts && _engine.facts.size > 0) {
for (const [key, value] of _engine.facts) {
const truthColor = value ? '#4af0c0' : '#ff4466';
const truthIcon = value ? '●' : '○';
html += `
<span style="color: #e0f0ff;">${_esc(key)}</span>
<span style="color: ${truthColor};">${truthIcon} ${_esc(String(value))}</span>
`;
}
} else {
html = '<span style="color: #888; grid-column: 1 / -1;">No active symbols</span>';
}
container.innerHTML = html;
}
function _updateFSM() {
const container = document.getElementById('sym-debug-fsm');
if (!container) return;
let html = '';
if (_fsmRegistry && _fsmRegistry.size > 0) {
for (const [agentId, fsm] of _fsmRegistry) {
const transitions = fsm.transitions ? Object.keys(fsm.transitions).length : 0;
html += `
<div style="
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 8px;
background: rgba(74, 240, 192, 0.05);
border-left: 2px solid #4af0c0;
">
<span style="color: #e0f0ff;">${_esc(agentId)}</span>
<span style="
color: #4af0c0;
font-size: 10px;
background: rgba(74, 240, 192, 0.1);
padding: 2px 6px;
border-radius: 2px;
">${_esc(fsm.state)}</span>
</div>
`;
}
} else if (_engine && _engine.fsm) {
// Single FSM mode
html += `
<div style="
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 8px;
background: rgba(74, 240, 192, 0.05);
border-left: 2px solid #4af0c0;
">
<span style="color: #e0f0ff;">Primary FSM</span>
<span style="
color: #4af0c0;
font-size: 10px;
background: rgba(74, 240, 192, 0.1);
padding: 2px 6px;
border-radius: 2px;
">${_esc(_engine.fsm.state)}</span>
</div>
`;
} else {
html = '<span style="color: #888;">No FSM registered</span>';
}
container.innerHTML = html;
}
function _updateReasoning() {
const container = document.getElementById('sym-debug-reasoning');
if (!container || !_engine) {
if (container) container.innerHTML = '<span style="color: #888;">No reasoning log</span>';
return;
}
let html = '';
if (_engine.reasoningLog && _engine.reasoningLog.length > 0) {
for (const entry of _engine.reasoningLog) {
const time = entry.timestamp
? new Date(entry.timestamp).toLocaleTimeString()
: '--:--:--';
html += `
<div style="
margin-bottom: 6px;
padding: 4px 6px;
background: rgba(74, 240, 192, 0.03);
border-left: 2px solid rgba(74, 240, 192, 0.3);
">
<div style="color: #888; font-size: 10px;">${time}</div>
<div style="color: #4af0c0;">${_esc(entry.rule || 'Unknown rule')}</div>
<div style="color: #e0f0ff;">→ ${_esc(entry.outcome || 'No outcome')}</div>
</div>
`;
}
} else {
html = '<span style="color: #888;">No reasoning paths recorded</span>';
}
container.innerHTML = html;
}
function _updateKnowledgeGraph() {
const statsContainer = document.getElementById('sym-debug-kg-stats');
const vizContainer = document.getElementById('sym-debug-kg-viz');
if (!statsContainer || !vizContainer) return;
if (!_kg) {
statsContainer.innerHTML = '<span style="color: #888;">No knowledge graph connected</span>';
vizContainer.innerHTML = '';
return;
}
const nodeCount = _kg.nodes ? _kg.nodes.size : 0;
const edgeCount = _kg.edges ? _kg.edges.length : 0;
statsContainer.innerHTML = `
<span style="color: #4af0c0;">${nodeCount}</span> nodes
<span style="color: #888;">|</span>
<span style="color: #4af0c0;">${edgeCount}</span> edges
`;
// Simple visualization
if (nodeCount > 0 && vizContainer) {
let vizHtml = '';
let idx = 0;
for (const [nodeId, node] of _kg.nodes) {
const x = 20 + (idx % 5) * 80;
const y = 20 + Math.floor(idx / 5) * 30;
const color = node.type === 'Agent' ? '#4af0c0' :
node.type === 'Location' ? '#ffaa22' : '#4488ff';
vizHtml += `
<div style="
position: absolute;
left: ${x}px;
top: ${y}px;
width: 8px;
height: 8px;
background: ${color};
border-radius: 50%;
box-shadow: 0 0 4px ${color};
" title="${_esc(nodeId)}"></div>
`;
idx++;
if (idx >= 15) break; // Limit visualization
}
vizContainer.innerHTML = vizHtml;
} else {
vizContainer.innerHTML = '';
}
}
function _updateMetrics() {
const container = document.getElementById('sym-debug-metrics');
if (!container) return;
let html = '';
// Engine metrics
if (_engine) {
const factCount = _engine.facts ? _engine.facts.size : 0;
const ruleCount = _engine.rules ? _engine.rules.length : 0;
html += `
<span style="color: #888;">Facts:</span> <span style="color: #4af0c0;">${factCount}</span>
<span style="color: #888;">Rules:</span> <span style="color: #4af0c0;">${ruleCount}</span>
`;
}
// Memory usage (rough estimate)
if (performance && performance.memory) {
const usedMB = Math.round(performance.memory.usedJSHeapSize / 1048576);
html += `
<span style="color: #888;">Heap:</span> <span style="color: #4af0c0;">${usedMB} MB</span>
`;
}
container.innerHTML = html || '<span style="color: #888;">No metrics available</span>';
}
// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
function show() {
if (!_overlay) return;
_overlay.style.display = 'block';
_visible = true;
update();
_startAutoRefresh();
}
function hide() {
if (!_overlay) return;
_overlay.style.display = 'none';
_visible = false;
_stopAutoRefresh();
}
function toggle() {
if (_visible) hide();
else show();
}
function isVisible() {
return _visible;
}
function _startAutoRefresh() {
if (_refreshInterval) return;
_refreshInterval = setInterval(update, 1000); // Update every second
}
function _stopAutoRefresh() {
if (_refreshInterval) {
clearInterval(_refreshInterval);
_refreshInterval = null;
}
}
function _esc(str) {
if (typeof str !== 'string') return String(str);
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
return {
init,
show,
hide,
toggle,
isVisible,
update,
};
})();
// Auto-export for module or global usage
if (typeof module !== 'undefined' && module.exports) {
module.exports = { SymbolicDebugger };
} else if (typeof window !== 'undefined') {
window.SymbolicDebugger = SymbolicDebugger;
}

269
performance-benchmark.js Normal file
View File

@@ -0,0 +1,269 @@
/**
* Performance Benchmark for The Nexus
*
* Runs automated performance tests and generates a report:
* - FPS stability test with 5+ agents
* - Draw call count validation
* - Frame time analysis
* - Memory usage tracking
*
* Usage:
* PerformanceBenchmark.run();
* PerformanceBenchmark.generateReport();
*/
const PerformanceBenchmark = (() => {
let _isRunning = false;
let _results = {
fps: [],
frameTime: [],
drawCalls: [],
timestamps: [],
agentCount: 0,
tier: 'unknown',
duration: 0
};
let _startTime = 0;
let _rafId = null;
function init() {
console.log('[PerformanceBenchmark] Initialized');
}
async function run(duration = 10000) {
if (_isRunning) return;
_isRunning = true;
console.log(`[PerformanceBenchmark] Starting ${duration}ms test...`);
// Show performance monitor
if (window.PerformanceMonitor) {
window.PerformanceMonitor.show();
}
// Get current tier
if (window.LODSystem) {
_results.tier = window.LODSystem.getPerformanceTier();
}
// Get agent count
if (window.agents) {
_results.agentCount = window.agents.length;
}
// Reset data
_results = {
fps: [],
frameTime: [],
drawCalls: [],
timestamps: [],
agentCount: _results.agentCount,
tier: _results.tier,
duration: duration
};
_startTime = performance.now();
return new Promise((resolve) => {
let lastTime = performance.now();
let frameCount = 0;
function measure() {
const now = performance.now();
const elapsed = now - _startTime;
if (elapsed >= duration) {
finish();
resolve(_results);
return;
}
// Calculate FPS
frameCount++;
if (now - lastTime >= 1000) {
const fps = Math.round((frameCount * 1000) / (now - lastTime));
_results.fps.push(fps);
_results.timestamps.push(Math.round(elapsed));
// Get draw calls
if (window.renderer && window.renderer.info) {
_results.drawCalls.push(window.renderer.info.render.calls);
}
frameCount = 0;
lastTime = now;
}
_rafId = requestAnimationFrame(measure);
}
measure();
});
}
function finish() {
_isRunning = false;
if (_rafId) cancelAnimationFrame(_rafId);
// Calculate statistics
const fps = _results.fps;
const avgFps = fps.reduce((a, b) => a + b, 0) / fps.length;
const minFps = Math.min(...fps);
const maxFps = Math.max(...fps);
_results.summary = {
averageFPS: Math.round(avgFps),
minFPS: minFps,
maxFPS: maxFps,
targetMet: avgFps >= 60,
stability: ((avgFps - minFps) / avgFps * 100).toFixed(1) + '%'
};
console.log('[PerformanceBenchmark] Complete:', _results.summary);
// Hide monitor
if (window.PerformanceMonitor) {
window.PerformanceMonitor.hide();
}
// Show results overlay
showResultsOverlay();
}
function showResultsOverlay() {
const div = document.createElement('div');
div.id = 'perf-benchmark-results';
div.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(10, 15, 26, 0.95);
border: 1px solid #00ffcc;
padding: 2rem;
border-radius: 8px;
color: #e0e0ff;
font-family: 'Orbitron', monospace;
z-index: 10001;
min-width: 300px;
`;
const s = _results.summary;
const targetStatus = s.targetMet
? '<span style="color: #00ffcc">✓ TARGET MET</span>'
: '<span style="color: #ff4444">✗ BELOW TARGET</span>';
div.innerHTML = `
<h3 style="margin: 0 0 1rem 0; color: #00ffcc;">Performance Benchmark</h3>
<div style="margin-bottom: 0.5rem;"><strong>Tier:</strong> ${_results.tier}</div>
<div style="margin-bottom: 0.5rem;"><strong>Agents:</strong> ${_results.agentCount}</div>
<div style="margin-bottom: 0.5rem;"><strong>Average FPS:</strong> ${s.averageFPS}</div>
<div style="margin-bottom: 0.5rem;"><strong>Min/Max FPS:</strong> ${s.minFPS} / ${s.maxFPS}</div>
<div style="margin-bottom: 0.5rem;"><strong>Stability:</strong> ${s.stability} variance</div>
<div style="margin: 1rem 0; padding: 0.5rem; background: rgba(0,0,0,0.3); border-radius: 4px;">
<strong>60 FPS Target:</strong> ${targetStatus}
</div>
<button onclick="this.parentElement.remove()" style="
background: #00ffcc;
color: #0a0f1a;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
font-family: inherit;
font-weight: bold;
">Close</button>
`;
document.body.appendChild(div);
}
function generateReport() {
const r = _results;
const s = r.summary || {};
const report = `
# The Nexus Performance Benchmark Report
**Date:** ${new Date().toISOString()}
**Duration:** ${r.duration}ms
**Performance Tier:** ${r.tier}
**Agent Count:** ${r.agentCount}
## Results
| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Average FPS | ${s.averageFPS || 'N/A'} | ≥ 60 | ${s.targetMet ? '✓ PASS' : '✗ FAIL'} |
| Minimum FPS | ${s.minFPS || 'N/A'} | ≥ 45 | ${(s.minFPS >= 45) ? '✓ PASS' : '✗ FAIL'} |
| Stability | ${s.stability || 'N/A'} | < 20% | ${parseFloat(s.stability) < 20 ? '✓ PASS' : '✗ FAIL'} |
## Hardware Requirements Met
${getHardwareRequirements(r)}
## Recommendations
${getRecommendations(r)}
`;
return report;
}
function getHardwareRequirements(results) {
const tier = results.tier;
const passed = results.summary?.targetMet;
if (passed) {
return `- Current hardware (${tier} tier) meets minimum sovereign requirements
- Suitable for deployment on similar hardware
- Consider lowering settings for mobile/integrated graphics`;
} else {
return `- Current hardware (${tier} tier) BELOW minimum requirements
- Recommend: M1 Mac or equivalent for 60 FPS
- Consider: Reduce agent count, disable shadows, lower resolution`;
}
}
function getRecommendations(results) {
const recs = [];
if (!results.summary?.targetMet) {
recs.push('- Enable LOD system if not active');
recs.push('- Reduce shadow map resolution or disable shadows');
recs.push('- Lower pixel ratio to 1.0');
recs.push('- Reduce agent draw distance');
}
if (results.drawCalls.some(c => c > 1000)) {
recs.push('- High draw call count detected - consider batching geometry');
}
if (results.agentCount < 5) {
recs.push('- Test with 5+ agents for full validation');
}
return recs.length ? recs.join('\n') : '- Performance optimal - no action required';
}
function downloadReport() {
const report = generateReport();
const blob = new Blob([report], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `nexus-performance-report-${Date.now()}.md`;
a.click();
URL.revokeObjectURL(url);
}
return {
init,
run,
generateReport,
downloadReport,
get results() { return _results; }
};
})();
window.PerformanceBenchmark = PerformanceBenchmark;

272
performance-monitor.js Normal file
View File

@@ -0,0 +1,272 @@
/**
* Performance Monitor for The Nexus
*
* Integrates Three.js Stats.js overlay with custom metrics:
* - FPS counter
* - Frame time (ms)
* - Draw calls
* - Agent LOD stats
*
* Usage:
* PerformanceMonitor.init();
* PerformanceMonitor.update(); // call in render loop
* PerformanceMonitor.show();
* PerformanceMonitor.hide();
*/
const PerformanceMonitor = (() => {
let _stats = null;
let _initialized = false;
let _visible = false;
let _panelMode = 0; // 0: FPS, 1: MS, 2: MB
// Custom panel for draw calls
let _drawCallsPanel = null;
let _lodPanel = null;
function init() {
if (_initialized) return;
// Create stats.js panels
_stats = new Stats();
_stats.showPanel(0); // 0: fps, 1: ms, 2: mb
_stats.dom.style.cssText = 'position:fixed;top:10px;left:10px;z-index:10000;';
_stats.dom.style.display = 'none'; // Hidden by default
// Add custom draw calls panel
_drawCallsPanel = _stats.addPanel(new Stats.Panel('DRAW', '#ff8', '#221'));
// Add custom LOD panel
_lodPanel = _stats.addPanel(new Stats.Panel('AGENTS', '#8ff', '#122'));
document.body.appendChild(_stats.dom);
_initialized = true;
// Add keyboard shortcut (Shift+P)
document.addEventListener('keydown', (e) => {
if (e.shiftKey && e.key === 'P') {
toggle();
}
if (_visible && e.key === ' ') {
e.preventDefault();
nextPanel();
}
});
console.log('[PerformanceMonitor] Initialized. Press Shift+P to toggle, Space to cycle panels.');
}
function show() {
if (!_initialized) init();
_stats.dom.style.display = 'block';
_visible = true;
}
function hide() {
if (_stats) {
_stats.dom.style.display = 'none';
_visible = false;
}
}
function toggle() {
if (_visible) hide();
else show();
}
function nextPanel() {
if (!_stats) return;
_panelMode = (_panelMode + 1) % 5;
_stats.showPanel(_panelMode);
}
function update(renderer, scene, camera) {
if (!_stats || !_visible) return;
_stats.begin();
// Update draw calls info
if (renderer && renderer.info) {
const info = renderer.info.render;
_drawCallsPanel.update(info.calls, 1000);
}
// Update LOD stats
if (window.LODSystem) {
const lodStats = window.LODSystem.getStats();
const total = lodStats.total || 1;
const active = lodStats.mesh + lodStats.sprite;
_lodPanel.update(active, total);
}
_stats.end();
}
function getSnapshot() {
const snapshot = {
timestamp: Date.now(),
fps: _stats ? _stats.fps : 0,
renderer: null,
lod: null
};
if (typeof renderer !== 'undefined' && renderer && renderer.info) {
snapshot.renderer = {
calls: renderer.info.render.calls,
triangles: renderer.info.render.triangles,
points: renderer.info.render.points,
lines: renderer.info.render.lines
};
}
if (window.LODSystem) {
snapshot.lod = window.LODSystem.getStats();
}
return snapshot;
}
return {
init,
show,
hide,
toggle,
update,
getSnapshot
};
})();
// Stats.js library (inline for self-containment)
// From: https://github.com/mrdoob/stats.js
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Stats = factory());
}(this, function() {
var Stats = function() {
var mode = 0;
var container = document.createElement('div');
container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
container.addEventListener('click', function(event) {
event.preventDefault();
showPanel(++mode % container.children.length);
}, false);
function addPanel(panel) {
container.appendChild(panel.dom);
return panel;
}
function showPanel(id) {
for (var i = 0; i < container.children.length; i++) {
container.children[i].style.display = i === id ? 'block' : 'none';
}
mode = id;
}
var beginTime = (performance || Date).now();
var prevTime = beginTime;
var frames = 0;
var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
if (self.performance && self.performance.memory) {
var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
}
showPanel(0);
return {
REVISION: 16,
dom: container,
addPanel: addPanel,
showPanel: showPanel,
begin: function() {
beginTime = (performance || Date).now();
},
end: function() {
frames++;
var time = (performance || Date).now();
msPanel.update(time - beginTime, 200);
if (time >= prevTime + 1000) {
fpsPanel.update((frames * 1000) / (time - prevTime), 100);
prevTime = time;
frames = 0;
if (memPanel) {
var memory = performance.memory;
memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
}
}
return time;
},
update: function() {
beginTime = this.end();
},
// Expose fps for getSnapshot
get fps() {
return fpsPanel ? fpsPanel._value : 0;
}
};
};
Stats.Panel = function(name, fg, bg) {
var min = Infinity, max = 0, round = Math.round;
var PR = round(window.devicePixelRatio || 1);
var WIDTH = 80 * PR, HEIGHT = 48 * PR,
TEXT_X = 3 * PR, TEXT_Y = 2 * PR,
GRAPH_X = 3 * PR, GRAPH_Y = 15 * PR,
GRAPH_WIDTH = 74 * PR, GRAPH_HEIGHT = 30 * PR;
var canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
canvas.style.cssText = 'width:80px;height:48px';
var context = canvas.getContext('2d');
context.font = 'bold ' + (9 * PR) + 'px Helvetica,Arial,sans-serif';
context.textBaseline = 'top';
context.fillStyle = bg;
context.fillRect(0, 0, WIDTH, HEIGHT);
context.fillStyle = fg;
context.fillText(name, TEXT_X, TEXT_Y);
context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
context.fillStyle = bg;
context.globalAlpha = 0.9;
context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
return {
dom: canvas,
_value: 0,
update: function(value, maxValue) {
this._value = value;
min = Math.min(min, value);
max = Math.max(max, value);
context.fillStyle = bg;
context.globalAlpha = 1;
context.fillRect(0, 0, WIDTH, GRAPH_Y);
context.fillStyle = fg;
context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
context.globalAlpha = 0.9;
context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
context.fillStyle = bg;
context.globalAlpha = 0.1;
context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
context.fillStyle = fg;
context.globalAlpha = 1;
context.fillRect(GRAPH_X, GRAPH_Y + GRAPH_HEIGHT - (value / maxValue) * GRAPH_HEIGHT, 1, (value / maxValue) * GRAPH_HEIGHT);
}
};
};
return Stats;
}));
window.PerformanceMonitor = PerformanceMonitor;

View File

@@ -200,6 +200,13 @@ canvas#nexus-canvas {
box-shadow: 0 0 20px var(--color-primary);
}
.hud-icon-btn.pov-active {
background: var(--color-gold);
border-color: var(--color-gold);
color: var(--color-bg);
box-shadow: 0 0 20px var(--color-gold);
}
.hud-status-item {
display: flex;
align-items: center;

View File

@@ -0,0 +1,255 @@
"""Unit tests for multi_user_bridge.py — session isolation and routing.
Refs: #1503
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# ── Constants ───────────────────────────────────────────────────────────────
PROJECT_ROOT = Path(__file__).parent.parent
# ── Fixture: patch heavy runtime dependencies BEFORE module import ──────────
@pytest.fixture(autouse=True)
def patch_runtime_deps(monkeypatch, tmp_path):
"""Prevent module-level side-effects by stubbing external deps before any import."""
tmp = tmp_path
# 1. Stub run_agent module with a fake AIAgent
fake_run_agent = MagicMock()
fake_agent = MagicMock()
fake_agent.model = "test-mock"
fake_agent.quiet_mode = True
fake_run_agent.AIAgent = MagicMock(return_value=fake_agent)
monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)
# 2. Set environment that multi_user_bridge reads at import time
fake_hermes = tmp / "hermes"
fake_hermes.mkdir()
fake_world = tmp / "world"
fake_world.mkdir()
(fake_world / "world_state.json").write_text(
'{"tick": 0, "rooms": {}, "time_of_day": "dawn"}'
)
monkeypatch.setenv("HERMES_PATH", str(fake_hermes))
# 3. Patch WORLD_DIR attribute that module computes at import
# We'll patch it after import via monkeypatch.setattr
monkeypatch.setattr("multi_user_bridge.WORLD_DIR", fake_world, raising=False)
# 4. Prevent world_tick_system.start() from spawning a daemon thread
# Patch at the class level before instantiation
from threading import Thread
monkeypatch.setattr(Thread, "start", lambda self: None)
# Ensure multi_user_bridge is cleared so next import is fresh with patches
if "multi_user_bridge" in sys.modules:
del sys.modules["multi_user_bridge"]
yield
# ── UserSession tests ───────────────────────────────────────────────────────
def test_user_session_creates_with_unique_id_and_room():
"""UserSession must initialise with provided identifiers."""
from multi_user_bridge import UserSession
session = UserSession(user_id="user-123", username="Alice", room="The Chapel")
assert session.user_id == "user-123"
assert session.username == "Alice"
assert session.room == "The Chapel"
assert isinstance(session.created_at, str)
assert isinstance(session.last_active, float)
assert session.messages == []
assert session.agent is not None # mocked agent created
def test_user_session_message_history_is_isolated():
"""Messages stored in one UserSession must not leak to another."""
from multi_user_bridge import UserSession
alice = UserSession(user_id="alice", username="Alice", room="The Threshold")
bob = UserSession(user_id="bob", username="Bob", room="The Threshold")
# Alice sends two messages
alice.messages.append({"role": "user", "content": "Hello from Alice"})
alice.messages.append({"role": "assistant", "content": "Hi Alice"})
# Bob sends one message
bob.messages.append({"role": "user", "content": "Greetings from Bob"})
# Isolation assertions
assert len(alice.messages) == 2
assert len(bob.messages) == 1
assert "Alice" in alice.messages[0]["content"]
assert "Bob" in bob.messages[0]["content"]
# Cross-check — Alice's history must not contain Bob's message
assert all("Bob" not in msg["content"] for msg in alice.messages)
assert all("Alice" not in msg["content"] for msg in bob.messages)
def test_user_session_multiple_instances_are_independent():
"""Multiple UserSession instances must not share mutable state."""
from multi_user_bridge import UserSession
sessions = [
UserSession(user_id=f"user-{i}", username=f"User{i}", room="The Threshold")
for i in range(5)
]
for i, s in enumerate(sessions):
s.messages.append({"role": "user", "content": f"msg-{i}"})
assert [len(s.messages) for s in sessions] == [1, 1, 1, 1, 1]
assert all(s.messages[0]["content"] == f"msg-{i}" for i, s in enumerate(sessions))
# ── SessionManager tests ────────────────────────────────────────────────────
def test_session_manager_get_or_create_returns_same_instance():
"""get_or_create must return the same UserSession for identical user_id."""
from multi_user_bridge import SessionManager
sm = SessionManager(max_sessions=10)
session1 = sm.get_or_create(user_id="alexander", username="Alexander")
session2 = sm.get_or_create(user_id="alexander", username="Alexander")
session3 = sm.get_or_create(user_id="alexander", username="DifferentName")
assert session1 is session2 # same object
assert session2 is session3 # same object
assert sm.get_session_count() == 1
def test_session_manager_respects_max_sessions():
"""When max_sessions is reached, the least-recently-active session must be evicted."""
from multi_user_bridge import SessionManager
sm = SessionManager(max_sessions=3)
# Create 3 sessions with deliberate timing
sm.get_or_create("user1", "User1")
time.sleep(0.01)
sm.get_or_create("user2", "User2")
time.sleep(0.01)
sm.get_or_create("user3", "User3")
assert sm.get_session_count() == 3
# Create 4th — should evict user1 (oldest)
sm.get_or_create("user4", "User4")
assert sm.get_session_count() == 3
# Re-adding user1 creates a fresh session (old was evicted)
new_user1 = sm.get_or_create("user1", "User1")
assert new_user1 is not None
sessions = sm.list_sessions()
user_ids = {s["user"] for s in sessions}
assert "User1" in user_ids # new one exists (username)
def test_session_manager_update_room_on_get_or_create():
"""Calling get_or_create with a different room must update session.room."""
from multi_user_bridge import SessionManager
sm = SessionManager()
session = sm.get_or_create("alice", "Alice", room="The Threshold")
assert session.room == "The Threshold"
# Later, Alice moves to the Chapel
session = sm.get_or_create("alice", "Alice", room="The Chapel")
assert session.room == "The Chapel"
def test_session_manager_list_sessions_returns_active():
"""list_sessions must return all currently active UserSession summaries."""
from multi_user_bridge import SessionManager
sm = SessionManager()
sm.get_or_create("user1", "User1", room="Room A")
sm.get_or_create("user2", "User2", room="Room B")
sessions = sm.list_sessions()
user_ids = {s["user"] for s in sessions}
assert user_ids == {"User1", "User2"}
# ── BridgeHandler request routing tests ────────────────────────────────────
def test_bridge_handler_health_endpoint_returns_status():
"""GET /bridge/health must return JSON with active_sessions count."""
from multi_user_bridge import BridgeHandler
class MockRequest:
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
import io
return io.BytesIO(b"")
handler = BridgeHandler(
request=MockRequest("/bridge/health"),
client_address=("127.0.0.1", 0),
server=MagicMock(),
)
handler.path = "/bridge/health"
captured = {}
def mock_json_response(data):
captured["data"] = data
handler._json_response = mock_json_response
handler.do_GET()
assert captured["data"]["status"] == "ok"
assert "active_sessions" in captured["data"]
def test_bridge_handler_sessions_endpoint_lists_active():
"""GET /bridge/sessions must list active sessions."""
from multi_user_bridge import BridgeHandler
class MockRequest:
def __init__(self, path):
self.path = path
def makefile(self, *args, **kwargs):
import io
return io.BytesIO(b"")
handler = BridgeHandler(
request=MockRequest("/bridge/sessions"),
client_address=("127.0.0.1", 0),
server=MagicMock(),
)
handler.path = "/bridge/sessions"
captured = {}
def mock_json_response(data):
captured["data"] = data
handler._json_response = mock_json_response
handler.do_GET()
assert "sessions" in captured["data"]
# ── Smoke / sanity test ─────────────────────────────────────────────────────
def test_multi_user_bridge_module_imports_cleanly():
"""multi_user_bridge must be importable with all runtime deps patched."""
from multi_user_bridge import UserSession, SessionManager, BridgeHandler, session_manager
assert UserSession is not None
assert SessionManager is not None
assert BridgeHandler is not None
assert session_manager is not None

View File

@@ -1,95 +0,0 @@
/**
* Tests for SymbolicDebugger component (issue #871)
*/
import { SymbolicDebugger } from '../nexus/components/symbolic-debugger.js';
import { SymbolicEngine, AgentFSM, KnowledgeGraph } from '../nexus/symbolic-engine.js';
// Mock DOM for Node.js testing
if (typeof document === 'undefined') {
const mockElements = new Map();
global.document = {
createElement: (tag) => {
const el = {
tagName: tag,
style: {},
innerHTML: '',
children: [],
appendChild: function(child) { this.children.push(child); return child; },
prepend: function(child) { this.children.unshift(child); return child; },
querySelector: () => null,
querySelectorAll: () => [],
addEventListener: () => {},
setAttribute: () => {},
getAttribute: () => null,
};
return el;
},
body: {
appendChild: (el) => {
mockElements.set(el.id, el);
return el;
}
},
addEventListener: () => {},
getElementById: (id) => mockElements.get(id) || {
style: {},
innerHTML: '',
onclick: null,
addEventListener: () => {},
},
};
global.window = { SymbolicDebugger: null };
}
function assert(condition, message) {
if (!condition) {
console.error(`❌ FAILED: ${message}`);
process.exit(1);
}
console.log(`✔ PASSED: ${message}`);
}
console.log('--- Running Symbolic Debugger Tests ---');
// Test 1: Module exports
assert(typeof SymbolicDebugger === 'object', 'SymbolicDebugger exports an object');
assert(typeof SymbolicDebugger.init === 'function', 'SymbolicDebugger has init method');
assert(typeof SymbolicDebugger.show === 'function', 'SymbolicDebugger has show method');
assert(typeof SymbolicDebugger.hide === 'function', 'SymbolicDebugger has hide method');
assert(typeof SymbolicDebugger.toggle === 'function', 'SymbolicDebugger has toggle method');
assert(typeof SymbolicDebugger.update === 'function', 'SymbolicDebugger has update method');
// Test 2: Initial state
assert(SymbolicDebugger.isVisible() === false, 'Debugger starts hidden');
// Test 3: Engine integration (mock)
const mockEngine = {
facts: new Map([['energy', 75], ['stable', true]]),
rules: [{ condition: () => true, action: () => 'test' }],
reasoningLog: [
{ timestamp: Date.now(), rule: 'TestRule', outcome: 'TestOutcome' }
]
};
SymbolicDebugger.init({ engine: mockEngine });
assert(true, 'Debugger initializes with engine');
// Test 4: FSM integration
const mockFSM = { state: 'IDLE', transitions: { IDLE: [] } };
SymbolicDebugger.init({ engine: mockEngine, fsmRegistry: new Map([['Agent1', mockFSM]]) });
assert(true, 'Debugger initializes with FSM registry');
// Test 5: Knowledge Graph integration
const mockKG = {
nodes: new Map([
['A', { id: 'A', type: 'Agent' }],
['B', { id: 'B', type: 'Location' }]
]),
edges: [{ from: 'A', to: 'B', relation: 'AT' }]
};
SymbolicDebugger.init({ engine: mockEngine, knowledgeGraph: mockKG });
assert(true, 'Debugger initializes with Knowledge Graph');
console.log('--- All Symbolic Debugger Tests Passed ---');

263
texture-optimizer.js Normal file
View File

@@ -0,0 +1,263 @@
/**
* Texture Optimizer for The Nexus
*
* Provides utilities for texture compression and optimization:
* - WebP fallback for browser compatibility
* - Texture size limits based on performance tier
* - Mipmap generation control
* - Memory budget tracking
*
* Usage:
* const tex = TextureOptimizer.load('./assets/texture.png');
* TextureOptimizer.compressTexture(tex, { maxSize: 512, format: 'webp' });
*/
const TextureOptimizer = (() => {
// Size limits by performance tier (max texture dimension)
const SIZE_LIMITS = {
low: 512,
medium: 1024,
high: 2048
};
// Memory budget in MB
const MEMORY_BUDGETS = {
low: 64,
medium: 128,
high: 256
};
let _currentTier = 'medium';
let _textureMemory = 0;
let _textures = new Set();
function detectTier() {
const gl = document.createElement('canvas').getContext('webgl');
if (!gl) return 'low';
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
if (!debugInfo) return 'medium';
const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
if (renderer.includes('Apple')) {
return renderer.includes('M3') || renderer.includes('M2 Pro') || renderer.includes('M1 Pro')
? 'high' : 'medium';
}
if (renderer.includes('Intel') && !renderer.includes('Arc')) return 'low';
if (/Android|webOS|iPhone|iPad|iPod/i.test(navigator.userAgent)) return 'low';
return 'high';
}
function init() {
_currentTier = detectTier();
console.log(`[TextureOptimizer] Tier: ${_currentTier}, Max texture size: ${SIZE_LIMITS[_currentTier]}px`);
}
/**
* Load a texture with automatic optimization
*/
function load(url, options = {}) {
const loader = new THREE.TextureLoader();
const texture = loader.load(url, (tex) => {
optimizeTexture(tex, options);
});
_textures.add(texture);
return texture;
}
/**
* Optimize an existing texture
*/
function optimizeTexture(texture, options = {}) {
const maxSize = options.maxSize || SIZE_LIMITS[_currentTier];
const format = options.format || 'auto';
// Limit texture size
const width = texture.image?.width || texture.image?.videoWidth || 0;
const height = texture.image?.height || texture.image?.videoHeight || 0;
if (width > maxSize || height > maxSize) {
const scale = maxSize / Math.max(width, height);
const newWidth = Math.floor(width * scale);
const newHeight = Math.floor(height * scale);
// Create resized canvas
const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(texture.image, 0, 0, newWidth, newHeight);
texture.image = canvas;
texture.needsUpdate = true;
console.log(`[TextureOptimizer] Resized texture from ${width}x${height} to ${newWidth}x${newHeight}`);
}
// Mipmap settings based on tier
if (_currentTier === 'low') {
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;
} else if (_currentTier === 'medium') {
texture.generateMipmaps = true;
texture.minFilter = THREE.LinearMipmapLinearFilter;
}
// Anisotropic filtering
if (options.anisotropy !== undefined) {
texture.anisotropy = options.anisotropy;
} else if (_currentTier === 'low') {
texture.anisotropy = 1;
} else if (_currentTier === 'medium') {
texture.anisotropy = 4;
} else {
texture.anisotropy = 8;
}
// Format conversion hint (for server-side preprocessing)
if (format === 'webp' && !urlEndsWith(texture.image?.src, '.webp')) {
console.warn(`[TextureOptimizer] Consider converting to WebP: ${texture.image?.src}`);
}
// Track memory usage
trackMemory(texture);
return texture;
}
function urlEndsWith(url, suffix) {
return url && url.toLowerCase().endsWith(suffix);
}
function trackMemory(texture) {
const width = texture.image?.width || 0;
const height = texture.image?.height || 0;
const bytesPerPixel = 4; // RGBA
const mipmaps = texture.generateMipmaps ? 1.33 : 1; // Mipmaps add ~33%
const memoryMB = (width * height * bytesPerPixel * mipmaps) / (1024 * 1024);
_textureMemory += memoryMB;
texture.userData.memoryMB = memoryMB;
const budget = MEMORY_BUDGETS[_currentTier];
if (_textureMemory > budget) {
console.warn(`[TextureOptimizer] Memory budget exceeded: ${_textureMemory.toFixed(1)}MB / ${budget}MB`);
cleanupTextures();
}
}
function cleanupTextures() {
const budget = MEMORY_BUDGETS[_currentTier];
if (_textureMemory <= budget) return;
// Sort by last used time (if available)
const sorted = Array.from(_textures).sort((a, b) => {
return (a.userData.lastUsed || 0) - (b.userData.lastUsed || 0);
});
for (const tex of sorted) {
if (_textureMemory <= budget * 0.8) break;
if (tex.userData.memoryMB) {
_textureMemory -= tex.userData.memoryMB;
tex.dispose();
_textures.delete(tex);
}
}
console.log(`[TextureOptimizer] Cleaned up textures. Memory: ${_textureMemory.toFixed(1)}MB`);
}
function getMemoryUsage() {
return {
used: _textureMemory,
budget: MEMORY_BUDGETS[_currentTier],
count: _textures.size
};
}
/**
* Audit all textures in a scene
*/
function auditScene(scene) {
const audit = {
textures: [],
totalMemory: 0,
oversized: [],
uncompressed: []
};
scene.traverse((object) => {
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
materials.forEach(mat => {
['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap'].forEach(mapType => {
const texture = mat[mapType];
if (texture && texture.image) {
const width = texture.image.width || 0;
const height = texture.image.height || 0;
const memoryMB = (width * height * 4) / (1024 * 1024);
audit.textures.push({
type: mapType,
size: `${width}x${height}`,
memoryMB: memoryMB.toFixed(2),
url: texture.image.src || 'generated'
});
audit.totalMemory += memoryMB;
if (width > SIZE_LIMITS[_currentTier] || height > SIZE_LIMITS[_currentTier]) {
audit.oversized.push({
type: mapType,
size: `${width}x${height}`,
limit: SIZE_LIMITS[_currentTier]
});
}
const src = texture.image.src || '';
if (src && !src.endsWith('.webp') && !src.endsWith('.ktx2') && !src.endsWith('.basis')) {
audit.uncompressed.push(src);
}
}
});
});
}
});
return audit;
}
/**
* Convert image to WebP (client-side, for runtime generated textures)
*/
async function convertToWebP(imageElement, quality = 0.85) {
const canvas = document.createElement('canvas');
canvas.width = imageElement.width;
canvas.height = imageElement.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(imageElement, 0, 0);
return new Promise((resolve) => {
canvas.toBlob((blob) => {
resolve(blob);
}, 'image/webp', quality);
});
}
return {
init,
load,
optimizeTexture,
getMemoryUsage,
auditScene,
convertToWebP,
SIZE_LIMITS,
MEMORY_BUDGETS
};
})();
window.TextureOptimizer = TextureOptimizer;