Skip to content

Memory leak fixes + pressure monitor foundation - #294

Closed
joelteply wants to merge 14 commits into
mainfrom
feature/rust-live-memory-leaks
Closed

joelteply wants to merge 14 commits into
mainfrom
feature/rust-live-memory-leaks

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • jemalloc: replaces macOS system allocator (hoards pages under Bevy's 15fps churn)
  • Agent DashMap leak: completed agents now removed immediately (was leaking full conversation history per tool call, never cleaned up — GB/hour with 14 active personas)
  • voice/end-session: Rust IPC command to drop LiveKit agents/listeners on call end, wired through TS VoiceOrchestrator cleanup path
  • Bevy PendingLoads: drain completed entries so asset Handles drop
  • MemoryPressureMonitor: autonomous tokio task (2s poll, crash-proof, panic-isolated reporters, watch channel for subscribers)
  • BevyMemoryReporter: first reporter — atomic stats from render loop (active slots, loaded models, render target bytes)
  • system/pressure IPC command: query current pressure snapshot

What this does NOT do yet

  • Pressure response: shed_load() is a stub — Bevy doesn't actually deactivate slots under pressure yet
  • bevy_renderer.rs modularization: 4271-line monolith needs splitting before proper per-subsystem memory ownership is possible
  • Disk/CPU pressure monitors: same pattern, not built yet
  • Other reporters: embedding, corpus, ORM — not implemented yet

This is the foundation. Pressure-driven load shedding comes next, after the Bevy renderer is modularized.

Test plan

  • Release build compiles clean
  • Deployed and tested with live call — memory still fluctuates but no longer monotonically climbs to 40GB+
  • Verify system/pressure IPC returns valid snapshots
  • Verify pressure log lines appear in orchestrator.log every 30s
  • Load test: sustained live call, monitor RSS stability

🤖 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
Copilot AI review requested due to automatic review settings March 10, 2026 19:39

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

This PR targets multiple sources of memory growth in the Continuum runtime and introduces a new “memory pressure” monitoring foundation intended to support future load shedding and operational introspection.

Changes:

  • Introduces a MemoryPressureMonitor with TS-exported snapshot types and a first BevyMemoryReporter.
  • Adds cleanup paths to reduce leaks (LiveKit session teardown command + agent map removal + Bevy pending-load draining + snapshot eviction).
  • Switches the Rust global allocator to jemalloc and adds new IPC plumbing for system/pressure and voice/end-session.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 12 comments.

Show a summary per file
File Description
src/workers/continuum-core/src/system_resources/mod.rs Exposes new memory pressure monitor module and types.
src/workers/continuum-core/src/system_resources/memory_pressure.rs Adds the autonomous pressure monitor, snapshot/reporting types, and watch channel publishing.
src/workers/continuum-core/src/modules/system_resources.rs Adds system/pressure IPC command and storage for a pressure monitor handle.
src/workers/continuum-core/src/modules/live.rs Adds voice/end-session IPC command to trigger LiveKit cleanup.
src/workers/continuum-core/src/modules/agent.rs Removes completed agents from DashMap to prevent retained history/tool-call memory.
src/workers/continuum-core/src/main.rs Enables jemalloc and starts the pressure monitor (currently not wired into IPC module registration).
src/workers/continuum-core/src/live/video/mod.rs Exposes the new Bevy memory reporter module.
src/workers/continuum-core/src/live/video/memory_reporter.rs Implements BevyMemoryReporter reading atomics from the renderer.
src/workers/continuum-core/src/live/video/capture.rs Cleans up participant snapshots when captures end; adds stale snapshot eviction.
src/workers/continuum-core/src/live/video/bevy_renderer.rs Adds shared atomic stats resource, updates per-frame stats, drains completed pending loads, and bounds the command channel.
src/workers/continuum-core/src/live/transport/livekit_agent.rs Adds agent/listener removal helpers for call teardown.
src/workers/continuum-core/bindings/modules/voice.ts Adds TS binding for voice/end-session.
src/workers/continuum-core/Cargo.toml Adds tikv-jemallocator dependency.
src/system/voice/server/VoiceOrchestratorRustBridge.ts Calls Rust voice/end-session during session end.
src/system/voice/server/VoiceOrchestrator.ts Wires Rust cleanup into TS session unregister path.

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

Comment thread src/workers/continuum-core/src/main.rs Outdated
}
r
};
let _pressure_monitor =

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

