Skip to content

Commit 5a3b8fb

Browse files
committed
fix(claude): group pruned sessions across roots and flat agent files
Key sessions relative to `projects/` so a copy in another config root is kept with the live original, and key legacy flat `agent-*.jsonl` transcripts on the `sessionId` inside them so sidechain replays still meet their parents. The statusline active block also reads the full history when entries are future-dated, since a pause before such an entry could otherwise anchor blocks after the current one.
1 parent 72ebaca commit 5a3b8fb

3 files changed

Lines changed: 139 additions & 22 deletions

File tree

‎rust/adapters/claude/src/paths.rs‎

Lines changed: 82 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,13 @@ pub(super) struct SinceFiles {
9191
///
9292
/// Claude session JSONL files are append-only, so a file last written before
9393
/// the window opened cannot hold an entry inside it. Files are kept or dropped
94-
/// per session, the main transcript together with its subagent transcripts,
95-
/// because deduplication matches sidechain replays against their parent
96-
/// messages within a session; dropping the parent file alone would let a
97-
/// replay count twice. Only the file list is narrowed; entries parsed from a
94+
/// per session, the main transcript together with its subagent transcripts
95+
/// and any copy in another config root, because deduplication matches
96+
/// sidechain replays against their parent messages within a session; dropping
97+
/// the parent file alone would let a replay count twice. Copies of a message
98+
/// in other sessions, such as resumed transcripts, keep the original
99+
/// timestamp, so they fall on the same side of the window as the original.
100+
/// Only the file list is narrowed; entries parsed from a
98101
/// surviving file are untouched. Every file is kept when `since` is unset or
99102
/// unparsable, when the window opens ahead of the current clock, or when a
100103
/// file's mtime cannot be read.
@@ -128,32 +131,56 @@ pub(super) fn split_files_before_since(
128131
.iter()
129132
.filter(|file| file_modified_millis(file).is_none_or(|modified| modified >= threshold))
130133
.map(|file| session_group_key(file))
131-
.collect::<FxHashSet<_>>();
134+
.collect::<FxHashSet<String>>();
132135
let (kept, pruned) = files
133136
.into_iter()
134137
.partition(|file| live_sessions.contains(&session_group_key(file)));
135138
SinceFiles { kept, pruned }
136139
}
137140

138-
/// Identifies the session a usage file belongs to, so `<session>.jsonl` and
139-
/// everything under `<session>/` (such as `subagents/`) share one key.
140-
/// Paths outside the `projects/<project>/<session>` layout key on themselves.
141-
fn session_group_key(path: &Path) -> PathBuf {
142-
let components = path.components().collect::<Vec<_>>();
143-
let Some(projects_index) = components
141+
/// Identifies the session a usage file belongs to, relative to `projects/`
142+
/// so a session copied into another config root shares one key.
143+
///
144+
/// `<session>.jsonl` and everything under `<session>/` (such as `subagents/`)
145+
/// share a key. Legacy flat `agent-*.jsonl` sidechain transcripts sit beside
146+
/// their parent, so they key on the `sessionId` recorded inside them. Paths
147+
/// outside the `projects/<project>/<session>` layout key on themselves.
148+
fn session_group_key(path: &Path) -> String {
149+
let components = path
150+
.components()
151+
.map(|component| component.as_os_str().to_string_lossy())
152+
.collect::<Vec<_>>();
153+
let relative = components
144154
.iter()
145-
.position(|component| component.as_os_str() == "projects")
146-
else {
147-
return path.to_path_buf();
155+
.position(|component| component == "projects")
156+
.map(|index| &components[index + 1..]);
157+
let Some([project, session, rest @ ..]) = relative else {
158+
return path.to_string_lossy().into_owned();
148159
};
149-
// `projects/<project>/<session>.jsonl` or `projects/<project>/<session>/...`
150-
let Some(session) = components.get(projects_index + 2) else {
151-
return path.to_path_buf();
152-
};
153-
let mut key = components[..projects_index + 2].iter().collect::<PathBuf>();
154-
let session = session.as_os_str().to_string_lossy();
155-
key.push(session.strip_suffix(".jsonl").unwrap_or(&session));
156-
key
160+
let session = session.strip_suffix(".jsonl").unwrap_or(session);
161+
if rest.is_empty()
162+
&& session.starts_with("agent-")
163+
&& let Some(parent_session) = recorded_session_id(path)
164+
{
165+
return format!("{project}/{parent_session}");
166+
}
167+
format!("{project}/{session}")
168+
}
169+
170+
/// Reads the first `sessionId` recorded in a transcript without parsing it.
171+
fn recorded_session_id(path: &Path) -> Option<String> {
172+
use std::io::Read as _;
173+
174+
const MARKER: &[u8] = br#""sessionId":""#;
175+
let mut head = Vec::new();
176+
fs::File::open(path)
177+
.ok()?
178+
.take(64 * 1024)
179+
.read_to_end(&mut head)
180+
.ok()?;
181+
let start = memmem::find(&head, MARKER)? + MARKER.len();
182+
let end = memchr::memchr(b'"', &head[start..])? + start;
183+
String::from_utf8(head[start..end].to_vec()).ok()
157184
}
158185

159186
fn file_modified_millis(path: &Path) -> Option<i64> {
@@ -403,4 +430,37 @@ mod tests {
403430
assert_eq!(split.kept, [live_parent, live_agent]);
404431
assert_eq!(split.pruned, [stale_parent, stale_agent]);
405432
}
433+
434+
#[test]
435+
fn keeps_legacy_flat_agent_transcripts_and_config_root_copies_with_their_session() {
436+
let fixture = fs_fixture!({
437+
"a/projects/p/live.jsonl": "{}",
438+
"a/projects/p/agent-1234.jsonl": r#"{"sessionId":"live","timestamp":"2026-09-01T12:00:00Z"}"#,
439+
"a/projects/p/agent-5678.jsonl": r#"{"sessionId":"stale","timestamp":"2026-09-01T12:00:00Z"}"#,
440+
"b/projects/p/live.jsonl": "{}",
441+
});
442+
let root = fixture.root();
443+
let live = root.join("a/projects/p/live.jsonl");
444+
let live_agent = root.join("a/projects/p/agent-1234.jsonl");
445+
let stale_agent = root.join("a/projects/p/agent-5678.jsonl");
446+
let other_root_copy = root.join("b/projects/p/live.jsonl");
447+
set_file_modified(&live, ts("2026-09-21T12:00:00Z"));
448+
for stale in [&live_agent, &stale_agent, &other_root_copy] {
449+
set_file_modified(stale, ts("2026-09-01T12:00:00Z"));
450+
}
451+
452+
let split = split_files_before_since(
453+
vec![
454+
live_agent.clone(),
455+
stale_agent.clone(),
456+
live.clone(),
457+
other_root_copy.clone(),
458+
],
459+
&shared_since(Some("20260920")),
460+
ts("2026-09-24T00:00:00Z"),
461+
);
462+
463+
assert_eq!(split.kept, [live_agent, live, other_root_copy]);
464+
assert_eq!(split.pruned, [stale_agent]);
465+
}
406466
}

‎rust/crates/ccusage/src/commands/mod.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,7 @@ fn load_statusline_active_block(
590590
return find_active_block(entries);
591591
}
592592
BlockAnchor::NeedsMoreHistory => {}
593+
BlockAnchor::NeedsFullHistory => break,
593594
}
594595
}
595596
find_active_block(load_entries(shared, None).ok()?)
@@ -609,6 +610,9 @@ enum BlockAnchor {
609610
From(TimestampMs),
610611
/// The window holds no pause long enough to anchor block boundaries.
611612
NeedsMoreHistory,
613+
/// Future-dated entries can form blocks after the current one, so only
614+
/// the unbounded selection is safe.
615+
NeedsFullHistory,
612616
}
613617

614618
/// Decides whether the entries inside a window pin down the active block.
@@ -627,6 +631,9 @@ fn statusline_block_anchor(
627631
let Some(&last) = timestamps.last() else {
628632
return BlockAnchor::NoActiveBlock;
629633
};
634+
if last > now {
635+
return BlockAnchor::NeedsFullHistory;
636+
}
630637
if now.duration_since(last) >= session_ms {
631638
return BlockAnchor::NoActiveBlock;
632639
}
@@ -1270,6 +1277,11 @@ mod tests {
12701277
statusline_block_anchor(&[at(9), at(4), at(1)], now, session),
12711278
BlockAnchor::NeedsMoreHistory
12721279
);
1280+
// A gap before a future-dated entry must not hide the current block.
1281+
assert_eq!(
1282+
statusline_block_anchor(&[at(1), at(-8)], now, session),
1283+
BlockAnchor::NeedsFullHistory
1284+
);
12731285
}
12741286

12751287
#[test]

‎rust/crates/ccusage/tests/claude_cli.rs‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,48 @@ fn bounded_unified_reports_still_detect_claude_with_only_stale_files() {
479479
);
480480
assert!(output.contains("Detected: Claude"), "{output}");
481481
}
482+
483+
#[test]
484+
fn statusline_keeps_the_current_block_before_future_dated_entries() {
485+
let fixture = Fixture::new();
486+
let now_ms = i64::try_from(
487+
std::time::SystemTime::now()
488+
.duration_since(std::time::UNIX_EPOCH)
489+
.unwrap()
490+
.as_millis(),
491+
)
492+
.unwrap();
493+
let at = |offset_hours: i64| {
494+
ccusage_core::format_rfc3339_millis(ccusage_core::TimestampMs::from_millis(
495+
now_ms + offset_hours * 60 * 60 * 1000,
496+
))
497+
};
498+
// A skewed clock wrote an entry eight hours ahead, after a long pause.
499+
let transcript = fixture.write_file(
500+
"projects/project-a/session-now.jsonl",
501+
[
502+
usage_line(&at(-1), "session-now", "msg-now", "req-now", 1.0),
503+
usage_line(&at(8), "session-now", "msg-future", "req-future", 9.0),
504+
]
505+
.join("\n"),
506+
);
507+
let hook = format!(
508+
r#"{{"session_id":"session-now","transcript_path":"{}","model":{{"display_name":"Model"}},"cost":{{"total_cost_usd":0}},"context_window":{{"total_input_tokens":1,"context_window_size":100}}}}"#,
509+
transcript.display()
510+
);
511+
512+
let output = run_ccusage(
513+
&fixture,
514+
&[
515+
"statusline",
516+
"--offline",
517+
"--no-cache",
518+
"--cost-source",
519+
"cc",
520+
"--timezone",
521+
"UTC",
522+
],
523+
Some(&hook),
524+
);
525+
assert!(output.contains("$1.00 block"), "{output}");
526+
}

0 commit comments

Comments
 (0)