Move conversation_log from AgentState to ContextState

The log records what goes into context, so it belongs under the context
lock. push() now auto-logs conversation entries, eliminating all the
manual lock-state-for-log, drop, lock-context-for-push dances.

- ContextState: new conversation_log field, Clone impl drops it
  (forked contexts don't log)
- push(): auto-logs Section::Conversation entries
- push_node, apply_tool_results, collect_results: all simplified
- collect_results: batch nodes under single context lock
- Assistant response logged under context lock after parse completes

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
This commit is contained in:
ProofOfConcept 2026-04-09 00:32:32 -04:00
parent d82a2ae90d
commit ddfdbe6cb1
4 changed files with 112 additions and 109 deletions

View file

@ -273,7 +273,7 @@ impl State {
use std::sync::Arc;
use crate::agent::{Agent, oneshot::{AutoAgent, AutoStep}};
use crate::agent::context::{Ast, AstNode, NodeBody};
use crate::agent::context::{Ast, AstNode, NodeBody, Section};
use crate::subconscious::defs;
/// Names and byte-interval triggers for the built-in subconscious agents.
@ -455,92 +455,90 @@ impl Subconscious {
/// Collect results from finished agents, inject outputs into the
/// conscious agent's context.
/// Reap finished agents and inject their outputs into the conscious context.
pub async fn collect_results(&mut self, agent: &Arc<Agent>) {
let finished: Vec<(usize, tokio::task::JoinHandle<(AutoAgent, Result<String, String>)>)> =
self.agents.iter_mut().enumerate().filter_map(|(i, sub)| {
if sub.handle.as_ref().is_some_and(|h| h.is_finished()) {
sub.last_run = Some(Instant::now());
Some((i, sub.handle.take().unwrap()))
} else {
None
}
}).collect();
let had_finished = !finished.is_empty();
let mut any_finished = false;
for i in 0..self.agents.len() {
if !self.agents[i].handle.as_ref().is_some_and(|h| h.is_finished()) {
continue;
}
let handle = self.agents[i].handle.take().unwrap();
self.agents[i].last_run = Some(Instant::now());
any_finished = true;
for (idx, handle) in finished {
let (auto_back, result) = handle.await.unwrap_or_else(
|e| (AutoAgent::new(String::new(), vec![], vec![], 0.0, 0),
Err(format!("task panicked: {}", e))));
self.agents[idx].auto = auto_back;
self.agents[i].auto = auto_back;
match result {
Ok(_) => {
let name = self.agents[idx].name.clone();
// Check state for outputs (written by the output tool closure)
let has_outputs = self.state.contains_key("surface")
|| self.state.contains_key("reflection")
|| self.state.contains_key("thalamus");
if has_outputs {
if let Some(surface_str) = self.state.get("surface").cloned() {
// Collect keys already in context to avoid duplicates
let existing: std::collections::HashSet<String> = {
let ctx = agent.context.lock().await;
ctx.conversation().iter()
.filter_map(|n| n.leaf())
.filter_map(|l| match l.body() {
NodeBody::Memory { key, .. } => Some(key.clone()),
_ => None,
})
.collect()
};
let store = crate::store::Store::cached().await.ok();
let store_guard = match &store {
Some(s) => Some(s.lock().await),
None => None,
};
for key in surface_str.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) {
if existing.contains(key) { continue; }
let rendered = store_guard.as_ref()
.and_then(|s| crate::cli::node::render_node(s, key));
if let Some(rendered) = rendered {
agent.push_node(AstNode::memory(
key,
format!("--- {} (surfaced) ---\n{}", key, rendered),
)).await;
}
}
}
if let Some(reflection) = self.state.get("reflection").cloned() {
if !reflection.trim().is_empty() {
agent.push_node(AstNode::dmn(format!(
"--- subconscious reflection ---\n{}",
reflection.trim(),
))).await;
}
}
if let Some(nudge) = self.state.get("thalamus").cloned() {
let nudge = nudge.trim();
if !nudge.is_empty() && nudge != "ok" {
agent.push_node(AstNode::dmn(format!(
"--- thalamus ---\n{}",
nudge,
))).await;
}
}
}
dbglog!("[subconscious] {} completed", name);
}
Err(e) => dbglog!("[subconscious] agent failed: {}", e),
Ok(_) => dbglog!("[subconscious] {} completed", self.agents[i].name),
Err(e) => dbglog!("[subconscious] {} failed: {}", self.agents[i].name, e),
}
}
if had_finished {
self.save_state();
if !any_finished { return; }
// Collect all nodes to inject under a single context lock
let mut nodes: Vec<AstNode> = Vec::new();
if let Some(surface_str) = self.state.get("surface").cloned() {
let existing: std::collections::HashSet<String> = {
let ctx = agent.context.lock().await;
ctx.conversation().iter()
.filter_map(|n| n.leaf())
.filter_map(|l| match l.body() {
NodeBody::Memory { key, .. } => Some(key.clone()),
_ => None,
})
.collect()
};
let store = crate::store::Store::cached().await.ok();
let store_guard = match &store {
Some(s) => Some(s.lock().await),
None => None,
};
for key in surface_str.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) {
if existing.contains(key) { continue; }
if let Some(rendered) = store_guard.as_ref()
.and_then(|s| crate::cli::node::render_node(s, key))
{
nodes.push(AstNode::memory(
key,
format!("--- {} (surfaced) ---\n{}", key, rendered),
));
}
}
}
if let Some(reflection) = self.state.get("reflection").cloned() {
if !reflection.trim().is_empty() {
nodes.push(AstNode::dmn(format!(
"--- subconscious reflection ---\n{}",
reflection.trim(),
)));
}
}
if let Some(nudge) = self.state.get("thalamus").cloned() {
let nudge = nudge.trim();
if !nudge.is_empty() && nudge != "ok" {
nodes.push(AstNode::dmn(format!("--- thalamus ---\n{}", nudge)));
}
}
if !nodes.is_empty() {
let mut ctx = agent.context.lock().await;
for node in nodes {
ctx.push(Section::Conversation, node);
}
drop(ctx);
agent.state.lock().await.changed.notify_one();
}
self.save_state();
}
/// Trigger subconscious agents that are due to run.