Skip to content

Bevy scene system, snapshot capture, persona tile genome heatmap - #295

Merged
joelteply merged 25 commits into
mainfrom
feature/bevy-scene-system
Mar 11, 2026
Merged

joelteply merged 25 commits into
mainfrom
feature/bevy-scene-system

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • Scene system: Asset-based room environments with identity-hash deterministic selection, 3-point portrait lighting, SceneInstanceReady RenderLayer propagation, data-driven AnimationProfile/AnimationConfig
  • Snapshot capture: Time-based SnapshotTracker with anti-burst protection (2s cooldown), single-flight GPU bridge capture via temporary Readback insertion
  • Persona tile: Fixed 4 genome slots with continuous heatmap coloring (maturity → color + height), removed silent error swallowing, model badge from provider alone
  • Pressure readiness: Renderer shed_load handles all pressure levels with idle_cadence + resolution scaling via thread-safe atomics

Key files

Area Files
Scene system scene/room.rs, scene/builder.rs, scene/lighting.rs, scene/slot.rs, scene/avatar.rs, scene/object.rs
Animation data scene/animation.rs (profiles/config), animation.rs (Bevy systems)
Snapshot types.rs (SnapshotTracker), mod.rs (request_snapshot_readback, SceneInstanceReady)
Widget PersonaTile.ts (heatmap, fixed slots, error logging), UserListWidget.ts (badge fix)
Pressure memory_reporter.rs (shed_load), types.rs (SharedMemoryStats atomics)

Architecture doc

Added docs/live/SCENE-ANIMATION-ARCHITECTURE.md — three-layer model (Persona → Sentinel → ECS), scene hierarchy, animation system design.

Test plan

  • Verify avatar scenes render with room backgrounds
  • Verify genome bars show 4 fixed slots with heatmap colors
  • Verify snapshot capture doesn't burst (check Rust logs for snapshot timing)
  • Verify pressure shed_load adjusts idle_cadence under memory load
  • Verify model badges differentiate by provider

🤖 Generated with Claude Code

Leak fixes:
- jemalloc: aggressive page return vs macOS system allocator hoarding
- Agent DashMap: remove completed agents immediately (was leaking full
  conversation history + tool results per agent, never cleaned up)
- voice/end-session: Rust command to drop LiveKit agents/listeners on
  call end, wired through VoiceOrchestrator → RustBridge → IPC
- Bevy PendingLoads: drain completed entries so asset handles drop
- Snapshot eviction: remove stale captures on participant leave

Memory pressure monitor (new):
- MemoryPressureMonitor: own tokio task, 2s poll, crash-proof
- MemoryReporter trait: panic-isolated, quarantine after 3 failures
- BevyMemoryReporter: first reporter, atomic stats from render loop
- BevyMemoryStats: lock-free atomics updated every frame
- PressureSnapshot via watch channel, system/pressure IPC command
- Levels: Normal/Warning/High/Critical with hysteresis
- Monitors system-wide memory, not just our process RSS
types.rs (486) — components, resources, enums, constants
animation.rs (1263) — morph targets, blink, breathe, gesture, gaze
skeleton.rs (472) — bone discovery, T-pose fix, scene tree helpers
vrm.rs (362) — VRM 0.x/1.0 blend shapes, humanoid bones, lookAt
mod.rs (1329) — public API, singleton, app setup, commands, readback
…me waste

- send_by_identity: 8 lock→lookup→send methods → single dispatch helper
- SpeakingSlots resource: computed once/frame, consumed by 5 systems (was 5 independent HashSet builds)
- set_morph() helper: replaces ~20 identical if-let-if bounds-check blocks
- MorphTargetLayout struct: discovery functions take &mut layout (was 13 individual &mut Option params)
- map_preset!/set_first! macros: compress VRM preset matching from verbose if-chains
- Remove all bevy_debug() calls + format! allocations (no-op function was still formatting strings)
- 4272 → 3515 lines (-18%), zero new warnings
Two critical fixes for the Rust continuum-core process:

