Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions core/continuum-cognition/src/cognition/dispatch_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@ pub fn fold_completion(wm: &WorkingMemory, ev: CommandCompletedEvent) -> bool {
let Some(label) = wm.dispatched_label(handle) else {
return false;
};
// A failure keeps its output: the error line first, then the result. Keeping only the error
// ("exit 101") dropped the build log at exactly the moment she needed it.
let body = ev.result.as_ref().map(result_text);
let (content, status) = if ev.success {
let body = ev
.result
.as_ref()
.map(result_text)
.unwrap_or_else(|| "done".to_string());
(body, DispatchStatus::Done)
(body.unwrap_or_else(|| "done".to_string()), DispatchStatus::Done) // unwrap_or_else: a completion with no result says only that it is done
} else {
let body = ev.error.unwrap_or_else(|| "failed".to_string());
(body, DispatchStatus::Failed)
let error = ev.error.unwrap_or_else(|| "failed".to_string()); // unwrap_or_else: a failure with no error text still reads as failed
(body.map_or_else(|| error.clone(), |body| format!("{error}\n{body}")), DispatchStatus::Failed) // map_or_else: no result leaves the error alone
};
wm.record_dispatch_event(handle, &label, &content, status);
true
Expand Down Expand Up @@ -166,5 +164,14 @@ mod tests {
let ours = snap.iter().find(|(h, ..)| *h == mine).unwrap();
assert_eq!(ours.3, DispatchStatus::Failed);
assert_eq!(ours.2, "link error");

// A failure that carries output keeps it after the error line: the log is why she looks
// (it was dropped, leaving only "exit 101").
let mut failed = ev(Some(mine), false, serde_json::Value::Null);
failed.result = Some(serde_json::json!("error[E0432]: unresolved import"));
assert!(fold_completion(&wm, failed));
let snap = wm.dispatched_snapshot();
let ours = snap.iter().find(|(h, ..)| *h == mine).unwrap();
assert_eq!(ours.2, "link error\nerror[E0432]: unresolved import");
}
}
126 changes: 58 additions & 68 deletions core/continuum-hands/src/code/shell_session/run_shell_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ pub(super) async fn run_shell_command(
s.status = ShellExecutionStatus::Failed;
s.stderr_lines.push(format!("no usable shell: {why}"));
s.process_ended = true; // no child was spawned
s.finished_at = Some(continuum_base::time::EpochMs::now().millis());
s.output_notify.notify_one();
settle(&mut s);
}
return;
}
Expand Down Expand Up @@ -156,9 +155,8 @@ pub(super) async fn run_shell_command(
if let Ok(mut s) = state.lock() {
s.status = ShellExecutionStatus::Failed;
s.stderr_lines.push(format!("Failed to spawn bash: {e}"));
s.finished_at = Some(continuum_base::time::EpochMs::now().millis());
s.process_ended = true; // nothing started, so nothing is left running
s.output_notify.notify_one();
settle(&mut s);
}
return;
}
Expand All @@ -178,9 +176,8 @@ pub(super) async fn run_shell_command(
s.status = ShellExecutionStatus::Failed;
s.stderr_lines
.push("Failed to capture shell output: stdout/stderr pipes unavailable".to_string());
s.finished_at = Some(continuum_base::time::EpochMs::now().millis());
s.process_ended = true; // the child was told to die and nothing reads it
s.output_notify.notify_one();
settle(&mut s);
}
return;
};
Expand Down Expand Up @@ -322,69 +319,62 @@ pub(super) async fn run_shell_command(
let _ = stdout_task.await;
let _ = stderr_task.await;

// Update final state (if not already set by timeout/kill)
if let Some(status) = exit_status {
if let Ok(mut s) = state.lock() {
if s.status == ShellExecutionStatus::Running {
s.exit_code = status.code();
s.status = if status.success() {
ShellExecutionStatus::Completed
} else {
ShellExecutionStatus::Failed
};
s.finished_at = Some(continuum_base::time::EpochMs::now().millis());
// Wake any blocked watch() calls to deliver final status
s.output_notify.notify_one();
// PUSHED COMPLETION (2026-08-24): a handed-back execution's
// finish previously reached her only if she remembered to
// poll. Publish the same command:completed shape tracked
// dispatches use; the dispatch listener folds it into her
// working memory IF the handle was registered (apply.rs does,
// on handback).
if s.handed_back {
if let (Some(bus), Ok(handle)) =
(SHELL_COMPLETION_BUS.get(), uuid::Uuid::parse_str(&s.id))
{
let mut lines: Vec<&String> =
s.stdout_lines.iter().chain(s.stderr_lines.iter()).collect();
let cut = lines.len().saturating_sub(20);
let tail: String = lines
.split_off(cut)
.into_iter()
.map(String::as_str)
.collect::<Vec<_>>()
.join("\n");
let ev = crate::runtime::command_events::CommandCompletedEvent {
command_name: "code/shell".to_string(),
duration_ms: s.finished_at.unwrap_or(0).saturating_sub(s.started_at), // set 3 lines up; 0 → saturates to 0ms, display only
success: s.exit_code == Some(0),
error: (s.exit_code != Some(0))
.then(|| format!("exit {}", s.exit_code.map_or(-1, |c| c))),
handle: Some(handle),
result: Some(serde_json::json!({
"exitCode": s.exit_code,
"tail": tail,
})),
};
if let Ok(payload) = serde_json::to_value(&ev) { // bus fan-out boundary — the same encode tracked dispatches pay
bus.publish_async_only(
crate::runtime::command_events::COMMAND_COMPLETED_TOPIC,
payload,
);
}
}
}

log_info!(
"code",
"shell",
"Execution {} finished: exit={} cmd={}",
&s.id[..8],
s.exit_code.unwrap_or(-1), // killed/no-status path reads as conventional -1 in the error line
&s.command
);
}
// The final status for every way out: a timeout or a kill set theirs above; an exit sets it
// here; a wait error (no status, its line already in stderr) is a failure.
if let Ok(mut s) = state.lock() {
if s.status == ShellExecutionStatus::Running {
s.exit_code = exit_status.and_then(|status| status.code());
let succeeded = exit_status.is_some_and(|status| status.success());
s.status = if succeeded { ShellExecutionStatus::Completed } else { ShellExecutionStatus::Failed };
}
settle(&mut s);
}
}

/// The ONE terminal step every way out of a run takes (HER-TOOLS T2: completion on every exit).
/// It stamps the end, wakes blocked watchers and, for an execution already handed back to her
/// as a handle, publishes its completion. Before this, only a normal exit published: a timeout,
/// a kill or a wait error left her panel entry `[running]` forever (the M5, 2026-10-30: six long
/// cargo runs never reported back, and Aris launched the same test three times).
fn settle(s: &mut ExecutionState) {
s.finished_at.get_or_insert_with(|| continuum_base::time::EpochMs::now().millis());
s.output_notify.notify_one();
if s.handed_back {
publish_completion(s);
}
log_info!("code", "shell", "Execution {} ended {:?}: exit={:?} cmd={}", s.id, s.status, s.exit_code, s.command);
}

/// Publish a handed-back execution's completion in the `command:completed` shape tracked
/// dispatches use; the dispatch listener folds it into her working memory. The output travels
/// as retained, whole: her view decides how much of it she sees (HER-TOOLS rule 4), never a
/// line count here.
fn publish_completion(s: &ExecutionState) {
let (Some(bus), Ok(handle)) = (SHELL_COMPLETION_BUS.get(), uuid::Uuid::parse_str(&s.id)) else {
return;
};
let succeeded = s.status == ShellExecutionStatus::Completed;
let ended = match (&s.status, s.exit_code) {
(ShellExecutionStatus::TimedOut, _) => "timed out at its timeout_ms".to_string(),
(ShellExecutionStatus::Killed, _) => "killed".to_string(),
(_, Some(code)) => format!("exit {code}"),
(_, None) => "ended without an exit status".to_string(),
};
let ev = crate::runtime::command_events::CommandCompletedEvent {
command_name: "code/shell".to_string(),
duration_ms: s.finished_at.map_or(0, |end| end.saturating_sub(s.started_at)), // map_or: settle stamped the end before this
success: succeeded,
error: (!succeeded).then(|| ended.clone()),
handle: Some(handle),
result: Some(serde_json::json!({
"ended": ended,
"exitCode": s.exit_code,
"stdout": s.stdout_lines.join("\n"),
"stderr": s.stderr_lines.join("\n"),
})),
};
if let Ok(payload) = serde_json::to_value(&ev) { // bus fan-out boundary: the same encode tracked dispatches pay
bus.publish_async_only(crate::runtime::command_events::COMMAND_COMPLETED_TOPIC, payload);
}
}

Expand Down
30 changes: 30 additions & 0 deletions core/continuum-hands/src/code/shell_session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,3 +531,33 @@
assert_eq!(result.status, ShellExecutionStatus::Completed);
assert!(result.stderr.unwrap().contains("error_msg"));
}

// what this catches: a handed-back execution that timed out publishing nothing, so her
// panel read `[running]` forever (the M5, 2026-10-30: six long cargo runs never reported
// back). Every exit settles through one step that publishes (HER-TOOLS T2).
#[test]
fn a_handed_back_execution_that_times_out_publishes_its_completion() {
let (dir, rt) = setup_workspace();
set_shell_completion_bus(std::sync::Arc::new(crate::runtime::message_bus::MessageBus::new()));
let bus = SHELL_COMPLETION_BUS.get().expect("bus wired").clone(); // another test may have wired it first
let mut rx = bus.receiver();
let mut session = ShellSession::new("test", "p1", dir.path()).unwrap();
let id = session.execute("sleep 30", Some(300), rt.handle()).unwrap();
session.executions[&id].lock().unwrap().handed_back = true;
let handle = uuid::Uuid::parse_str(&id).unwrap();
let ended = rt.block_on(async {
loop {
// 10 s is this test's bound on a 300 ms timeout reaching the bus, not a product timeout.
let event = tokio::time::timeout(Duration::from_secs(10), rx.recv()).await.expect("completion arrives").expect("bus open");
if event.name != crate::runtime::command_events::COMMAND_COMPLETED_TOPIC {
continue;
}
let ev: crate::runtime::command_events::CommandCompletedEvent = serde_json::from_value((*event.payload).clone()).unwrap();
if ev.handle == Some(handle) {
return ev;
}
}
});
assert!(!ended.success);
assert_eq!(ended.error.as_deref(), Some("timed out at its timeout_ms"));
}
Loading