Skip to content
Merged
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
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,17 @@ fuzz/artifacts/

packages/node_modules/
packages/dist/
/outputs/.drafts/atomic-neural-graph-cited.md
/outputs/.drafts/atomic-neural-graph-draft.md
/outputs/.drafts/atomic-neural-graph-research-T1.md
/outputs/.drafts/atomic-neural-graph-research-T2.md
/outputs/.drafts/atomic-neural-graph-research-T3.md
/outputs/.drafts/atomic-neural-graph-research-T4.md
/outputs/.drafts/atomic-neural-graph-research-T5.md
/outputs/.drafts/atomic-neural-graph-revised.md
/outputs/.drafts/atomic-neural-graph-verification.md
/outputs/.plans/atomic-neural-graph-T1.md
/outputs/.plans/atomic-neural-graph-T2.md
/outputs/.plans/atomic-neural-graph-T3.md
/outputs/.plans/atomic-neural-graph-T4.md
/outputs/.plans/atomic-neural-graph.md
89 changes: 88 additions & 1 deletion atomic-agent/src/turn/orchestrator/session_end.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Session end handling for the turn orchestrator.

use crate::error::AgentResult;
use crate::error::{AgentError, AgentResult};
use crate::event::TurnEvent;
use crate::record::{record_turn, TurnRecordOptions};
use crate::turn::phase::{self, Event, Phase, TransitionContext};

use super::{DispatchResult, TurnOrchestrator};
Expand Down Expand Up @@ -42,6 +43,92 @@ impl TurnOrchestrator {
}
}

// Flush any unrecorded turn BEFORE finalizing. Headless agents such as
// Cursor's CLI fire sessionStart/postToolUse/sessionEnd but no per-turn
// `stop` (TurnEnd), so the turn's file changes are still uncommitted at
// session end. Record them now — crucially *before* switching back to
// the parent view below, which restores the working copy and would
// otherwise discard the agent's work. Idempotent: agents that already
// recorded each turn on `stop` leave a clean working copy here, so
// `record_turn` returns `EmptyTurn` and this is a no-op for them.
{
// Ensure the working copy is on the session's agent view before
// recording. session-start aligns to it, but that can drift back to
// the parent view by session end (observed with Cursor's CLI), which
// makes `record_turn` see a view mismatch and record nothing. Align
// explicitly so the agent's uncommitted files are recorded on the
// agent view. Best-effort — non-fatal if it can't switch.
match atomic_repository::Repository::open_existing(&self.repo_root) {
Ok(mut repo) => {
if repo.current_view() != session.view_name {
if let Err(e) = repo.align_to_view(&session.view_name) {
log::warn!(
"SessionEnd: could not align to agent view '{}': {} (non-fatal)",
session.view_name,
e,
);
} else {
log::info!(
"SessionEnd: aligned working copy to agent view '{}' before flush",
session.view_name,
);
}
}
}
Err(e) => log::warn!(
"SessionEnd: could not open repo to align view: {} (non-fatal)",
e
),
}

let prompt = event
.prompt
.clone()
.or_else(|| session.current_prompt.clone())
.or_else(|| session.first_prompt.clone());
let turn_number = session.turn_count + 1;
let turn_duration_ms = session.current_turn_duration_ms().unwrap_or(0);
let record_result = {
let record_options = TurnRecordOptions {
session: &session,
event: &event,
turn_number,
turn_duration_ms,
prompt,
};
record_turn(&self.repo_root, &record_options)
};
match record_result {
Ok(outcome) => {
session.end_turn();
let recorded_files: Vec<String> = outcome.recorded_file_list().to_vec();
session.add_files_touched(&recorded_files);
session.recorded_change_hashes.push(outcome.hash);
session.clear_current_prompt();
self.inject_reasoning_nodes(session_id, &event);
self.save_turn_provenance(session_id, &session, &outcome, &event);
log::info!(
"SessionEnd flushed a pending turn for session {}: {}",
session_id,
outcome
);
}
Err(AgentError::EmptyTurn { .. }) => {
log::info!(
"SessionEnd for session {}: no pending changes to flush",
session_id
);
}
Err(e) => {
log::error!(
"SessionEnd flush-record failed for session {}: {}",
session_id,
e
);
}
}
}