1. **Memory leak (GB-scale)**: Candle inference via spawn_blocking created
   hundreds of Metal/ObjC objects (command buffers, compute pipelines) per
   generate call. Without an autorelease pool on the thread pool thread,
   these accumulated and caused RSS to grow monotonically from ~2.5GB to
   16+GB, crashing the process. Fix: wrap inference_inner() in
   objc_autoreleasePoolPush/Pop. Same fix applied to GPU compute shader.

2. **Avatar video strobe**: Dual-write race condition where both CPU
   (ReadbackComplete) and GPU (Metal compute RGBA→NV12) wrote to the same
   IOSurface simultaneously. Fix: ensure_continuous_readback removes
   Readback component from bridge slots; ReadbackComplete observer bails
   for bridge slots; resize handler respects bridge state.

3. **IPC memory diagnostics**: Per-command RSS tracking via macOS
   task_info API. Logs commands causing >2MB growth and periodic top-10
   leaker report every 10s.

Also: LiveRoomSnapshotService writes snapshots to disk (not RAM),
VideoFrameCapture temporarily disabled pending re-enablement.
- Memory pressure monitor with Bevy reporter integration
- BackpressureService cache size limits and eviction
- InMemoryCognitionStorage bounded history (max 200 entries)
- ConversationHistorySource cache-only mode (no DB fallback)
- LiveRoomAwarenessSource uses cached snapshots only
- RAGComposer single-flight coalescing for concurrent requests
- TrainingDataAccumulator bounded buffer
- system-stop script improvements
Memory leak root cause was missing Metal autorelease pools on
spawn_blocking threads, not the capture paths themselves. Both
features confirmed stable under live chat load testing.
CandleAdapter now checks memory gate (is_memory_gate_closed) before
spawning inference — refuses under critical pressure. Semaphore limits
concurrent local inferences to 2, preventing 4-way pile-up that peaked
at 40GB. Personas 3-4 queue until 1-2 finish and release memory.

IPC memory diagnostics: per-command RSS tracking via macOS task_info,
periodic top-10 leaker report every 10s. Identified SQLite page cache
as second memory retention source (data/count, data/query cumulative
34GB+ during chat cascades).
Each subsystem now responds to the MemoryPressureMonitor's guidance:

Candle inference:
- Hard RSS ceiling (24GB) with immediate refusal
- Semaphore reduced to 1 (fully serialized, no pile-up)
- Memory gate check before spawning expensive work

SQLite ORM (every 10s):
- Normal: 64MB cache for performance
- Warning: 16MB cache
- High/Critical: 2MB cache + PRAGMA shrink_memory

Infrastructure:
- PressureLevel stored in global atomic, updated every 2s
- MemoryPressureMonitor::current_level() — lock-free static accessor
- Any subsystem can make graduated decisions without holding locks
Extracted lighting into spawn_scene_lighting() — key (25k upper-left),
fill (10k lower-right), rim (12k cool from behind) + ambient (800).
Shared across all avatar render layers. Designed for future scene
composition system (SceneBuilder with asset-driven presets).
Every subsystem now reads shared pressure level and self-manages:
- ThoughtStream: 1 responder at high/critical (was up to 3)
- Persona cadence: 1.5-4x slower under pressure
- Voice broadcast: limits targets (3/1/0) by pressure level
- Drain loop: breaks early at high+ pressure
- Bevy idle_cadence: 2/4/8 via shared atomic under pressure

BackpressureService unified from binary gate to graduated pressure
cache (normal/warning/high/critical) with 2s TTL from Rust IPC.

jemalloc: dirty_decay_ms=1000, muzzy_decay_ms=2000 — returns freed
pages to OS in 1-2s instead of default 10s. Eliminates the 3-5GB
"owned unmapped memory" that inflated RSS permanently.

SQLite: cache 64MB→8MB, mmap 256MB→disabled (counted toward RSS on
macOS). Adaptive cache shrinks to 2MB under pressure.

Query semaphore(4): caps concurrent data/query operations to prevent
15 personas materializing large result sets simultaneously.