main.rs starts a MemoryPressureMonitor and immediately drops the handle (let _pressure_monitor = ...), and this monitor isn't connected to the IPC SystemResourceModule (which is created inside start_server). This makes the new system/pressure command effectively unusable and also means nothing can subscribe to the watch channel. Consider creating the monitor in the IPC startup path (where modules are registered) and storing the Arc<MemoryPressureMonitor> somewhere accessible (e.g., inside SystemResourceModule).

Suggested change
let _pressure_monitor =
let pressure_monitor =

Copilot uses AI. Check for mistakes.
// jemalloc: returns memory to OS aggressively instead of hoarding pages.
// macOS system allocator fragments badly under Bevy's 15fps readback churn
// (14 slots × 921KB per frame) — RSS grows to 30-40GB and never shrinks.
// jemalloc's dirty page purging returns freed memory within seconds.

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

The global jemalloc allocator is enabled unconditionally. tikv-jemallocator is not supported on all targets (notably Windows MSVC), which can break builds for those environments. Consider gating this with cfg (e.g., #[cfg(not(target_env = "msvc"))]) or providing a fallback allocator for unsupported targets.

Suggested change
// jemalloc's dirty page purging returns freed memory within seconds.
// jemalloc's dirty page purging returns freed memory within seconds.
#[cfg(not(target_env = "msvc"))]

Copilot uses AI. Check for mistakes.
frame_notifiers,
ready,
identity_to_slot: std::sync::Mutex::new(HashMap::new()),
memory_stats: Arc::new(BevyMemoryStats::new()),

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

BevyAvatarSystem::start() creates memory_stats, passes a clone into the Bevy thread, but then stores a different freshly-created Arc<BevyMemoryStats> in Self { memory_stats: ... }. This means external readers (e.g., BevyMemoryReporter) will never see updates (they'll read zeros forever). Store the same memory_stats Arc that is passed to run_bevy_app.

Suggested change
memory_stats: Arc::new(BevyMemoryStats::new()),
memory_stats,

Copilot uses AI. Check for mistakes.
/// Start the Bevy renderer on a dedicated OS thread.
fn start() -> Self {
let (command_tx, command_rx) = crossbeam_channel::unbounded();
let (command_tx, command_rx) = crossbeam_channel::bounded(512);

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

Switching the command channel to crossbeam_channel::bounded(512) makes Sender::send() potentially block when the queue fills. Many call sites use send() on latency-sensitive paths and ignore the result; blocking here can stall voice/video tasks and create deadlocks under load. If the intent is backpressure, consider try_send/send_timeout plus logging/dropping, or keep it unbounded and enforce limits elsewhere.

Suggested change
let (command_tx, command_rx) = crossbeam_channel::bounded(512);
let (command_tx, command_rx) = crossbeam_channel::unbounded();

Copilot uses AI. Check for mistakes.
Comment on lines +1627 to +1636
// 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 10, 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() defines a new static CREATION_LOCKS that is different from the one inside get_or_create_agent(), so this cleanup will never remove entries from the actual creation-lock map (leaving those Arcs/leaks behind). Consider moving CREATION_LOCKS to a single shared module-level static so both functions access the same map.

Copilot uses AI. Check for mistakes.
Comment on lines 171 to +176
async fn remove_capture(&self, identity: &str) {
let mut captures = self.active_captures.lock().await;
captures.remove(identity);
// Also remove stale snapshot for this participant
let mut snapshots = self.snapshots.lock().await;
snapshots.remove(identity);

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

remove_capture() holds the active_captures mutex guard while awaiting the snapshots mutex, which increases lock contention and makes future deadlocks more likely if any code ever acquires these locks in the opposite order. Consider dropping the captures guard before awaiting snapshots.lock() (e.g., by limiting the guard scope).

Copilot uses AI. Check for mistakes.
Comment on lines +384 to +389
clog_warn!(
"🧠 MemoryReporter '{}' panicked ({}/3): {:?}",
name,
entry.consecutive_panics,
e
);

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

catch_unwind's panic payload (e) is a Box<dyn Any + Send>, which doesn't implement Debug; formatting it with {:?} will not compile. Consider logging a downcasted &str/String message (when available) or a generic "" message instead.

Copilot uses AI. Check for mistakes.
//!
//! - Own tokio task: `tokio::spawn` with `catch_unwind` wrapper
//! - No shared locks with Bevy, IPC, or audio systems
//! - Reporters called with timeout: 100ms max per reporter

Copilot AI Mar 10, 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 docs claim reporters are "called with timeout: 100ms max per reporter", but reporter.report() is invoked directly with no timeout/guard. Either implement an actual timeout (e.g., run the report in a separate task and timeout it) or update the docs so they match the real behavior.

Suggested change
//! - Reporters called with timeout: 100ms max per reporter
//! - Reporter calls are best-effort; no hard per-reporter timeout is enforced

Copilot uses AI. Check for mistakes.
Comment on lines +46 to +52
//! ```rust,ignore
//! // Start the monitor (once, at server boot)
//! let monitor = MemoryPressureMonitor::start();
//!
//! // Any system can subscribe to pressure changes
//! let mut rx = monitor.subscribe();
//! tokio::spawn(async move {

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

The usage example calls MemoryPressureMonitor::start() with no arguments, but the actual signature is start(reporters: Vec<Arc<dyn MemoryReporter>>). This will confuse future readers; update the example to match the real API (or adjust the API if the no-arg start is intended).

Copilot uses AI. Check for mistakes.
Comment on lines 17 to 35
pub struct SystemResourceModule {
monitor: Arc<SystemResourceMonitor>,
pressure_monitor: Option<Arc<MemoryPressureMonitor>>,
}

impl SystemResourceModule {
pub fn new(monitor: Arc<SystemResourceMonitor>) -> Self {
Self { monitor }
Self {
monitor,
pressure_monitor: None,
}
}

/// Set the memory pressure monitor reference.
/// Called after both are created in main.rs.
pub fn set_pressure_monitor(&mut self, pm: Arc<MemoryPressureMonitor>) {
self.pressure_monitor = Some(pm);
}
}

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

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

SystemResourceModule is registered into the runtime as an Arc<...>, but pressure_monitor is an Option that is never set, and set_pressure_monitor(&mut self, ...) can't be called through the shared Arc after registration. As written, system/pressure will always return "Memory pressure monitor not initialized". Consider storing the pressure monitor in an interior-mutable cell (e.g., OnceLock<Arc<...>>/Mutex<Option<_>>) and wiring it up where modules are constructed (IPC start_server path).

Copilot uses AI. Check for mistakes.
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.
@joelteply

Copy link
Copy Markdown
Contributor Author

Already merged into main. All commits from this branch are in main. Active work continues on #295.

@joelteply joelteply closed this Mar 11, 2026
joelteply added a commit that referenced this pull request Aug 10, 2026
… evict it (run-18057-f1, #392)

The 0-byte SWE-bench patch, structurally. The full result of the act a persona
just ran — the grep matches she must edit next, the file she just read — rode the
working-memory faculty's single contribution at WORKING_MEMORY_SALIENCE (0.5). That
contribution competes in arbiter.focus() top-k, so under capacity pressure the whole
thing was truncated and she generated her next turn BLIND to what her own hands had
returned. On sympy-18057 that meant: grep for `__eq__`, never see the result, yield
nothing.

Fix: the live act's full result is now read DIRECTLY from the shared working-memory
buffer in the message builder (WorkingMemory::pinned_active_result_block) and appended
as its own durable trailing turn — bypassing the faculty bid / arbiter entirely, so no
attention pass stands between the hands and the mind. Removed from the evictable faculty
contribution (which keeps only the trail + notices + dispatched summary).

Identical gating to the old block: settlement-seq gated so it stops re-prefilling once
the turn settles (#139/#165), clipped by budget, shown only when it carries more than
the trail head. Text on the wire, not structured tool_use/tool_result Parts:
content_text() is blind to non-Text parts, so Parts would undercount in fit_messages
and risk a window-edge 400, and the live GGUF template renders text reliably. True
tool-role Parts is a separate per-template-gated follow-up (#294 family).

- New guard `pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast`:
  the result reaches the prompt even when NOTHING bid it through the arbiter (the exact
  eviction state), and never lands in the cacheable system prefix.
- Retargeted the three full-result WM tests (whole/clipped/settlement-gate) from the
  faculty contribution to the pinned block — every invariant preserved.
- Fixed a Step-3 test committed red (never run green): restore() appends a [resumed]
  wake-orientation fact by design (#147/#165), so an N-entry snapshot restores to N+1;
  the test now asserts survival by content, not an exact count.

945/945 cognition tests green (cargo test -p continuum-core --lib --features metal,accelerate).
The live proof — deploy + a persona re-running sympy-18057 with the result threading
back to the _sympify edit — is the next step.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 11, 2026
…Steps 0-5 + 18057 acceptance) (#2225)

* refactor(cognition): typed Observation — Step 0 new observation.rs types + renderers

New `act_observe/observation.rs` owns the typed act value that will thread through
the act→observe→re-perceive contract (docs/cognition/TYPED-OBSERVATION-REFACTOR.md):
ToolVerb (the ONE verb→class home), ToolOutput (ToolResult + verb + typed paths),
ActStatus, Observation, ActOutcome. render_recency / render_recall are pure
functions of an Observation delegating to the existing recency helpers (byte-stable,
#205). Also lands Step-1 pure helpers: ToolVerb::classify subsumes the `wrote`
substring logic and extract_paths() reads typed file paths from call input. No
caller changes; apply.rs untouched. cargo check green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(cognition): typed Observation — Step 2 apply_act returns ActOutcome

apply_act now builds Vec<Observation> and returns ActOutcome instead of
Option<String>:
- no hands → ActOutcome::NoHands (was None)
- executor batch Err → ActOutcome::ExecutorError { calls, message } (was None —
  now distinguishable from no-hands for a future backstop)
- executed / already-satisfied / redundant-orientation → Acted { acts }, each act
  a typed Observation whose result correlates by tool_use_id == call.id (NOT the
  positional get(i) the string render still uses), verb + paths precomputed.

The two inline renderings + record_receipt/engram admit are UNCHANGED (byte-stable,
#205) — the typed acts are threaded alongside. settle_step's sole call maps
`produced_an_act()` → Acted / ActUnfulfilled (behavior identical to Some/None).
Guard tests migrate string→typed in lockstep; all 35 act_observe tests green.
ts-rs bindings emitted for the 5 new cognition types.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(cognition): typed Observation — Step 3 WorkingMemory stores typed acts on the Receipt

WmEntry gains #[serde(default)] acts: Vec<Observation> (back-compat, same
contract as saved_at_ms/build_sha). record_receipt_typed(&acts, rendered)
stores the byte-identical receipt text ALONGSIDE the typed acts; recent_acts()
and active_act() expose them so consumers read the tool result by TYPED FIELD
(call.id == result.tool_use_id) instead of re-parsing [action #n] prose
(run-18057-f1). apply_act records via record_receipt_typed. Guards: an old
volatile.json without acts restores without panic; the typed receipt threads
the act by field and keeps recent() byte-stable (#205).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(cognition): typed Observation — Step 4 migrate the seam-5 predicates off receipt prose

The live receipt render is a bare name(args) (the 'I ran ' opener was dropped for
#158), so the string scans mutated_workspace/wrote_without_observation/
claimed_file_without_act used ('I ran code/write(' …) were DEAD against a real
recency window — [no-deliverable]/[unobserved] were structurally unreachable
(the seam-5 live drift). Migrate them to read the TYPED verb + paths off
WmEntry.acts via recent_entries(): mutated_workspace/wrote_without_observation
scope by WmKind::Settlement and test ToolVerb::mutates/observes;
claimed_file_without_act matches the claimed file against the typed paths of a
MUTATING act (a read no longer backs a completion claim). has_real_action_receipt
(brackets-in-prose scan) → any_real_receipt (WmKind::Receipt). settle.rs callers
pass recent_entries()/pre_settle entries. Fixtures rebuilt as typed Observations
(the string fixtures were GREEN≠REACHABLE — they matched a render the live path
never emits). Deferred to keep the sweep green+honest: all_calls_already_satisfied
/is_redundant_orientation (still match name(args), which IS in the live receipt, so
correct against live data), latest_action_seq, and the Fact-tag→FactKind split.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(cognition): typed Observation — Step 5 render_recency/render_recall are the sole producers

The per-call inline format! recency + render_act_for_recall recall blocks in
apply_act are gone; both channel strings are now produced ONCE from the typed
Observation via the pure render_recency/render_recall helpers (defined in Step 0,
byte-identical to the old inline shaping — the humanize/bound/args logic lives in
observation.rs now). Render is a pure function of the act, so the recency string
and the typed acts can never drift. Sourced from the id-correlated result
(tool_use_id == call.id), immune to the fg-vs-original positional hazard.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(cognition): typed Observation — Step 6 (partial) 18057 typed-thread acceptance assertion

Strengthen the_hands_change_the_mind to assert, through the REAL drive_to_settle
loop, that the just-executed act's RESULT re-enters via the TYPED field
(active_act().output.result.content) and that the call correlates to its result
BY ID (call.id == result.tool_use_id) — never a re-parse of [action #n] prose nor
a positional index. This is act-grained proof the tool result threads back (the
channel run-18057-f1 lost the grep result through as an evictable perception bid →
0-byte patch). recent_acts() exposes the whole investigation off the typed channel.

DEFERRED (honest): the message-builder pinned assistant_tool_use↔tool_result pair
in llm_deliberation_faculty (the render side of this typed value) is the remaining
Step 6 piece. It appends the pair post-arbiter so capacity pressure cannot evict it
— but it changes EVERY live persona prompt (KV-prefix shape + adapter tool-part
handling + a double-inclusion decision vs the existing wm text trailing), which
needs live validation this VDD-gated sweep cannot provide. Not shipped blind.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(cognition): pin the just-executed act's result so attention can't evict it (run-18057-f1, #392)

The 0-byte SWE-bench patch, structurally. The full result of the act a persona
just ran — the grep matches she must edit next, the file she just read — rode the
working-memory faculty's single contribution at WORKING_MEMORY_SALIENCE (0.5). That
contribution competes in arbiter.focus() top-k, so under capacity pressure the whole
thing was truncated and she generated her next turn BLIND to what her own hands had
returned. On sympy-18057 that meant: grep for `__eq__`, never see the result, yield
nothing.

Fix: the live act's full result is now read DIRECTLY from the shared working-memory
buffer in the message builder (WorkingMemory::pinned_active_result_block) and appended
as its own durable trailing turn — bypassing the faculty bid / arbiter entirely, so no
attention pass stands between the hands and the mind. Removed from the evictable faculty
contribution (which keeps only the trail + notices + dispatched summary).

Identical gating to the old block: settlement-seq gated so it stops re-prefilling once
the turn settles (#139/#165), clipped by budget, shown only when it carries more than
the trail head. Text on the wire, not structured tool_use/tool_result Parts:
content_text() is blind to non-Text parts, so Parts would undercount in fit_messages
and risk a window-edge 400, and the live GGUF template renders text reliably. True
tool-role Parts is a separate per-template-gated follow-up (#294 family).

- New guard `pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast`:
  the result reaches the prompt even when NOTHING bid it through the arbiter (the exact
  eviction state), and never lands in the cacheable system prefix.
- Retargeted the three full-result WM tests (whole/clipped/settlement-gate) from the
  faculty contribution to the pinned block — every invariant preserved.
- Fixed a Step-3 test committed red (never run green): restore() appends a [resumed]
  wake-orientation fact by design (#147/#165), so an N-entry snapshot restores to N+1;
  the test now asserts survival by content, not an exact count.

945/945 cognition tests green (cargo test -p continuum-core --lib --features metal,accelerate).
The live proof — deploy + a persona re-running sympy-18057 with the result threading
back to the _sympify edit — is the next step.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[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