// State machine transition
let result = phase::transition(
session.phase,
Expand Down
76 changes: 45 additions & 31 deletions atomic-cli/src/commands/view/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,24 @@
//! atomic view list [OPTIONS]
//!
//! Options:
//! -v, --verbose Show additional details (state hash, change count)
//! -s, --short Show only view names (no metadata)
//! -h, --help Print help information
//! ```
//!
//! # Examples
//!
//! List all views:
//! List all views (default — shows metadata):
//! ```text
//! $ atomic view list
//! dev
//! * feature-auth
//! release-1.0
//! dev [shared] (3 changes) state: 2AAAAAAAA...
//! * feature-auth [draft] (2 changes, 3 inherited) state: XYZABCDEF... parent: dev
//! ```
//!
//! List with verbose output:
//! Short listing (names only):
//! ```text
//! $ atomic view list --verbose
//! dev (0 changes) state: 2AAAAAAAA...
//! * feature-auth (3 changes) state: XYZABCDEF...
//! release-1.0 (10 changes) state: 123456789...
//! $ atomic view list --short
//! dev
//! * feature-auth
//! ```

use clap::Parser;
Expand All @@ -47,22 +45,29 @@ use std::path::PathBuf;
/// List all views.
///
/// Shows all views in the repository with the current view marked
/// with an asterisk (*).
/// with an asterisk (*). By default, displays metadata (scope, change
/// count, state hash, parent). Use `--short` for names only.
#[derive(Parser, Debug, Default)]
#[command(name = "list")]
pub struct List {
/// Show only view names (no metadata).
#[arg(long, short = 's')]
pub short: bool,

/// Show additional details (state hash, change count).
///
/// When enabled, displays the Merkle state hash and number of
/// changes for each view.
#[arg(long, short = 'v')]
/// This is now the default behavior. Kept for backward compatibility.
#[arg(long, short = 'v', hide = true)]
pub verbose: bool,
}

impl List {
/// Create a new List command with default settings.
pub fn new() -> Self {
Self { verbose: false }
Self {
short: false,
verbose: false,
}
}

/// Builder: set the verbose flag.
Expand Down Expand Up @@ -99,22 +104,18 @@ impl Command for List {
let mut sorted_views = views;
sorted_views.sort();

// Calculate padding for alignment in verbose mode
// Calculate padding for alignment
let max_name_len = sorted_views.iter().map(|s| s.len()).max().unwrap_or(0);

for view in sorted_views {
let is_current = view == current;
let marker = if is_current { "*" } else { " " };

if self.verbose {
// Get view info for verbose output
if self.short {
println!("{} {}", marker, style_view(&view));
} else {
match repo.get_view_info(&view) {
Ok(info) => {
let change_word = if info.change_count == 1 {
"change"
} else {
"changes"
};
let kind_tag = match info.kind_label() {
"draft" => "[draft]",
_ => "[shared]",
Expand All @@ -123,13 +124,27 @@ impl Command for List {
Some(p) => format!(" parent: {}", style_view(p)),
None => String::new(),
};
// Show own changes for views with a parent;
// show total for root views.
let change_display = if info.parent_name.is_some() {
let own = info.own_change_count;
let inherited = info.change_count.saturating_sub(info.own_change_count);
if own == 1 {
format!("({} change, {} inherited)", own, inherited)
} else {
format!("({} changes, {} inherited)", own, inherited)
}
} else if info.change_count == 1 {
format!("({} change)", info.change_count)
} else {
format!("({} changes)", info.change_count)
};
println!(
"{} {:<width$} {:<10} ({} {}) state: {}{}",
"{} {:<width$} {:<10} {} state: {}{}",
marker,
style_view(&view),
kind_tag,
info.change_count,
change_word,
change_display,
info.state_short(),
parent_info,
width = max_name_len
Expand All @@ -140,8 +155,6 @@ impl Command for List {
println!("{} {}", marker, style_view(&view));
}
}
} else {
println!("{} {}", marker, style_view(&view));
}
}

Expand Down Expand Up @@ -185,13 +198,14 @@ mod tests {
#[test]
fn test_default() {
let cmd = List::default();
assert!(!cmd.short);
assert!(!cmd.verbose);
}

#[test]
fn test_new() {
let cmd = List::new();
assert!(!cmd.verbose);
assert!(!cmd.short);
}

#[test]
Expand Down Expand Up @@ -221,7 +235,7 @@ mod tests {
// Change to the repo directory
std::env::set_current_dir(repo_path).unwrap();

// List views
// List views (default = verbose)
let cmd = List::new();
let result = cmd.run();
assert!(result.is_ok());
Expand Down Expand Up @@ -271,7 +285,7 @@ mod tests {
// Change to the repo directory
std::env::set_current_dir(repo_path).unwrap();

// List views with verbose output
// List views with verbose output (same as default now)
let cmd = List::new().with_verbose(true);
let result = cmd.run();
assert!(result.is_ok());
Expand Down
Loading
Loading