Result: RSS peaks 5-9GB during bursts (was 30-40GB stuck), drops
back to 1.5GB idle. Process stays alive through bursty voice chat.
Old thresholds (60% warning, 80% high) kept the system permanently at
warning/high on a 32GB machine with browser + Claude Code + Node,
since normal system usage is 70-80%. This throttled all AI personas
permanently — only 1 ThoughtStream responder, 2x cadence, voice
broadcast limited.

New thresholds reflect actual danger to the process, not normal system
usage: 80% warning, 90% high, 95% critical.
When a call empties (all participants leave), sends UnloadIdle to Bevy
to free non-active model slots. Previously models stayed loaded forever
after calls ended, holding ~8MB per model in GPU/heap memory.

UnloadIdle command: Bevy-side knows which slots are active vs idle,
unloads only idle ones (loaded but not in active render loops).

Pressure shed_load at Critical stays resize-only — unloading models
during pressure spikes is counterproductive since reloading them costs
more memory temporarily. UnloadIdle is for explicit lifecycle cleanup.
Extract monolithic slot/state management into a proper scene graph:
- scene/object.rs: Polymorphic SceneObject enum (Avatar, StaticMesh, Environment)
- scene/avatar.rs: AvatarObject with full animation state, bones, morph targets
- scene/lighting.rs: LightRig enum (Portrait, Outdoor, Studio) with spawn functions
- scene/builder.rs: build_scene() spawns root→camera hierarchy per slot
- scene/slot.rs: RenderSlot owns HashMap<String, SceneObject>, typed accessors

Each avatar gets a unique room color via room_color_from_identity() hash.
Cameras are now lazy (created on Load via build_scene, not pre-allocated).
Slots support multiple objects — foundation for multi-avatar scenes,
props, environments, and future Sims-style persona apartments.

Wired into renderer: mod.rs process_commands uses build_scene + teardown,
animation.rs iterates RenderSlot fields, metal_gpu_convert.rs updated.
Zero errors, zero warnings. Verified deployed and rendering.
Scene system is now a generic render engine decoupled from LiveKit.
RoomConfig component declares environment (glTF asset path or procedural
style). populate_rooms Bevy system loads glTF environments or generates
procedural geometry (Office/Studio/Lounge) from persona identity hash.
All environment entities are children of scene root — teardown is automatic.
Scene selection mirrors voice and avatar: identity → hash → scene from
catalog. 5 starter room GLBs (office, studio, lounge, home-office,
server-room) generated at build time by scripts/generate-scene-models.ts,
integrated into npm start Phase 2a alongside voice model download.

Scene catalog (SCENE_CATALOG) with select_scene_for_identity() uses the
same FNV-1a hash with salt="scene" for independent distribution. All
scenes are assets (GLB files) — no procedural geometry in the renderer.
Room geometry was invisible (black) because glTF child nodes don't
inherit parent RenderLayers automatically. Added SceneInstanceReady
observer on the environment entity that propagates layers to all
descendants, matching the pattern used for avatar glTF scenes.
scenes work well, system not so much.
Scene system:
- Asset-based room environments with identity-hash deterministic selection
- 3-point portrait lighting rig for avatar scenes
- SceneInstanceReady observer propagates RenderLayers to glTF children
- AnimationProfile/AnimationConfig data-driven animation parameters

Snapshot capture:
- Time-based SnapshotTracker with anti-burst (2s cooldown, 4s min age)
- Single-flight capture for GPU bridge slots (temporary Readback insertion)
- Stale slot cleanup in request_snapshot_readback system

Persona tile improvements:
- Fixed 4 genome slots (consistent width, top adapters by maturity)
- Continuous heatmap coloring for genome bars (deep blue → teal → green → amber → mint)
- Continuous height scaling (25-100% based on maturity)
- Removed silent error swallowing in genome/layers fetch
- Model badge derives from provider alone (fixes all-identical meters)

Renderer pressure readiness:
- shed_load handles Normal/Warning/High/Critical with idle_cadence + resolution
- SharedMemoryStats.desired_idle_cadence atomic for thread-safe pressure response
- sync_idle_cadence system reads atomic every frame
Copilot AI review requested due to automatic review settings March 11, 2026 17:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Large cross-cutting PR that adds an asset-based Bevy scene/animation system (rooms + lighting + scene graph), introduces a Rust memory-pressure monitor and multiple “pressure-aware” throttles, improves snapshot capture + LiveKit cleanup, and reduces several high-RSS retention paths across Rust + TypeScript.

