Compare commits

..

3 Commits

Author SHA1 Message Date
b87e83875e Merge branch 'main' into fix/1644
Some checks failed
Review Approval Gate / verify-review (pull_request) Failing after 10s
CI / test (pull_request) Failing after 1m8s
CI / validate (pull_request) Failing after 1m14s
2026-04-22 01:10:48 +00:00
e2299514b1 Merge branch 'main' into fix/1644
Some checks failed
Review Approval Gate / verify-review (pull_request) Failing after 9s
CI / test (pull_request) Failing after 1m11s
CI / validate (pull_request) Failing after 1m16s
2026-04-22 01:08:59 +00:00
Alexander Whitestone
c2003e258f docs: restore GENOME.md codebase architecture map (#1644)
Some checks failed
CI / test (pull_request) Failing after 51s
CI / validate (pull_request) Failing after 50s
Review Approval Gate / verify-review (pull_request) Failing after 8s
Restores the missing GENOME.md file which provides a comprehensive
map of the Nexus codebase for developers and AI agents.

## Contents
- Overview and key stats
- Architecture diagram
- Frontend systems (3D world, GOFAI, memory, audio)
- Backend services (WebSocket, scripts, tools)
- Data files and configuration
- Testing instructions
- Key patterns (component, WebSocket, portal schema)
- Security summary
- Related repos
- Quick start guide

Closes #1644
2026-04-20 19:16:52 -04:00
8 changed files with 235 additions and 199 deletions

234
GENOME.md Normal file
View File

@@ -0,0 +1,234 @@
# GENOME.md — The Nexus Codebase Architecture Map
**Generated**: 2026-04-20
**Repository**: Timmy_Foundation/the-nexus
**Purpose**: Comprehensive map of the Nexus codebase for developers and AI agents.
---
## Overview
The Nexus is Timmy's canonical 3D/world repository — a sovereign AI agent visualization surface and local-first training ground. It combines a Three.js 3D browser world with Python cognition components, WebSocket bridges, and fleet orchestration tools.
**Key Stats**:
- ~357 source files
- 201 Python files
- 23 JavaScript files
- 107 Markdown docs
- 24 Shell scripts
---
## Architecture
```
the-nexus/
├── app.js # Main Three.js 3D world (frontend entry)
├── index.html # HTML shell
├── style.css # Global styles
├── server.py # WebSocket gateway
├── gofai_worker.js # GOFAI web worker
├── portals.json # Portal registry
├── vision.json # Vision points config
├── provenance.json # File integrity hashes
├── nexus/ # Python cognition layer
│ ├── components/ # Frontend JS modules
│ ├── mnemosyne/ # Memory system
│ ├── mempalace/ # Long-term memory
│ └── symbolic-engine.js # GOFAI rules
├── scripts/ # Operational scripts
├── bin/ # CLI tools
├── tests/ # Test suite
├── docs/ # Documentation
└── config/ # Configuration files
```
---
## Frontend (Browser World)
### Entry Points
| File | Purpose |
|------|---------|
| `index.html` | HTML shell, HUD layout |
| `app.js` | Main Three.js app (~141K lines) |
| `style.css` | All styles (~61K) |
| `gofai_worker.js` | Off-thread GOFAI reasoning |
### Core Systems
| System | File | Description |
|--------|------|-------------|
| 3D World | `app.js` | Three.js scene, camera, rendering |
| GOFAI | `app.js` | Symbolic rules, blackboard, planner |
| Memory | `nexus/components/spatial-memory.js` | 3D memory crystals |
| Audio | `nexus/components/spatial-audio.js` | Spatial sound system |
| Portals | `portals.json` | External service links |
| Chat | `app.js` | Chat panel and messaging |
| HUD | `app.js` + `style.css` | Heads-up display |
### Components (`nexus/components/`)
| Component | Purpose |
|-----------|---------|
| `spatial-memory.js` | 3D memory crystal visualization |
| `spatial-audio.js` | Spatial sound for memories |
| `memory-birth.js` | Memory creation animation |
| `memory-pulse.js` | BFS pulse wave on click |
| `memory-inspect.js` | Memory detail panel |
| `memory-connections.js` | Connection graph |
| `memory-particles.js` | Particle effects |
| `memory-optimizer.js` | Memory cleanup |
| `session-rooms.js` | Evennia room snapshots |
| `timeline-scrubber.js` | Time navigation |
| `resonance-visualizer.js` | Pattern visualization |
| `portal-health-check.js` | Portal status monitoring |
| `spatial-chat.js` | 3D audio chat notifications |
---
## Backend (Python)
### Core Services
| File | Purpose |
|------|---------|
| `server.py` | WebSocket gateway for real-time comms |
| `multi_user_bridge.py` | Multi-user MUD bridge |
| `gitea_api/` | Gitea API helpers |
### Scripts (`scripts/`)
| Script | Purpose |
|--------|---------|
| `cleanup-duplicate-prs.sh` | Close duplicate PRs |
| `check-existing-prs.sh` | Pre-flight PR check |
| `pr_backlog_analyzer.py` | PR backlog analysis |
| `audit_mempalace_privacy.py` | Privacy audit |
| `provision-runner.sh` | Runner setup |
| `runner_health_probe.sh` | Health monitoring |
### Bin Tools (`bin/`)
| Tool | Purpose |
|------|---------|
| `enforce_branch_protection.py` | Branch protection enforcement |
| `check_duplicate_milestones.py` | Milestone cleanup |
| `generate_provenance.py` | Provenance hash generation |
---
## Data Files
| File | Format | Purpose |
|------|--------|---------|
| `portals.json` | JSON | Portal registry (8 portals) |
| `vision.json` | JSON | Vision points |
| `world_state.json` | JSON | World state snapshot |
| `provenance.json` | JSON | File integrity hashes |
| `manifest.json` | JSON | PWA manifest |
---
## Configuration
| File | Purpose |
|------|---------|
| `.gitea/branch-protection/` | Branch protection rules |
| `.github/workflows/` | CI/CD workflows |
| `config/` | Runtime configuration |
| `pytest.ini` | Test configuration |
---
## Testing
| Directory | Coverage |
|-----------|----------|
| `tests/` | Unit and integration tests |
| `tests/test_provenance.py` | File integrity tests |
| `tests/test_spatial_search.js` | Spatial search tests |
Run tests:
```bash
python3 -m pytest tests/ -v
node --test tests/*.js
```
---
## Key Patterns
### Component Pattern
```javascript
const ComponentName = (() => {
let _state = null;
function init(config) { ... }
function update(delta) { ... }
return { init, update };
})();
export { ComponentName };
```
### WebSocket Pattern
```python
async def handler(websocket):
async for message in websocket:
# Process and broadcast
pass
```
### Portal Schema
```json
{
"id": "portal-id",
"name": "Display Name",
"portal_type": "game-world",
"destination": { "url": "...", "type": "harness" }
}
```
---
## Security
- WebSocket gateway binds to `127.0.0.1` by default
- Optional token authentication via `NEXUS_WS_TOKEN`
- Rate limiting on connections and messages
- Branch protection on `main`
- Provenance hash verification
See `SECURITY.md` for full details.
---
## Related Repos
| Repo | Relationship |
|------|--------------|
| `timmy-config` | Configuration and fleet management |
| `hermes-agent` | Agent runtime |
| `timmy-home` | SOUL.md and core docs |
| `the-door` | Crisis detection system |
---
## Quick Start
```bash
# Clone
git clone https://forge.alexanderwhitestone.com/Timmy_Foundation/the-nexus.git
# Run WebSocket gateway
python3 server.py
# Open browser world
open index.html
# Run tests
python3 -m pytest tests/
```
---
*This GENOME.md is auto-maintained. Update when adding major new systems.*

3
app.js
View File

@@ -734,9 +734,6 @@ async function init() {
const response = await fetch('./portals.json');
const portalData = await response.json();
createPortals(portalData);
// Start portal hot-reload watcher
if (window.PortalHotReload) PortalHotReload.start(5000);
} catch (e) {
console.error('Failed to load portals.json:', e);
addChatMessage('error', 'Portal registry offline. Check logs.');

View File

@@ -1,13 +0,0 @@
.avatar-name-tag{position:fixed;transform:translate(-50%,-100%);background:rgba(0,0,0,0.7);color:#00ffcc;font-family:'JetBrains Mono',monospace;font-size:12px;padding:2px 8px;border-radius:4px;border:1px solid rgba(0,255,204,0.3);pointer-events:none;z-index:100;white-space:nowrap;text-shadow:0 0 6px rgba(0,255,204,0.5)}
.avatar-color-picker{position:fixed;top:60px;right:16px;background:rgba(10,15,26,0.95);border:1px solid rgba(0,255,204,0.3);border-radius:8px;padding:12px;z-index:1000;min-width:200px;font-family:'JetBrains Mono',monospace;color:#e0e0e0}
.avatar-color-picker.hidden{display:none}
.avatar-picker-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;font-size:14px;color:#00ffcc}
.avatar-picker-close{background:none;border:none;color:#666;font-size:18px;cursor:pointer}
.avatar-picker-name{margin-bottom:12px}
.avatar-picker-name label{display:block;font-size:10px;color:#666;text-transform:uppercase;margin-bottom:4px}
.avatar-picker-name input{width:100%;background:rgba(255,255,255,0.05);border:1px solid rgba(0,255,204,0.2);border-radius:4px;color:#e0e0e0;padding:6px 8px;font-family:inherit;font-size:13px;outline:none}
.avatar-picker-colors label{display:block;font-size:10px;color:#666;text-transform:uppercase;margin-bottom:6px}
.avatar-color-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}
.avatar-color-swatch{width:36px;height:36px;border-radius:50%;border:2px solid transparent;cursor:pointer;transition:border-color 0.15s,transform 0.15s}
.avatar-color-swatch:hover{transform:scale(1.15)}
.avatar-color-swatch.active{border-color:white;box-shadow:0 0 8px currentColor}

View File

@@ -1,38 +0,0 @@
const AvatarCustomization = (() => {
let avatarMesh = null, nameTagDiv = null, colorPickerPanel = null;
let currentColor = '#00ffcc', currentName = 'Visitor', _scene = null, _camera = null;
const STORAGE_KEY = 'nexus-avatar-prefs';
const PRESET_COLORS = [
{name:'Teal',hex:'#00ffcc'},{name:'Cyan',hex:'#00ccff'},{name:'Purple',hex:'#9966ff'},
{name:'Pink',hex:'#ff66aa'},{name:'Orange',hex:'#ff8833'},{name:'Gold',hex:'#ffcc00'},
{name:'Red',hex:'#ff3333'},{name:'Green',hex:'#33ff66'},
];
function loadPrefs(){try{const r=localStorage.getItem(STORAGE_KEY);if(r){const p=JSON.parse(r);if(p.color)currentColor=p.color;if(p.name)currentName=p.name;}}catch(e){}}
function savePrefs(){try{localStorage.setItem(STORAGE_KEY,JSON.stringify({color:currentColor,name:currentName}));}catch(e){}}
function createAvatarMesh(color){
const geo=new THREE.CapsuleGeometry(0.3,0.8,8,16);
const mat=new THREE.MeshStandardMaterial({color:new THREE.Color(color),emissive:new THREE.Color(color).multiplyScalar(0.3),metalness:0.3,roughness:0.5});
const mesh=new THREE.Mesh(geo,mat);mesh.position.set(0,1.2,0);mesh.castShadow=true;return mesh;
}
function updateAvatarColor(hex){
currentColor=hex;if(avatarMesh){avatarMesh.material.color.set(hex);avatarMesh.material.emissive.set(new THREE.Color(hex).multiplyScalar(0.3));}
document.querySelectorAll('.avatar-color-swatch').forEach(el=>el.classList.toggle('active',el.dataset.color===hex));savePrefs();
}
function createNameTag(name){const d=document.createElement('div');d.className='avatar-name-tag';d.textContent=name;document.body.appendChild(d);return d;}
function updateNameTagPosition(){if(!nameTagDiv||!_camera)return;const pos=new THREE.Vector3(0,2.4,0);if(avatarMesh&&avatarMesh.parent)pos.add(avatarMesh.parent.position);pos.project(_camera);const x=(pos.x*0.5+0.5)*window.innerWidth;const y=(-pos.y*0.5+0.5)*window.innerHeight;nameTagDiv.style.left=x+'px';nameTagDiv.style.top=y+'px';nameTagDiv.style.display=pos.z<1?'block':'none';}
function updateNameTagText(name){currentName=name;if(nameTagDiv)nameTagDiv.textContent=name;savePrefs();}
function createColorPicker(){
const panel=document.createElement('div');panel.id='avatar-color-picker';panel.className='avatar-color-picker hidden';
panel.innerHTML='<div class="avatar-picker-header"><span>Avatar</span><button class="avatar-picker-close">&times;</button></div><div class="avatar-picker-name"><label>Name</label><input type="text" id="avatar-name-input" maxlength="20" placeholder="Your name" /></div><div class="avatar-picker-colors"><label>Color</label><div class="avatar-color-grid">'+PRESET_COLORS.map(c=>'<button class="avatar-color-swatch '+(c.hex===currentColor?'active':'')+'" data-color="'+c.hex+'" style="background:'+c.hex+'" title="'+c.name+'"></button>').join('')+'</div></div>';
document.body.appendChild(panel);
panel.querySelector('.avatar-picker-close').addEventListener('click',()=>panel.classList.add('hidden'));
panel.querySelectorAll('.avatar-color-swatch').forEach(el=>el.addEventListener('click',()=>updateAvatarColor(el.dataset.color)));
const ni=panel.querySelector('#avatar-name-input');ni.value=currentName;ni.addEventListener('input',(e)=>updateNameTagText(e.target.value||'Visitor'));
return panel;
}
function toggleColorPicker(){if(!colorPickerPanel)return;colorPickerPanel.classList.toggle('hidden');const ni=colorPickerPanel.querySelector('#avatar-name-input');if(ni&&!colorPickerPanel.classList.contains('hidden')){ni.value=currentName;ni.focus();}}
function update(playerPos){if(!avatarMesh)return;avatarMesh.position.set(playerPos.x,playerPos.y-0.8,playerPos.z);updateNameTagPosition();}
function init(sceneRef,cameraRef){_scene=sceneRef;_camera=cameraRef;loadPrefs();avatarMesh=createAvatarMesh(currentColor);_scene.add(avatarMesh);nameTagDiv=createNameTag(currentName);colorPickerPanel=createColorPicker();const h=document.querySelector('.hud-top-right');if(h){const b=document.createElement('button');b.id='avatar-customize-btn';b.className='hud-icon-btn';b.title='Customize Avatar';b.innerHTML='<span class="hud-icon">🎨</span>';b.addEventListener('click',toggleColorPicker);h.insertBefore(b,h.firstChild);}console.log('[AvatarCustomization] Initialized —',currentColor,currentName);}
return{init,update,setColor:updateAvatarColor,setName:updateNameTagText,toggleColorPicker};
})();
window.AvatarCustomization=AvatarCustomization;

View File

@@ -23,7 +23,6 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="./avatar-customization.css">
<link rel="manifest" href="./manifest.json">
<script type="importmap">
{
@@ -398,7 +397,6 @@
<script src="./boot.js"></script>
<script src="./avatar-customization.js"></script>
<script src="./lod-system.js"></script>
<script src="./portal-hot-reload.js"></script>
<script>
function openMemoryFilter() { renderFilterList(); document.getElementById('memory-filter').style.display = 'flex'; }
function closeMemoryFilter() { document.getElementById('memory-filter').style.display = 'none'; }

View File

@@ -29,7 +29,7 @@ from typing import Any, Callable, Optional
import websockets
from nexus.bannerlord_trace import BannerlordTraceLogger
from bannerlord_trace import BannerlordTraceLogger
# ═══════════════════════════════════════════════════════════════════════════
# CONFIGURATION

View File

@@ -304,43 +304,6 @@ async def inject_event(event_type: str, ws_url: str, **kwargs):
sys.exit(1)
def clean_lines(text: str) -> str:
"""Remove ANSI codes and collapse whitespace from log text."""
import re
text = strip_ansi(text)
text = re.sub(r'\s+', ' ', text).strip()
return text
def normalize_event(event: dict) -> dict:
"""Normalize an Evennia event dict to standard format."""
return {
"type": event.get("type", "unknown"),
"actor": event.get("actor", event.get("name", "")),
"room": event.get("room", event.get("location", "")),
"message": event.get("message", event.get("text", "")),
"timestamp": event.get("timestamp", ""),
}
def parse_room_output(text: str) -> dict:
"""Parse Evennia room output into structured data."""
import re
lines = text.strip().split("\n")
result = {"name": "", "description": "", "exits": [], "objects": []}
if lines:
result["name"] = strip_ansi(lines[0]).strip()
if len(lines) > 1:
result["description"] = strip_ansi(lines[1]).strip()
for line in lines[2:]:
line = strip_ansi(line).strip()
if line.startswith("Exits:"):
result["exits"] = [e.strip() for e in line[6:].split(",") if e.strip()]
elif line.startswith("You see:"):
result["objects"] = [o.strip() for o in line[8:].split(",") if o.strip()]
return result
def main():
parser = argparse.ArgumentParser(description="Evennia -> Nexus WebSocket Bridge")
sub = parser.add_subparsers(dest="mode")

View File

@@ -1,105 +0,0 @@
/**
* Portal Hot-Reload for The Nexus
*
* Watches portals.json for changes and hot-reloads portal list
* without server restart. Existing connections unaffected.
*
* Usage:
* PortalHotReload.start(intervalMs);
* PortalHotReload.stop();
* PortalHotReload.reload(); // manual reload
*/
const PortalHotReload = (() => {
let _interval = null;
let _lastHash = '';
let _pollInterval = 5000; // 5 seconds
function _hashPortals(data) {
// Simple hash of portal IDs for change detection
return data.map(p => p.id || p.name).sort().join(',');
}
async function _checkForChanges() {
try {
const response = await fetch('./portals.json?t=' + Date.now());
if (!response.ok) return;
const data = await response.json();
const hash = _hashPortals(data);
if (hash !== _lastHash) {
console.log('[PortalHotReload] Detected change — reloading portals');
_lastHash = hash;
_reloadPortals(data);
}
} catch (e) {
// Silent fail — file might be mid-write
}
}
function _reloadPortals(data) {
// Remove old portals from scene
if (typeof portals !== 'undefined' && Array.isArray(portals)) {
portals.forEach(p => {
if (p.group && typeof scene !== 'undefined' && scene) {
scene.remove(p.group);
}
});
portals.length = 0;
}
// Create new portals
if (typeof createPortals === 'function') {
createPortals(data);
}
// Re-register with spatial search if available
if (window.SpatialSearch && typeof portals !== 'undefined') {
portals.forEach(p => {
if (p.config && p.config.name && p.group) {
SpatialSearch.register('portal', p, p.config.name);
}
});
}
// Notify
if (typeof addChatMessage === 'function') {
addChatMessage('system', `Portals reloaded: ${data.length} portals active`);
}
console.log(`[PortalHotReload] Reloaded ${data.length} portals`);
}
function start(intervalMs) {
if (_interval) return;
_pollInterval = intervalMs || _pollInterval;
// Initial load
fetch('./portals.json').then(r => r.json()).then(data => {
_lastHash = _hashPortals(data);
}).catch(() => {});
_interval = setInterval(_checkForChanges, _pollInterval);
console.log(`[PortalHotReload] Watching portals.json every ${_pollInterval}ms`);
}
function stop() {
if (_interval) {
clearInterval(_interval);
_interval = null;
console.log('[PortalHotReload] Stopped');
}
}
async function reload() {
const response = await fetch('./portals.json?t=' + Date.now());
const data = await response.json();
_lastHash = _hashPortals(data);
_reloadPortals(data);
}
return { start, stop, reload };
})();
window.PortalHotReload = PortalHotReload;