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
76 changes: 61 additions & 15 deletions crates/antfarm-core/src/claude/backfill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use super::line::{Block, UserContent};
use super::parse::{Parsed, RawLine, parse_batch};
use super::reduce::{line_delta, summarize};
use super::source::SourceStats;
use crate::input::{AgentRef, Input};
use crate::input::{AgentRef, ForkLink, Input};
use crate::model::{
AgentId, CallRecord, FileTouch, LineRefs, ParseStats, ResultStatus, SessionId, Time, ToolCallId,
};
Expand Down Expand Up @@ -88,13 +88,14 @@ fn run(
sink: &mpsc::Sender<Input>,
stats: &Mutex<SourceStats>,
) -> Result<(), Closed> {
let send = |calls, files, read, done| {
let send = |(calls, files, forks), read, done| {
sink.blocking_send(Input::Backfill {
session: job.session.clone(),
agent: job.agent.clone(),
job: job.id,
calls,
files,
forks,
read,
total: job.boundary,
done,
Expand All @@ -112,7 +113,7 @@ fn run(
Ok(f) => f,
Err(e) => {
fail(e);
return send(Vec::new(), Vec::new(), job.boundary, true);
return send(Decoded::default(), job.boundary, true);
}
};
let mut reader = BackReader::new(file, job.boundary, &TailConfig::default(), chunk);
Expand All @@ -129,12 +130,12 @@ fn run(
// The engine drops this job's batches once it hears of the truncation;
// finishing here keeps a read error from showing as loading forever.
fail(e);
return send(Vec::new(), Vec::new(), job.boundary, true);
return send(Decoded::default(), job.boundary, true);
}
};
let (calls, files) = decoder.decode(lines);
let decoded = decoder.decode(lines);
let read = job.boundary - reader.remaining();
send(calls, files, read, reader.remaining() == 0)?;
send(decoded, read, reader.remaining() == 0)?;
let mut s = stats.lock().unwrap();
s.bytes_read += read - reported;
reported = read;
Expand All @@ -147,13 +148,19 @@ fn run(
}

/// A result read before its call was.
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
struct Seen {
at: Option<Time>,
status: ResultStatus,
offset: u64,
/// The agent a forked skill's result names.
fork: Option<(String, bool)>,
}

/// One chunk's calls in file order, its edits one entry per path, and the forked skills
/// that returned in it.
pub(crate) type Decoded = (Vec<CallRecord>, Vec<FileTouch>, Vec<ForkLink>);

/// Turns chunks of lines, newest chunk first, into compact calls and file edits.
pub(crate) struct Decoder {
agent: AgentId,
Expand Down Expand Up @@ -181,17 +188,24 @@ impl Decoder {

/// Decodes one chunk, which is older than every chunk before it. Returns its calls in
/// file order and its edits, one entry per path.
pub fn decode(&mut self, lines: Vec<RawLine>) -> (Vec<CallRecord>, Vec<FileTouch>) {
pub fn decode(&mut self, lines: Vec<RawLine>) -> Decoded {
let mut stats = ParseStats::default();
let (parsed, _errors) = parse_batch(lines, &mut stats);
let mut calls = Vec::new();
let mut files: Vec<FileTouch> = Vec::new();
let mut forks = Vec::new();
for line in parsed.iter().rev() {
match &line.parsed {
Parsed::User(u) => {
let UserContent::Blocks(blocks) = &u.message.content else {
continue;
};
let fork = u
.tool_use_result
.as_ref()
.filter(|r| r.status.as_deref() == Some("forked"))
.and_then(|r| r.agent_id.clone().map(|a| (a, r.background)))
.filter(|(a, _)| !a.is_empty());
for b in blocks {
if let Block::ToolResult {
tool_use_id,
Expand All @@ -210,6 +224,7 @@ impl Decoder {
at: u.env.timestamp,
status,
offset: line.offset,
fork: fork.clone(),
},
);
}
Expand All @@ -223,16 +238,27 @@ impl Decoder {
};
let seen = self.results.remove(id);
self.touch(&mut files, name, input, at);
if let Some((agent, background)) =
seen.as_ref().and_then(|s| s.fork.as_ref())
&& name == super::subagents::FORK_TOOL
{
forks.push(ForkLink {
call: ToolCallId::from(id.as_str()),
agent: AgentId::from(agent.as_str()),
at: seen.as_ref().and_then(|s| s.at),
background: *background,
});
}
calls.push(CallRecord {
id: ToolCallId::from(id.as_str()),
name: self.name(name),
summary: summarize(name, input).into(),
at,
finished: seen.and_then(|s| s.at),
status: seen.map_or(ResultStatus::Pending, |s| s.status),
finished: seen.as_ref().and_then(|s| s.at),
status: seen.as_ref().map_or(ResultStatus::Pending, |s| s.status),
lines: LineRefs {
call: Some(line.offset),
result: seen.map(|s| s.offset),
result: seen.as_ref().map(|s| s.offset),
},
background: None,
});
Expand All @@ -242,7 +268,8 @@ impl Decoder {
}
}
calls.reverse();
(calls, files)
forks.reverse();
(calls, files, forks)
}

/// Adds an edit to the chunk's files. Lines are visited newest first, so the first
Expand Down Expand Up @@ -296,9 +323,10 @@ mod tests {
fn pairs_results_read_before_their_calls_across_chunks() {
let mut d = Decoder::new(AgentId::from("root"));
// Newest chunk first: B's result, then a chunk with A, A's result, and B's call.
let (calls, _) = d.decode(vec![raw(300, RESULT_B)]);
let (calls, _, _) = d.decode(vec![raw(300, RESULT_B)]);
assert!(calls.is_empty());
let (calls, files) = d.decode(vec![raw(0, CALL_A), raw(100, RESULT_A), raw(200, CALL_B)]);
let (calls, files, _) =
d.decode(vec![raw(0, CALL_A), raw(100, RESULT_A), raw(200, CALL_B)]);
let ids: Vec<_> = calls.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, ["ta", "tb"]);
assert_eq!(calls[0].status, ResultStatus::Ok);
Expand All @@ -316,10 +344,28 @@ mod tests {
assert_eq!((files[0].added, files[0].removed), (2, 1));
}

#[test]
fn a_forked_skill_result_becomes_a_fork_link() {
let mut d = Decoder::new(AgentId::from("root"));
let call = r#"{"type":"assistant","timestamp":"2026-11-02T10:00:00Z","message":{"id":"m1","content":[{"type":"tool_use","id":"tsk","name":"Skill","input":{"skill":"code-review"}}]}}"#;
let result = r#"{"type":"user","timestamp":"2026-11-02T10:05:00Z","message":{"content":[{"type":"tool_result","tool_use_id":"tsk","content":"done"}]},"toolUseResult":{"agentId":"afk","commandName":"code-review","status":"forked","success":true}}"#;
let (calls, _, forks) = d.decode(vec![raw(0, call), raw(200, result)]);
assert_eq!(calls.len(), 1);
assert_eq!(
forks,
[ForkLink {
call: ToolCallId::from("tsk"),
agent: AgentId::from("afk"),
at: Some("2026-11-02T10:05:00Z".parse().unwrap()),
background: false,
}]
);
}

#[test]
fn a_call_with_no_result_before_the_boundary_stays_pending() {
let mut d = Decoder::new(AgentId::from("root"));
let (calls, _) = d.decode(vec![raw(0, CALL_B)]);
let (calls, _, _) = d.decode(vec![raw(0, CALL_B)]);
assert_eq!(calls[0].status, ResultStatus::Pending);
assert_eq!(calls[0].finished, None);
}
Expand Down
2 changes: 2 additions & 0 deletions crates/antfarm-core/src/claude/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub struct SubagentMeta {
pub request_shape: Option<String>,
pub model: Option<String>,
pub finished: Option<bool>,
/// Present on a workflow's agents, which also carry no `toolUseId`.
pub workflow_phase: Option<serde_json::Value>,
}

/// `<sessionId>/workflows/wf_<id>.json`. Only the fields antfarm shows.
Expand Down
9 changes: 9 additions & 0 deletions crates/antfarm-core/src/claude/line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ impl Default for UserContent {
#[derive(Debug, Clone, Default)]
pub struct ToolUseResult {
pub is_async: bool,
/// A forked skill sent to the background, since Claude Code 2.1.325. Its result
/// returns at once and the fork finishes later, like an async `Agent` spawn.
pub background: bool,
pub status: Option<String>,
pub agent_id: Option<String>,
pub file_path: Option<String>,
Expand All @@ -158,6 +161,12 @@ impl<'de> Deserialize<'de> for ToolUseResult {
"isAsync" => {
out.is_async = map.next_value::<Option<bool>>()?.unwrap_or(false)
}
"background" => {
out.background = map
.next_value::<serde_json::Value>()?
.as_bool()
.unwrap_or(false)
}
"status" => {
out.status = map.next_value::<Option<OptString>>()?.and_then(|s| s.0)
}
Expand Down
12 changes: 10 additions & 2 deletions crates/antfarm-core/src/claude/reduce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ pub(crate) struct BackfillBatch {
pub job: u64,
pub calls: Vec<CallRecord>,
pub files: Vec<FileTouch>,
pub forks: Vec<crate::input::ForkLink>,
pub read: u64,
pub total: u64,
pub done: bool,
Expand Down Expand Up @@ -270,6 +271,10 @@ pub(crate) fn backfill(
}
a.older.prepend(batch.calls);
merge_files(&mut session.files_touched, batch.files);
for f in &batch.forks {
let (call, agent) = (&f.call, &f.agent);
super::subagents::fork_returned(session, side, call, agent, &id, f.background, f.at, em);
}
if batch.done && matches!(agent, AgentRef::Root) {
session.truncated_before = None;
}
Expand Down Expand Up @@ -708,7 +713,7 @@ fn open_call(cx: &mut Cx, id: &str, name: &str, input: &Value, group: Option<&st
},
});
agent.open.insert(call_id.clone(), call);
if super::subagents::SPAWN_TOOLS.contains(&name) {
if super::subagents::SPAWN_TOOLS.contains(&name) || name == super::subagents::FORK_TOOL {
super::subagents::spawn_opened(cx.side, &call_id, &me);
}
cx.emit(Event::ToolCallStarted {
Expand Down Expand Up @@ -897,7 +902,9 @@ fn close_call(
call: call.id.clone(),
status: call.status,
});
if super::subagents::SPAWN_TOOLS.contains(&call.name.as_str()) {
if super::subagents::SPAWN_TOOLS.contains(&call.name.as_str())
|| call.name == super::subagents::FORK_TOOL
{
let at = cx.at;
super::subagents::spawn_closed(cx.session, cx.side, &call, &owner, result, at, cx.em);
}
Expand Down Expand Up @@ -1430,6 +1437,7 @@ mod tests {
job,
calls,
files: Vec::new(),
forks: Vec::new(),
read: if done { 100 } else { 50 },
total: 100,
done,
Expand Down
Loading
Loading