Changes:

  • Add Bevy scene graph + room catalog + animation profiles/config as data, plus VRM parsing and skeleton helpers.
  • Introduce a Rust MemoryPressureMonitor (TS bindings + Backpressure integration) and apply pressure-aware caps (SQLite cache, query concurrency, inference gating).
  • Reduce memory retention/leaks (agent cleanup, shell session GC/caps, conversation/media caching limits, snapshots stored on disk).

Reviewed changes

Copilot reviewed 59 out of 61 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/workers/continuum-core/src/system_resources/mod.rs Exposes new memory pressure module and re-exports types.
src/workers/continuum-core/src/system_resources/memory_pressure.rs New autonomous memory pressure monitor + TS type exports + budget snapshot types.
src/workers/continuum-core/src/runtime/message_bus.rs Recent-event buffer switched to VecDeque + TTL sweeping + tests.
src/workers/continuum-core/src/orm/sqlite.rs Adjust SQLite PRAGMAs and add pressure-aware cache shrinking.
src/workers/continuum-core/src/modules/system_resources.rs Adds IPC endpoints for pressure/gate/budget snapshots.
src/workers/continuum-core/src/modules/live.rs Adds voice/end-session command to trigger cleanup.
src/workers/continuum-core/src/modules/embedding.rs Adds TTL sweep before cache insert.
src/workers/continuum-core/src/modules/data.rs Adds query concurrency limiting via semaphore.
src/workers/continuum-core/src/modules/agent.rs Removes completed agents from map to prevent growth.
src/workers/continuum-core/src/main.rs Installs jemalloc + starts pressure monitor + delayed Bevy reporter registration.
src/workers/continuum-core/src/live/video/mod.rs Adds memory_reporter module export.
src/workers/continuum-core/src/live/video/metal_gpu_convert.rs Fixes Metal queue ordering + adds autorelease pool + improves conversion path.
src/workers/continuum-core/src/live/video/memory_reporter.rs Adds Bevy MemoryReporter implementation + pressure-driven shed/load commands.
src/workers/continuum-core/src/live/video/capture.rs Evicts stale participant snapshots when captures removed.
src/workers/continuum-core/src/live/video/bevy_renderer/vrm.rs Adds GLB JSON parsing for VRM blend shapes/bones/lookAt config.
src/workers/continuum-core/src/live/video/bevy_renderer/types.rs Adds renderer public types + snapshot tracker + shared stats structures.
src/workers/continuum-core/src/live/video/bevy_renderer/skeleton.rs Adds bone discovery, RenderLayer propagation, and T-pose fixes.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/slot.rs Adds slot registry and render-slot object management.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/room.rs Adds room catalog + deterministic selection + environment population system.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/object.rs Defines SceneObject variants (avatar/static/environment).
src/workers/continuum-core/src/live/video/bevy_renderer/scene/mod.rs Scene module barrel + exports.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/lighting.rs Adds light rig presets/spawners.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/builder.rs Adds scene root/camera builder + global light spawner.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/avatar.rs Adds avatar object/state types for scene graph.
src/workers/continuum-core/src/live/video/bevy_renderer/scene/animation.rs Adds animation profiles + AnimationConfig ECS component.
src/workers/continuum-core/src/live/transport/livekit_agent.rs Removes per-agent VAD; adds manager cleanup methods.
src/workers/continuum-core/src/live/transport/call_server.rs Unloads idle avatar models on call cleanup.
src/workers/continuum-core/src/live/audio/stt/whisper.rs Reuses preallocated Whisper state + adds memory gate refusal.
src/workers/continuum-core/src/ipc/mod.rs Adds per-command RSS delta tracking + periodic leak report logging.
src/workers/continuum-core/src/inference/candle_adapter.rs Adds inference semaphore + autorelease pool + RSS ceiling + gate checks.
src/workers/continuum-core/src/code/shell_session.rs Adds GC call before execution + caps output/history sizes.
src/workers/continuum-core/bindings/modules/voice.ts Adds voiceEndSession() binding.
src/workers/continuum-core/bindings/modules/system_resources.ts Adds pressure/gate IPC bindings + TS types.
src/workers/continuum-core/Cargo.toml Adds tikv-jemallocator + lint config.
src/widgets/chat/user-list/UserListWidget.ts Fixes model badge display when only provider known.
src/widgets/chat/user-list/PersonaTile.ts Adds genome heatmap + fixed 4-slot rendering + better error logging.
src/system/voice/server/VoiceOrchestratorRustBridge.ts Calls Rust voiceEndSession on session end.
src/system/voice/server/VoiceOrchestrator.ts Triggers Rust session cleanup + pressure-aware broadcast limiting.
src/system/user/server/modules/cognition/memory/InMemoryCognitionStorage.ts Adds per-persona caps for in-memory collections.
src/system/user/server/modules/TrainingDataAccumulator.ts Caps interaction index size.
src/system/user/server/modules/PersonaState.ts Cadence scales with memory pressure.
src/system/user/server/modules/PersonaAutonomousLoop.ts Yields under high+ pressure during queue draining.
src/system/rag/sources/LiveRoomAwarenessSource.ts Loads snapshot base64 lazily from disk rather than caching in memory.
src/system/rag/sources/ConversationHistorySource.ts Reduces fetch limit + caps cache + strips base64 media for cache.
src/system/rag/shared/RAGComposer.ts Adds cleanup for shared in-flight source entries.
src/system/live/LiveRoomSnapshotService.ts Persists snapshots to disk and caches path instead of base64.
src/system/core/services/BackpressureService.ts Integrates Rust pressure snapshot into backpressure decisions.
src/system/conversation/server/ThoughtStreamCoordinator.ts Responders count becomes pressure-aware.
src/shared/version.ts Bumps package version constant.
src/scripts/system-stop.sh Kills orphaned node/tsx processes tied to project path.
src/scripts/parallel-start.sh Runs scene model generation alongside voice model download/build.
src/scripts/generate-scene-models.ts Adds generator for starter scene GLBs via gltf-transform.
src/package.json Version bump + adds @gltf-transform/core dev dependency.
src/package-lock.json Lockfile updates for version + new dependency.
src/generated-command-schemas.json Regenerates schemas metadata timestamp.
docs/live/SCENE-ANIMATION-ARCHITECTURE.md Adds architecture doc for scene/animation model.
docs/IMMERSIVE-SOCIAL-ARCHITECTURE.md Adds immersive social rendering modes doc.
CLAUDE.md Adds “Sensory Architecture” design constraint section.
Files not reviewed (1)
  • src/package-lock.json: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +1535 to +1539
// Arc::try_unwrap will succeed if we hold the last reference,
// allowing us to call disconnect(self). Otherwise just drop it.
if let Ok(agent) = Arc::try_unwrap(agent) {
agent.disconnect().await;
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove_agent only calls disconnect() when Arc::try_unwrap succeeds, but start_video_loop() holds another Arc<LiveKitAgent>, so try_unwrap will almost never succeed. This means agents may never disconnect from the LiveKit room and their video loop/Bevy slot may keep running after removal. Consider making LiveKitAgent::disconnect take &self (so it can be called through Arc) and always invoking it here, or add an explicit shutdown signal that terminates the video loop before dropping the Arc.

Copilot uses AI. Check for mistakes.
Comment on lines +1542 to +1550
// Clean up creation lock for this key
#[allow(clippy::type_complexity)]
static CREATION_LOCKS: std::sync::Mutex<
Option<std::collections::HashMap<(String, String), Arc<tokio::sync::Mutex<()>>>>,
> = std::sync::Mutex::new(None);
if let Ok(mut locks) = CREATION_LOCKS.lock() {
if let Some(map) = locks.as_mut() {
map.remove(&key);
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CREATION_LOCKS is declared as a separate static inside both get_or_create_agent and remove_agent. These are different statics, so remove_agent won't actually remove entries from the lock map used during creation, leading to unbounded growth of per-agent mutexes. Move the creation-lock map to a single shared location (module-level static or a LiveKitAgentManager field) and reference it from both methods.

Copilot uses AI. Check for mistakes.
Comment thread src/workers/continuum-core/src/main.rs Outdated
Comment on lines +132 to +137
// Start memory pressure monitor — own task, non-blocking, crash-proof.
// Polls every 2s, publishes via watch channel. Modules subscribe to react.
// Start with empty reporters — Bevy might not be ready yet (race condition).
let pressure_monitor =
continuum_core::system_resources::MemoryPressureMonitor::start(Vec::new());

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MemoryPressureMonitor is started here, but the IPC runtime (and SystemResourceModule) is created inside start_server on a separate thread before this runs. As a result, SystemResourceModule.pressure_monitor is never set and system/pressure / system/memory-budget will always return "not initialized". Consider starting the pressure monitor before spawning the IPC thread and passing the Arc<MemoryPressureMonitor> into start_server (so it can be wired into SystemResourceModule), or store a global singleton handle accessible from the module.

Copilot uses AI. Check for mistakes.
Comment on lines +92 to +101
"system/pressure" => {
// Memory pressure snapshot from the autonomous monitor
if let Some(pm) = &self.pressure_monitor {
let snapshot = pm.current();
let json = serde_json::to_value(snapshot)
.map_err(|e| format!("Failed to serialize pressure: {e}"))?;
Ok(CommandResult::Json(json))
} else {
Err("Memory pressure monitor not initialized".to_string())
}

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The system/pressure and system/memory-budget commands error out unless pressure_monitor is set, but set_pressure_monitor() is never called anywhere in the repo (search shows only the definition). With the current boot sequence, these IPC endpoints will be unusable. Either wire the monitor into this module during runtime registration, or make these commands read from global atomics/singleton monitor state instead of an Option field.

Copilot uses AI. Check for mistakes.
Comment on lines +474 to +481
// Spawn the monitor loop on its own task
tokio::spawn(Self::run_loop(
monitor.tx.clone(),
current_rss,
current_pressure,
entries,
reporter_rx,
));

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The module-level docs claim the monitor task is spawned with a catch_unwind wrapper and that each reporter is called with a timeout, but start() spawns run_loop() directly and reporter calls are synchronous without any timeout. Either implement the promised isolation (wrap the loop in catch_unwind + restart/log, and enforce per-reporter timeouts) or adjust the docs to match actual behavior so consumers don't assume stronger guarantees than provided.

Copilot uses AI. Check for mistakes.
Comment on lines +176 to +178
fs.mkdirSync(snapshotDir, { recursive: true });
const snapshotPath = path.join(snapshotDir, `room-${roomId.slice(0, 8)}.jpg`);
fs.writeFileSync(snapshotPath, Buffer.from(base64, 'base64'));

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

captureAndDescribe() performs fs.mkdirSync and fs.writeFileSync inside an async capture loop. These synchronous filesystem calls block the Node.js event loop and can add latency during active persona cycles. Prefer using fs.promises.mkdir / fs.promises.writeFile (or offload to a worker thread) so snapshot persistence doesn't block other server work.

Suggested change
fs.mkdirSync(snapshotDir, { recursive: true });
const snapshotPath = path.join(snapshotDir, `room-${roomId.slice(0, 8)}.jpg`);
fs.writeFileSync(snapshotPath, Buffer.from(base64, 'base64'));
await fs.promises.mkdir(snapshotDir, { recursive: true });
const snapshotPath = path.join(snapshotDir, `room-${roomId.slice(0, 8)}.jpg`);
await fs.promises.writeFile(snapshotPath, Buffer.from(base64, 'base64'));

Copilot uses AI. Check for mistakes.
Comment on lines +114 to +122
if (!snapshot?.snapshotPath) return [];

// Read base64 from disk lazily — NOT held in RAM between cycles
let base64: string;
try {
const buffer = fs.readFileSync(snapshot.snapshotPath);
base64 = buffer.toString('base64');
} catch {
return []; // File gone or unreadable

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildArtifacts() reads the snapshot file using fs.readFileSync, which blocks the Node.js event loop during RAG composition. Since this may run frequently in persona cycles, prefer async I/O (fs.promises.readFile) or caching/streaming so artifact generation doesn't introduce synchronous stalls.

Copilot uses AI. Check for mistakes.
Screenshot: live session with scene environments, genome heatmaps, cognitive telemetry
Quote: tightened — removed run-on sentence, emphasizes sensory bridging
Critical fixes:
- Wire MemoryPressureMonitor into SystemResourceModule via OnceLock
  (system/pressure and system/memory-budget IPC endpoints were dead)
- LiveKit agent disconnect now takes &self, always called on remove
  (agents were never disconnecting due to Arc::try_unwrap failure)
- Unify AGENT_CREATION_LOCKS into single module-level static
  (two separate statics caused unbounded growth of per-agent mutexes)

Reliability:
- Wrap pressure monitor loop in catch_unwind for panic isolation
- Add 100ms timeout per reporter via spawn_blocking + tokio::timeout
- Fix test_pressure_levels thresholds to match current 80/90/95 values

Performance:
- LiveRoomSnapshotService: mkdirSync/writeFileSync → async fs.promises
- LiveRoomAwarenessSource: readFileSync → async fs.promises.readFile
- Add PressureLevel::normalize() mapping action zone (80-95%) to 0.0-1.0
- PRESSURE_FLOOR/PRESSURE_CEILING constants as single source of truth
- normalized_pressure field on PressureSnapshot (Rust + ts-rs generated)
- BackpressureService.normalizedPressure getter for all TS consumers
- 5 test assertions covering floor/midpoint/ceiling/clamp boundaries
@joelteply
joelteply merged commit a1c0b51 into main Mar 11, 2026
2 of 5 checks passed
@joelteply
joelteply deleted the feature/bevy-scene-system branch March 11, 2026 18:50
joelteply added a commit that referenced this pull request Aug 2, 2026
…g into one watermark frame (#295) (#2094)

A fresh node (no persisted attach cursor) attached with bare
AttachStart::FromTranscriptStart — the variant airc's own doc marks
'audit/replay tools only' — and streamed the room's ENTIRE history
into the live bus: thousands of events decoded, published, and
serviced by every persona as if they were happening now. BigMama's
first Windows core boot pegged 24 cores for ~45 minutes on exactly
this (k3-serving carries ~5000+ events). Confirmed by her empty-room
control: the same build in a fresh room came up clean and reached
serving mode.

Fix: attach_request_for_cursor() — the first-ever attach still starts
from the transcript head for cursor correctness but sets
with_coalesced_backlog() (airc card 7d5b6a65), so the daemon collapses
the whole catch-up phase into ONE AttachCursorAdvanced summary frame at
the live seam. The existing handler persists that frame, so every later
attach resumes After(cursor) as before. A resumed attach still streams
its gap uncoalesced — those events were live while the node was down
and are owed to the durable-transcript writer (#140) and perception.

Semantics: the room starts at join for a fresh node — personas perceive
the room AS IT IS NOW (#131); deep history is #249's bounded
durable-transcript hydration, never a perception replay. Also a #291
front-door fix: first clone + first boot no longer melts the machine.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
joelteply added a commit that referenced this pull request Aug 2, 2026
…cklog_tail(32) (#295 follow-up) (#2098)

Joel: 'When you join a Discord channel do you read the whole history
from 10 years back? No — one page.' #2094 bounded the first-ever attach
to zero backlog (pure live-edge join); airc PR #1312 adds the
backlog_tail knob — the daemon streams the newest N backlog events at
the catch-up seam and coalesces everything older into the watermark
summary, tail delivered BEFORE the summary so the #261 cursor
discipline holds.

Continuum side: bump ALL airc crate pins 816a0be → f01a3f4 together
(mixed revs would produce two airc-core versions and type clashes) and
set FIRST_ATTACH_PAGE = 32 on the no-cursor attach. Resumed attaches
unchanged: gap replay stays uncoalesced.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants