From 2071a695c8e08a2540594619bc6a52363e4792b0 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 13:14:00 +0800 Subject: [PATCH 1/8] feat(branch): let the root and the default branch open lines The tool's `create` admits the root in every state and the current default branch while it holds the role; every other line is refused `branch_not_opener` and writes nothing. A plugin line is never an opener, and a former default branch keeps the lines it opened and coordinates them but opens none. The admission is taken in the lock that reserves the line, so a move that lands while a creation is in flight cannot admit a caller the tree no longer has as an opener. The texts that state who opens a line now name both openers, a status note tells a line taking the role that it may open lines and a line losing it that it may not, and the tool description's last sentence states the reach of messages and of `end`. --- .../src/timeline_tree.rs | 95 +++- .../tests/branch_flow.rs | 501 +++++++++++++++++- crates/dim-agent-runtime/src/error.rs | 11 +- .../rust-agent/generated/modules.json | 1 + 4 files changed, 568 insertions(+), 40 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index d9193311d3..c7f6f556bc 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -275,21 +275,27 @@ impl TreeCommands { options: BranchOptions, admission: CancellationToken, ) -> Result { - self.branch_with_idle_notice(parent, at, options, admission, IdleNotice::Steer) + self.tree + .upgrade() + .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? + .create_child(parent, at, options, admission, None) .await } - async fn branch_with_idle_notice( + /// Opens a line for the `branch` tool: the caller's eligibility and the + /// Session's cap are charged in the same lock that reserves the line (§4, + /// §6.1). + async fn open_tool_line( &self, parent: String, at: u64, options: BranchOptions, admission: CancellationToken, - idle_notice: IdleNotice, + open: ToolOpen, ) -> Result { self.tree .upgrade() .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .create_child(parent, at, options, admission, idle_notice) + .create_child(parent, at, options, admission, Some(open)) .await } // The data methods below spell out `std::result::Result` for rutis' @@ -1727,6 +1733,25 @@ impl TimelineTree { .clone() .ok_or_else(|| AgentError::UnknownBranch(id.into())) } + /// Admits one open by the `branch` tool where the line it opens is + /// reserved: under the same lock, so the caller's eligibility and the + /// Session's counted total are the state the reservation is taken in (§4, + /// §6.1). A refusal writes nothing. + fn admit_open(state: &TreeState, opener: &str) -> Result<()> { + if !Self::can_open(state, opener) { + return Err(AgentError::refused( + BranchRefusal::NotOpener, + format!("line {opener} is not the root or the default branch"), + )); + } + Ok(()) + } + /// The Session's two openers: the root in every state, and the current + /// default branch while it holds the role (§4, §11). A plugin line is + /// never either. + fn can_open(state: &TreeState, line: &str) -> bool { + line == ROOT_BRANCH_ID || line == state.default.as_str() + } /// Whether `id` is above the current default branch: the default's parent /// chain goes through it. fn protects(state: &TreeState, id: &str) -> bool { @@ -2272,7 +2297,7 @@ impl TimelineTree { at: u64, options: BranchOptions, admission: CancellationToken, - idle_notice: IdleNotice, + open: Option, ) -> BoxFuture<'_, Result> { Box::pin(async move { if self.state.lock().unwrap().ended.contains_key(&parent) { @@ -2327,6 +2352,9 @@ impl TimelineTree { return Err(AgentError::Cancelled("branch admission".into())); } let mut state = self.state.lock().unwrap(); + if let Some(open) = open { + Self::admit_open(&state, &parent)?; + } let mut above = Some(parent.clone()); while let Some(id) = above { if state.ended.contains_key(&id) { @@ -2350,7 +2378,7 @@ impl TimelineTree { create_anchor: Some(event.sequence), source: Some(final_data.source.clone()), }, - idle_notice, + open.map_or(IdleNotice::Steer, |open| open.idle_notice), )?); Ok(()) })?; @@ -2816,7 +2844,7 @@ impl TimelineTreeControl for TimelineTree { options: BranchOptions, admission: CancellationToken, ) -> BoxFuture<'_, Result> { - self.create_child(parent, at, options, admission, IdleNotice::Steer) + self.create_child(parent, at, options, admission, None) } fn get(&self, id: &str) -> Option { self.state.lock().unwrap().nodes.get(id).and_then(|node| { @@ -3136,6 +3164,13 @@ enum IdleNotice { Steer, None, } +/// An open by the `branch` tool: the notice the new line gives its opener when +/// a turn ends quietly. The tree reads the caller's eligibility in the lock +/// that reserves the line (§4). +#[derive(Clone, Copy)] +struct ToolOpen { + idle_notice: IdleNotice, +} const QUIET_IDLE_ATTRIBUTE: &str = "idle-notice"; /// One line its parent opened, as the parent's own facts recorded it. struct Child { @@ -4849,7 +4884,7 @@ impl BranchTool { }; crate::context_policy::check_cancel(&cancel)?; match input.action.as_str() { - "create" => self.create(&own, input, &context, &call.id, cancel).await, + "create" => self.create(input, &context, &call.id, cancel).await, "message" => self.message(&own, input).await, "read" => self.read(&own, input, &line).await, "end" => tokio::select! { @@ -4862,18 +4897,11 @@ impl BranchTool { /// Opens a tool line cut before this request's model start (design §11). async fn create( &self, - own: &OwnLine, input: BranchInput, context: &ToolExecutionContext, call_id: &str, cancel: CancellationToken, ) -> std::result::Result { - if own.role != LineRole::Main { - return Ok(refusal( - "branch_not_main", - "Only main opens lines. Tell main if more parallel work is needed.".into(), - )); - } let prompt = input.prompt.unwrap_or_default(); if prompt.is_empty() { return Err(invalid("create requires a nonempty prompt")); @@ -4970,9 +4998,9 @@ impl BranchTool { sequence.as_u64().expect("event sequence is unsigned") - 1 } }; - let branch = self + let opened = self .tree - .branch_with_idle_notice( + .open_tool_line( context.branch_id.clone(), at, BranchOptions { @@ -4984,14 +5012,20 @@ impl BranchTool { }, }, cancel, - input.idle_notice, + ToolOpen { + idle_notice: input.idle_notice, + }, ) - .await - .map_err(|error| match error { - AgentError::Cancelled(reason) => HostError::Cancelled(reason), - error => HostError::failed(error.to_string()), - })?; - Ok(ToolResult::text(format!("Line created: {}", branch.id()))) + .await; + match opened { + Ok(branch) => Ok(ToolResult::text(format!("Line created: {}", branch.id()))), + Err(AgentError::BranchRefused { + refusal: BranchRefusal::NotOpener, + .. + }) => Ok(refusal("branch_not_opener", NOT_OPENER_TEXT.into())), + Err(AgentError::Cancelled(reason)) => Err(HostError::Cancelled(reason)), + Err(error) => Err(HostError::failed(error.to_string())), + } } /// Sends one message to a line of the calling line's pair (design §6). async fn message( @@ -5662,7 +5696,7 @@ fn tool_line_body(line: &str, parent: &str, prompt: &str) -> String { prompt, String::new(), format!("How you work with {parent}:"), - format!("- Work on this purpose only. You cannot open lines; if more parallel work is needed, tell {parent}."), + format!("- Work on this purpose only. You cannot open lines unless this line is the default branch of the session, and this block does not make it one: a status note would. If more parallel work is needed and you cannot open a line, tell {parent}."), format!("- Read {parent} with the branch tool (action read, branch \"{parent}\") when what {parent} did or decided since your cut changes your work; the parent block reports when {parent} has moved. Message {parent} only for what it must act on: a decision that changes its work, a blocker only the user can settle, a conflict with another line, or a change to your purpose. Use mode \"steer\" for what {parent} must act on now, \"append\" for what {parent} should see at its next step. Do not send {parent} a progress report it can read, and do not page through {parent}'s whole stream: read the page that answers your question, then act."), format!("- You share the workspace with {parent} and its other lines. Change only the files {parent} gave you; before changing any other file, tell {parent} which. If edit or write fails because the file was modified after it was last read, another line may have changed the file: read it again and tell {parent} before you continue."), "- The user can talk to you directly. Answer the user, and ask with ask_user when only the user can decide.".to_string(), @@ -5725,15 +5759,15 @@ fn status_note( let change = if default { match kind { "tool" => format!( - "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." + "This line is now the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {other} stays open and keeps the lines it opened." ), _ => format!( - "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." + "The user has now made this line the session's default branch, switched from line {other}. While this block is your latest one: answer the user here; you can open lines with create; you cannot call end on yourself; the user ends this line. Line {other} stays open and keeps the lines it opened." ), } } else { format!( - "Line {other} is now the session's default branch. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; the rest of the rules above hold again." + "Line {other} is now the session's default branch. This line stays open, reports to {parent} as before and keeps coordinating the lines it opened; it can no longer open lines with create, and the rest of the rules above hold again." ) }; let body = format!("{birth}\n\n{change}"); @@ -5749,10 +5783,13 @@ fn status_note( crate::context_block::element("dim-branch-line", &attrs, &body) } +/// The `branch` tool's refusal of `create` on a line that is neither the root +/// nor the default branch (design §4, §11). +const NOT_OPENER_TEXT: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; /// The `branch` tool's description: its policy sentences are the coordination /// text for `main` ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), /// replaceable at [`BranchToolConfig`]. -const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (main only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line reads the line it was cut from; main reads the lines it opened. Messages pass only between main and the lines it opened."; +const BRANCH_TOOL_DESCRIPTION: &str = "Work with the other lines of this session. A line is you: it starts from your history at the point it is opened, then works in parallel on its own line. It is not a helper with its own memory, and it owes you no result; you and it keep each other informed by reading each other's work and messaging what the other must act on. On main you coordinate: answer a line's steer and act on what it asks for; leave a line's part to that line instead of redoing it; read a line's work instead of waiting for a report.\n- create (the root and the current default branch only): open a line to work on prompt in parallel. Open one line per part that can go on at the same time as the rest — separate files, a separate question, or a second approach — instead of doing those parts one after another yourself; not for a single quick edit, nor when your next step needs its result. Write prompt as a brief to yourself: the purpose, what you already know that it needs, which files or area are its own, and when it should tell you or end. Returns the line's id.\n- message: send content to a line you opened, or to the line that opened you. Send a decision, a blocker, or a conflict, not a progress report the receiver can read. Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line. Use \"steer\" when the receiver must act now or is idle.\n- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended. With no after, a read continues after your last read of that line: from your cut for the line you were cut from, and from its first event for a line you opened. Pass after to read from another point. Do not page through a whole line.\n- end: on a line opened with create, end your own line. content is your final message to the line that opened you: what you found, did, changed and left undone. It is your last action.\nA line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only."; /// Factory configuration of the branch tool ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). /// The product sets none of it, so the built-in text is in force. diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 8b0fb8f436..32c44f406d 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -3708,8 +3708,9 @@ async fn a_refused_branch_call_writes_nothing() { ) .await, ( - "branch_not_main".into(), - "Only main opens lines. Tell main if more parallel work is needed.".into() + "branch_not_opener".into(), + "Only the root and the default branch open lines. Tell one of them if more parallel work is needed." + .into() ) ); assert!( @@ -4309,14 +4310,30 @@ async fn session_close_cancels_an_active_build_and_waits_for_rollback() { } async fn open_line(session: &Session, purpose: &str) -> String { - let before: std::collections::BTreeSet = session + open_line_from(session, "main", purpose).await +} + +/// Opens a tool line from `opener`, which must be the root or the current +/// default branch, and waits until it is idle. +async fn open_line_from(session: &Session, opener: &str, purpose: &str) -> String { + let before = line_ids(session); + let call = serde_json::json!({"action": "create", "prompt": purpose}).to_string(); + let result = tool_call(session, opener, &call).await; + assert_eq!(result.is_error, None, "{:?}", result.content); + wait_new_line(session, &before).await +} + +/// The open lines' ids at this moment. +fn line_ids(session: &Session) -> std::collections::BTreeSet { + session .branches() .iter() .map(|info| info.id.clone()) - .collect(); - let call = serde_json::json!({"action": "create", "prompt": purpose}).to_string(); - let result = tool_call(session, "main", &call).await; - assert_eq!(result.is_error, None, "{:?}", result.content); + .collect() +} + +/// Waits until a line outside `before` is listed and idle, and answers its id. +async fn wait_new_line(session: &Session, before: &std::collections::BTreeSet) -> String { let child = soon(async { loop { let opened = session @@ -4765,7 +4782,7 @@ async fn the_branch_tool_declares_its_actions_and_modes() { serde_json::json!(200) ); for sentence in [ - "- create (main only): open a line to work on prompt in parallel.", + "- create (the root and the current default branch only): open a line to work on prompt in parallel.", "- message: send content to a line you opened, or to the line that opened you.", "Mode \"append\" (default) reaches the receiver at its next step without interrupting it and does not wake an idle line.", "- read: show a page of the activity of the line you were cut from, or of a line you opened, also after it ended.", @@ -4774,7 +4791,7 @@ async fn the_branch_tool_declares_its_actions_and_modes() { "- end: on a line opened with create, end your own line.", "Returns the line's id.", "It is your last action.", - "A line reads the line it was cut from; main reads the lines it opened. Messages pass only between main and the lines it opened.", + "A line messages and reads the line it was cut from and the lines it opened. The end action ends the calling line only.", ] { assert!( branch.description.contains(sentence), @@ -11872,3 +11889,469 @@ async fn restore_default(store: &Arc, id: &str) -> String { soon(restored.close()).await.unwrap(); default } + +/// Moves the Session's conversation to `line` and answers once the move is +/// durable; a participant's note may still be on its way. +async fn switch(session: &Session, line: &str) { + soon(session.set_default_branch( + line, + BranchSource::User { + operation_id: "switch".into(), + }, + )) + .await + .unwrap(); +} + +const NOT_OPENER: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; + +/// §20.29: the root opens a line while another line is the default branch, so +/// the new line starts from the root's history at the cut the root names, +/// reports to the root, and the default branch hears nothing about it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_root_opens_a_line_while_another_line_is_default() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = open_line(&session, "b").await; + switch(&session, &b).await; + let note = line_block( + &until_events(&session, &b, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="true""#)) + }) + .await, + ) + .expect("the move wrote its note"); + assert!( + note.0.contains("you can open lines with create"), + "the default branch holds the right the root keeps: {}", + note.0 + ); + let before = line_ids(&session); + let cut = session.sequence("main").unwrap(); + let result = tool_call( + &session, + "main", + &format!(r#"{{"action":"create","prompt":"c","at":{cut}}}"#), + ) + .await; + assert_eq!(result.is_error, None, "{:?}", result.content); + let c = wait_new_line(&session, &before).await; + let info = session + .branches() + .into_iter() + .find(|info| info.id == c) + .expect("the root opened C"); + assert_eq!( + info.parent.as_deref(), + Some("main"), + "C is cut from the root" + ); + assert_eq!( + info.branch_point, + Some(cut), + "C starts where the root's own history stood" + ); + let prefix = chain_events(&session, &c, ..=cut).await.unwrap(); + assert_eq!(prefix[0].sequence, 1, "C inherits the root's history"); + assert!( + prefix.last().is_some_and(|event| event.sequence < cut), + "C inherits the root's history only through its cut" + ); + let roster = until_events(&session, "main", |events| { + roster_block(events).is_some_and(|(text, retired)| !retired && text.contains(&c)) + }) + .await; + assert!( + roster_block(&roster) + .expect("the roster is live") + .0 + .contains(&format!("- {c}: c")), + "the root lists C under its purpose: {roster:?}" + ); + let ended = tool_call( + &session, + &c, + r#"{"action":"end","content":"c is finished"}"#, + ) + .await; + assert_eq!(ended.is_error, None, "{:?}", ended.content); + until_events(&session, "main", |events| { + blocks_with(events, "]| { + events.iter().any(|event| { + matches!(&event.kind, EventKind::InputMessage(data) + if data.blocks.iter().any(|block| matches!(block, + InputBlock::Raw { text, .. } if text.contains(&c) || text.contains("c is finished")))) + }) + }; + assert!( + !about_c(&local_events(&session, &b).await), + "the default branch hears nothing about the root's line, neither its open nor its end" + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.23: the current default branch opens a line of its own, which reports to +/// it and not to the root. The note a move writes on it states the rule. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_default_branch_opens_a_line() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = open_line(&session, "b").await; + switch(&session, &b).await; + let note = line_block( + &until_events(&session, &b, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="true""#)) + }) + .await, + ) + .expect("the move wrote its note"); + assert!( + note.0.contains("you can open lines with create"), + "the note states the rule the tool applies: {}", + note.0 + ); + let c = open_line_from(&session, &b, "c").await; + let info = session + .branches() + .into_iter() + .find(|info| info.id == c) + .expect("B opened C"); + assert_eq!(info.parent.as_deref(), Some(b.as_str())); + let roster = until_events(&session, &b, |events| { + roster_block(events).is_some_and(|(text, retired)| !retired && text.contains(&c)) + }) + .await; + assert!( + roster_block(&roster) + .expect("B holds its own roster") + .0 + .contains(&format!("- {c}: c")), + "the opener lists the line it opened: {roster:?}" + ); + assert!( + !blocks_with(&local_events(&session, "main").await, "" + )), + "{:?}", + opening[0] + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.32: every line but the two openers is refused `create` and writes +/// nothing. A former default branch keeps its lines, messages and reads them. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_former_default_branch_keeps_its_lines_and_opens_none() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + switch(&session, &a).await; + until_events(&session, &a, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="true""#)) + }) + .await; + let t = open_line_from(&session, &a, "t").await; + assert!( + roster_block(&local_events(&session, &a).await) + .is_some_and(|(text, retired)| !retired && text.contains(&t)), + "A coordinates T while it holds the role" + ); + switch(&session, "main").await; + let note = line_block( + &until_events(&session, &a, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="false""#)) + }) + .await, + ) + .expect("the move back wrote A's note"); + assert!( + note.0.contains("it can no longer open lines with create"), + "the note says what A lost: {}", + note.0 + ); + let before = line_ids(&session); + let creates = |events: Vec>| { + events + .iter() + .filter(|event| matches!(event.kind, EventKind::BranchCreate(_))) + .count() + }; + let written = creates(local_events(&session, &a).await); + assert_eq!( + call(&session, &a, r#"{"action":"create","prompt":"grandchild"}"#).await, + ("branch_not_opener".into(), NOT_OPENER.into()) + ); + assert_eq!(line_ids(&session), before, "the refusal created no line"); + assert_eq!( + creates(local_events(&session, &a).await), + written, + "the refusal wrote nothing on A" + ); + let sent = tool_call( + &session, + &a, + &format!(r#"{{"action":"message","to":"{t}","content":"keep going"}}"#), + ) + .await; + assert_eq!(sent.is_error, None, "{:?}", sent.content); + let page = page_of( + &tool_call( + &session, + &a, + &format!(r#"{{"action":"read","branch":"{t}"}}"#), + ) + .await, + ); + assert!( + !page_sequences(&page).is_empty(), + "A still reads the line it opened: {page:?}" + ); + assert!( + roster_block(&local_events(&session, &a).await) + .is_some_and(|(text, retired)| !retired && text.contains(&format!("- {t}: t"))), + "A keeps its roster after losing the role" + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.32: a plugin line is never an opener, whatever it is. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_plugin_line_never_opens_a_line() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let host = open_host_line(&session, "main", "a plugin line").await; + let before = line_ids(&session); + assert_eq!( + call(&session, &host, r#"{"action":"create","prompt":"child"}"#).await, + ("branch_not_opener".into(), NOT_OPENER.into()) + ); + assert_eq!(line_ids(&session), before); + assert!( + !local_events(&session, &host) + .await + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreate(_))), + "the refusal wrote nothing" + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.3, §20.32: a tool line that is not the default branch is refused and +/// writes nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_tool_line_still_cannot_open_a_line() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + let before = line_ids(&session); + assert_eq!( + call(&session, &a, r#"{"action":"create","prompt":"child"}"#).await, + ("branch_not_opener".into(), NOT_OPENER.into()) + ); + assert_eq!(line_ids(&session), before); + assert!( + !local_events(&session, &a) + .await + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreate(_))), + "the refusal wrote nothing" + ); + soon(agent.close()).await.unwrap(); +} + +/// The opener's two keys stay apart: a line that is not the root keeps the +/// identity its move wrote and the roster of the lines it opened. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = open_line(&session, "b").await; + switch(&session, &b).await; + let identity = line_block( + &until_events(&session, &b, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="true""#)) + }) + .await, + ) + .expect("B's note"); + let t = open_line_from(&session, &b, "t").await; + let events = until_events(&session, &b, |events| { + roster_block(events).is_some_and(|(text, retired)| !retired && text.contains(&t)) + }) + .await; + let roster = roster_block(&events).expect("the roster is under its own key"); + assert!(!roster.1, "the roster is live: {roster:?}"); + assert!( + roster + .0 + .starts_with(&format!("")), + "{}", + roster.0 + ); + assert!( + roster.0.contains(&format!("- {t}: t")), + "the roster lists the line B opened: {}", + roster.0 + ); + assert_eq!( + line_block(&events).expect("B's identity"), + identity, + "the roster write leaves the identity's latest block alone" + ); + let opening = opening_blocks(&local_events(&session, &t).await); + assert!( + opening[0].1.starts_with(&format!( + "" + )), + "{:?}", + opening[0] + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.3a, second half: a line the user opened that becomes the default branch +/// opens a tool line, lists it, messages and reads it, and its notices reach it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_user_opened_default_branch_coordinates_the_line_it_opens() { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let cut = session.sequence("main").unwrap(); + let u = soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "the user's line".into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap(); + quiet(&session, &u).await; + switch(&session, &u).await; + let t = open_line_from(&session, &u, "t").await; + let roster = until_events(&session, &u, |events| { + roster_block(events).is_some_and(|(text, retired)| !retired && text.contains(&t)) + }) + .await; + assert!( + roster_block(&roster) + .expect("U holds a roster") + .0 + .contains(&format!("- {t}: t")), + "{roster:?}" + ); + let sent = tool_call( + &session, + &u, + &format!(r#"{{"action":"message","to":"{t}","content":"go on"}}"#), + ) + .await; + assert_eq!(sent.is_error, None, "{:?}", sent.content); + let page = page_of( + &tool_call( + &session, + &u, + &format!(r#"{{"action":"read","branch":"{t}"}}"#), + ) + .await, + ); + assert!(!page_sequences(&page).is_empty(), "{page:?}"); + until_events(&session, &u, |events| { + blocks_with(events, "" + )), + "{}", + note.0 + ); + let roster = roster_block(&local_events(&session, &b).await).expect("B's roster"); + assert!( + !roster.1 && roster.0.contains(&format!("- {t}: t")), + "the note left the roster alone: {roster:?}" + ); + switch(&session, "main").await; + let note = line_block( + &until_events(&session, &b, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="false""#)) + }) + .await, + ) + .expect("the move out wrote B's note"); + assert!( + note.0.contains("it can no longer open lines with create"), + "{}", + note.0 + ); + let roster = roster_block(&local_events(&session, &b).await).expect("B's roster"); + assert!( + !roster.1 && roster.0.contains(&format!("- {t}: t")), + "the second note left the roster alone: {roster:?}" + ); + soon(agent.close()).await.unwrap(); +} diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index 9791e471f6..ef43e493a2 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -49,8 +49,11 @@ pub enum AgentError { Multiple(Vec), } -/// Why the tree refused an operation on a line, named the way the protocol's -/// `appError` names it ([timeline branches §14](../../../docs/design/timeline-branches.md#14-clients)). +/// Why the tree refused an operation on a line, named the way the protocol +/// names it: the codes `session.branch_set_default` answers as its `appError` +/// and the codes the branch tool answers as its own result +/// ([timeline branches §11](../../../docs/design/timeline-branches.md#11-the-branch-tool), +/// [§14](../../../docs/design/timeline-branches.md#14-clients)). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BranchRefusal { /// The target is already the Session's default branch. @@ -65,6 +68,9 @@ pub enum BranchRefusal { /// the default branch. The root's own refusal is the operation's input /// error, which its callers already answer. CannotEnd, + /// The caller may not open a line: only the root, and the current default + /// branch, open one. + NotOpener, } impl BranchRefusal { @@ -75,6 +81,7 @@ impl BranchRefusal { Self::NotSelectable => "branch_not_selectable", Self::Protected => "branch_target_protected", Self::CannotEnd => "branch_cannot_end", + Self::NotOpener => "branch_not_opener", } } } diff --git a/docs/architecture/rust-agent/generated/modules.json b/docs/architecture/rust-agent/generated/modules.json index e43224de2d..da38f70d6c 100644 --- a/docs/architecture/rust-agent/generated/modules.json +++ b/docs/architecture/rust-agent/generated/modules.json @@ -18087,6 +18087,7 @@ "path AgentError::refused", "path BranchRefusal::AlreadyDefault", "path BranchRefusal::CannotEnd", + "path BranchRefusal::NotOpener", "path BranchRefusal::NotSelectable", "path BranchRefusal::Protected", "path Result", From f9d5b9ed25728c60688db46824df4e0fd7df1f38 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 13:15:55 +0800 Subject: [PATCH 2/8] feat(branch): hold a Session cap on open tool lines A create is charged under the lock that reserves its line: the open tool lines that are not on the protected path, the current default branch and its ancestors, plus the admitted reservations. Publication charges nothing a second time, a creation that definitively fails releases its slot, and a caller that stops waiting keeps it because the build goes on. A switch that leaves the Session over the cap closes nothing and refuses only later opens. `BranchToolConfig::max_open_lines` carries the cap, four by default, and `create` refuses `branch_limit_reached` when an open would cross it. The number comes from 1224 recorded runs of the timeline-branches scenarios, where the most tool lines open at once was two; the evaluation re-checks it. --- .../src/timeline_tree.rs | 57 ++++- .../tests/branch_flow.rs | 213 +++++++++++++++++- crates/dim-agent-runtime/src/error.rs | 4 + .../rust-agent/generated/modules.json | 1 + xtask/src/app_server.rs | 1 + 5 files changed, 269 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index c7f6f556bc..5325fd63b3 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -1737,13 +1737,19 @@ impl TimelineTree { /// reserved: under the same lock, so the caller's eligibility and the /// Session's counted total are the state the reservation is taken in (§4, /// §6.1). A refusal writes nothing. - fn admit_open(state: &TreeState, opener: &str) -> Result<()> { + fn admit_open(state: &TreeState, opener: &str, max_open_lines: usize) -> Result<()> { if !Self::can_open(state, opener) { return Err(AgentError::refused( BranchRefusal::NotOpener, format!("line {opener} is not the root or the default branch"), )); } + if Self::counted_tool_lines(state) >= max_open_lines { + return Err(AgentError::refused( + BranchRefusal::LimitReached, + format!("the Session holds {max_open_lines} open tool lines"), + )); + } Ok(()) } /// The Session's two openers: the root in every state, and the current @@ -1752,6 +1758,21 @@ impl TimelineTree { fn can_open(state: &TreeState, line: &str) -> bool { line == ROOT_BRANCH_ID || line == state.default.as_str() } + /// The tool lines a new open is charged with, one slot each: the lines the + /// tool opened that are open or ending, except the current default branch + /// and its ancestors, which an end cannot close (§6.1). A reservation is in + /// `nodes` before its build, so it is counted here too. + fn counted_tool_lines(state: &TreeState) -> usize { + state + .nodes + .iter() + .filter(|(id, node)| { + matches!(node.info.source, Some(BranchSource::Tool { .. })) + && id.as_str() != state.default.as_str() + && !Self::protects(state, id) + }) + .count() + } /// Whether `id` is above the current default branch: the default's parent /// chain goes through it. fn protects(state: &TreeState, id: &str) -> bool { @@ -2353,7 +2374,7 @@ impl TimelineTree { } let mut state = self.state.lock().unwrap(); if let Some(open) = open { - Self::admit_open(&state, &parent)?; + Self::admit_open(&state, &parent, open.max_open_lines)?; } let mut above = Some(parent.clone()); while let Some(id) = above { @@ -3138,7 +3159,13 @@ impl DynPlugin for BranchToolPlugin { .as_deref() .unwrap_or(BRANCH_TOOL_DESCRIPTION), ), - handler: Arc::new(BranchTool { tree }), + handler: Arc::new(BranchTool { + tree, + max_open_lines: self + .config + .max_open_lines + .unwrap_or(DEFAULT_MAX_OPEN_LINES), + }), }, )?; Ok(Effect::Done) @@ -3165,11 +3192,12 @@ enum IdleNotice { None, } /// An open by the `branch` tool: the notice the new line gives its opener when -/// a turn ends quietly. The tree reads the caller's eligibility in the lock -/// that reserves the line (§4). +/// a turn ends quietly, and the Session's cap on open tool lines. The tree +/// charges both in the lock that reserves the line (§4, §6.1). #[derive(Clone, Copy)] struct ToolOpen { idle_notice: IdleNotice, + max_open_lines: usize, } const QUIET_IDLE_ATTRIBUTE: &str = "idle-notice"; /// One line its parent opened, as the parent's own facts recorded it. @@ -4806,6 +4834,8 @@ fn first_line(purpose: &str) -> String { struct BranchTool { tree: Arc, + /// The Session's cap on open tool lines (§6.1). + max_open_lines: usize, } const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; /// Target events per `read` page; the final atomic batch may exceed it. @@ -5014,6 +5044,7 @@ impl BranchTool { cancel, ToolOpen { idle_notice: input.idle_notice, + max_open_lines: self.max_open_lines, }, ) .await; @@ -5023,6 +5054,10 @@ impl BranchTool { refusal: BranchRefusal::NotOpener, .. }) => Ok(refusal("branch_not_opener", NOT_OPENER_TEXT.into())), + Err(AgentError::BranchRefused { + refusal: BranchRefusal::LimitReached, + .. + }) => Ok(refusal("branch_limit_reached", LIMIT_REACHED_TEXT.into())), Err(AgentError::Cancelled(reason)) => Err(HostError::Cancelled(reason)), Err(error) => Err(HostError::failed(error.to_string())), } @@ -5786,6 +5821,10 @@ fn status_note( /// The `branch` tool's refusal of `create` on a line that is neither the root /// nor the default branch (design §4, §11). const NOT_OPENER_TEXT: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; +/// The `branch` tool's refusal of `create` when the open would cross the +/// Session's cap of open tool lines (design §6.1, §11). +const LIMIT_REACHED_TEXT: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; + /// The `branch` tool's description: its policy sentences are the coordination /// text for `main` ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)), /// replaceable at [`BranchToolConfig`]. @@ -5803,8 +5842,16 @@ pub struct BranchToolConfig { /// BranchLine, the part that writes the roster /// ([timeline branches §12.4](../../../docs/design/timeline-branches.md#124-texts-and-their-classes)). pub roster_closing: Option>, + /// The Session's cap on open tool lines in place of the built-in four + /// ([timeline branches §6.1](../../../docs/design/timeline-branches.md#61-resources-and-limits)). + pub max_open_lines: Option, } +/// The cap in force when the product sets none: four open tool lines at once, +/// the larger of four and the two open at once that recorded runs reached, plus +/// two (§6.1). The evaluation re-checks it. +const DEFAULT_MAX_OPEN_LINES: usize = 4; + fn branch_definition(description: &str) -> ToolDefinition { ToolDefinition { risk: Some("session".into()), diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 32c44f406d..3a5656b179 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -11890,6 +11890,15 @@ async fn restore_default(store: &Arc, id: &str) -> String { default } +/// The branch tool's configuration with a Session cap, as the design's cap +/// cases state it. +fn capped(max_open_lines: usize) -> BranchToolConfig { + BranchToolConfig { + max_open_lines: Some(max_open_lines), + ..BranchToolConfig::default() + } +} + /// Moves the Session's conversation to `line` and answers once the move is /// durable; a participant's note may still be on its way. async fn switch(session: &Session, line: &str) { @@ -11904,6 +11913,7 @@ async fn switch(session: &Session, line: &str) { } const NOT_OPENER: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; +const LIMIT_REACHED: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; /// §20.29: the root opens a line while another line is the default branch, so /// the new line starts from the root's history at the cut the root names, @@ -12186,12 +12196,209 @@ async fn a_tool_line_still_cannot_open_a_line() { soon(agent.close()).await.unwrap(); } +/// §20.30: continuing on tool children does not fill the cap, because the +/// default branch and its ancestors do not count. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_cap_does_not_count_the_default_branch_or_its_ancestors() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = open_line(&session, "b").await; + switch(&session, &b).await; + let c = open_line_from(&session, &b, "c").await; + switch(&session, &c).await; + let d = open_line_from(&session, &c, "d").await; + switch(&session, &d).await; + let info = session + .branches() + .into_iter() + .find(|info| info.id == d) + .expect("the chain reached D"); + assert_eq!(info.parent.as_deref(), Some(c.as_str())); + let e = open_line(&session, "e").await; + let f = open_line(&session, "f").await; + let open = line_ids(&session); + assert!(open.contains(&b) && open.contains(&e) && open.contains(&f)); + assert_eq!( + call(&session, "main", r#"{"action":"create","prompt":"g"}"#).await, + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "B, C and D spent no slot: E and F filled the two" + ); + assert_eq!(session.branches().len(), 6, "the refusal closed nothing"); + soon(agent.close()).await.unwrap(); +} + +/// §20.31: a switch that leaves the Session over the cap refuses new opens and +/// closes nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_switch_over_the_cap_closes_nothing() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + switch(&session, &a).await; + let b = open_line_from(&session, &a, "b").await; + switch(&session, "main").await; + let before = line_ids(&session); + assert!(before.contains(&a) && before.contains(&b)); + assert_eq!( + call(&session, "main", r#"{"action":"create","prompt":"c"}"#).await, + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "A and B count again, which is the cap" + ); + assert_eq!(line_ids(&session), before, "the switch closed no line"); + assert_eq!( + session.branches().len(), + 3, + "every line open before the switch is open after it" + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.34: a switch that frees a slot admits the next open, and nothing is +/// closed to free it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_switch_that_frees_a_slot_admits_the_next_open() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + let x = open_line(&session, "x").await; + assert_eq!( + call(&session, "main", r#"{"action":"create","prompt":"y"}"#).await, + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "A and X fill the cap while the root holds the role" + ); + switch(&session, &a).await; + let y = open_line(&session, "y").await; + let open = line_ids(&session); + assert!( + open.contains(&a) && open.contains(&x) && open.contains(&y), + "A stopped counting, so Y fitted; no line was closed" + ); + soon(agent.close()).await.unwrap(); +} + +/// §20.33 and §20.35: the cap is charged where the line is reserved, so the +/// last slot admits one open only, and a reservation holds a slot before its +/// line publishes and frees it when the creation fails. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_cap_is_refused_under_the_tree_lock() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + let b = open_line(&session, "b").await; + assert_eq!( + call(&session, "main", r#"{"action":"create","prompt":"c"}"#).await, + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "the last slot was spent by B" + ); + assert!( + !session + .branches() + .iter() + .any(|info| info.parent.as_deref() == Some(b.as_str())), + "the refusal opened nothing" + ); + let _ = (a, b); + soon(agent.close()).await.unwrap(); + + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + let b = open_line(&session, "b").await; + switch(&session, &b).await; + probe.delay_child.store(true, Ordering::SeqCst); + let builds = probe.child_builds.load(Ordering::SeqCst); + session + .submit( + r#"tool:branch {"action":"create","prompt":"held"}"#.into(), + InputMode::Queue, + "main", + ) + .await + .unwrap(); + soon(async { + while probe.child_builds.load(Ordering::SeqCst) == builds { + probe.child_entered.notified().await; + } + }) + .await; + soon(session.stop("main", "user stop".into())) + .await + .unwrap(); + assert_eq!( + call(&session, &b, r#"{"action":"create","prompt":"later"}"#).await, + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "the held reservation is charged with A, so B finds no room" + ); + assert!( + !local_events(&session, &b) + .await + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreate(_))), + "the refusal wrote nothing on B" + ); + probe.delay_child.store(false, Ordering::SeqCst); + probe.child_release.notify_one(); + soon(async { + loop { + let failed = local_events(&session, "main") + .await + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreateFailed(_))); + if failed { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + let later = open_line_from(&session, &b, "later").await; + assert_eq!( + session + .branches() + .into_iter() + .find(|info| info.id == later) + .expect("the freed slot admitted the open") + .parent + .as_deref(), + Some(b.as_str()) + ); + let _ = a; + soon(agent.close()).await.unwrap(); +} + /// The opener's two keys stay apart: a line that is not the root keeps the /// identity its move wrote and the roster of the lines it opened. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster() { let probe = Arc::new(Probe::default()); - let agent = setup(&probe).await; + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); @@ -12305,7 +12512,9 @@ async fn a_user_opened_default_branch_coordinates_the_line_it_opens() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_status_note_and_a_live_roster_do_not_retire_each_other() { let probe = Arc::new(Probe::default()); - let agent = setup(&probe).await; + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index ef43e493a2..ddd21834a6 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -71,6 +71,9 @@ pub enum BranchRefusal { /// The caller may not open a line: only the root, and the current default /// branch, open one. NotOpener, + /// The Session holds its limit of open tool lines, counting the admitted + /// reservations. + LimitReached, } impl BranchRefusal { @@ -82,6 +85,7 @@ impl BranchRefusal { Self::Protected => "branch_target_protected", Self::CannotEnd => "branch_cannot_end", Self::NotOpener => "branch_not_opener", + Self::LimitReached => "branch_limit_reached", } } } diff --git a/docs/architecture/rust-agent/generated/modules.json b/docs/architecture/rust-agent/generated/modules.json index da38f70d6c..c1a838b155 100644 --- a/docs/architecture/rust-agent/generated/modules.json +++ b/docs/architecture/rust-agent/generated/modules.json @@ -18087,6 +18087,7 @@ "path AgentError::refused", "path BranchRefusal::AlreadyDefault", "path BranchRefusal::CannotEnd", + "path BranchRefusal::LimitReached", "path BranchRefusal::NotOpener", "path BranchRefusal::NotSelectable", "path BranchRefusal::Protected", diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 6068bf42f3..00bc7378cb 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -230,6 +230,7 @@ pub async fn serve_home( dim_agent_capabilities::timeline_tree::BranchToolConfig { description: run.overrides.branch_description.clone(), roster_closing: run.overrides.roster_closing.clone(), + max_open_lines: None, }, ); dim_app_server::permission_rules::install(&mut builder); From cc5e2b0c29f0c516487f700bfd0c11ac1f36d3fb Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 13:16:07 +0800 Subject: [PATCH 3/8] test(branch): measure a cold restore with two openers The Session holds the root and the default branch, each with two open tool lines, and the measure reports the cold restore in milliseconds. It is ignored and is not a CI threshold. --- .../tests/branch_flow.rs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 3a5656b179..1b7a2c35f9 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -12564,3 +12564,58 @@ async fn a_status_note_and_a_live_roster_do_not_retire_each_other() { ); soon(agent.close()).await.unwrap(); } + +/// E3: cold restore with two openers, the root and the default branch, each +/// holding open tool lines. Run with `--release --ignored --nocapture`. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore] +async fn measure_e3_cold_restore_with_two_openers() { + async fn tool_line(session: &Session, opener: &str, purpose: &str) -> String { + let cut = session.sequence(opener).unwrap(); + let turn = format!("turn-{purpose}"); + let id = soon(session.branch( + opener.into(), + cut, + BranchOptions { + prompt: purpose.into(), + source: BranchSource::Tool { + turn_id: turn.clone(), + request_id: format!("request-{purpose}"), + call_id: format!("call-{purpose}"), + }, + }, + )) + .await + .unwrap(); + soon(session.idle(&id)).await.unwrap(); + id + } + let mut elapsed = Vec::new(); + for _ in 0..5 { + let probe = Arc::new(Probe::default()); + let agent = setup(&probe).await; + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let opener = tool_line(&session, "main", "the default branch").await; + switch(&session, &opener).await; + for index in 0..2 { + tool_line(&session, &opener, &format!("default {index}")).await; + } + for index in 0..2 { + tool_line(&session, "main", &format!("root {index}")).await; + } + let id = session.id(); + soon(session.close()).await.unwrap(); + let started = std::time::Instant::now(); + let restored = soon(agent.restore_session(id.into())).await.unwrap(); + soon(restored.idle("main")).await.unwrap(); + elapsed.push(started.elapsed()); + soon(agent.close()).await.unwrap(); + } + elapsed.sort(); + println!( + "E3 cold restore with two openers and four open lines: median {:.1} ms", + elapsed[elapsed.len() / 2].as_secs_f64() * 1e3 + ); +} From 2553666a40cf67a2733c5f4c4dd2106993d03446 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 13:31:51 +0800 Subject: [PATCH 4/8] docs(branch): state the opener rule and the cap's charge The BranchTool page now says how `create` is admitted: the caller's eligibility and the Session's cap are charged in the lock that reserves the line, and a failed creation releases its slot. Its tests list names the flows this change adds. --- .../rust-agent/plugins/BranchTool.md | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/BranchTool.md b/docs/architecture/rust-agent/plugins/BranchTool.md index 2047a9d74e..15ed7617ab 100644 --- a/docs/architecture/rust-agent/plugins/BranchTool.md +++ b/docs/architecture/rust-agent/plugins/BranchTool.md @@ -7,13 +7,16 @@ It is installed with the default execution loop; the minimal execution profile leaves it out. The facts it emits and consumes are BranchLine's, the branch part below. -`create` passes the optional idle notice policy to TimelineTree. The child -restores it from its opening identity before BranchLine handles turn ends. `create` admits -two callers and refuses every other line: the root, in every state, and the current -default branch. The root's right never changes, which is what lets a user ask it for a -line while another line holds the role. The cap is a total over the Session and counts -the open tool lines that are not on the protected path, so a line the user keeps -continuing on costs no slot. +`create` passes the optional idle notice policy and the Session's cap to TimelineTree. +The child restores the idle notice from its opening identity before BranchLine handles +turn ends. `create` admits two callers and refuses every other line: the root, in every +state, and the current default branch. The root's right never changes, which is what +lets a user ask it for a line while another line holds the role. The cap is a total +over the Session and counts the open tool lines that are not on the protected path, so +a line the user keeps continuing on costs no slot. TimelineTree charges the caller's +eligibility and the cap in the lock that reserves the new line, so a switch or a second +create cannot slip between a check and the reservation; publication charges nothing a +second time, and a creation that fails releases its slot. `end` ends the calling line and nothing else, so it guards the caller as well as the target: only a tool line ends itself, a plugin line follows its own protocol, and a line @@ -64,6 +67,15 @@ specific target from its own `step/tool-use` and `step/tool-result` (design [§6 [branch_flow.rs](../../../../crates/dim-agent-capabilities/tests/branch_flow.rs): `a_stop_settles_the_branch_tool_while_the_tree_still_builds_the_child`, `a_refused_branch_call_writes_nothing`, +`the_root_opens_a_line_while_another_line_is_default`, +`the_default_branch_opens_a_line`, +`a_former_default_branch_keeps_its_lines_and_opens_none`, +`a_plugin_line_never_opens_a_line`, +`a_tool_line_still_cannot_open_a_line`, +`the_cap_does_not_count_the_default_branch_or_its_ancestors`, +`a_switch_over_the_cap_closes_nothing`, +`a_switch_that_frees_a_slot_admits_the_next_open`, +`the_cap_is_refused_under_the_tree_lock`, `a_tool_line_ends_itself_and_main_learns_it_from_the_roster`, `a_message_reaches_its_receiver_in_the_mode_it_asked_for`, `a_first_parent_read_starts_after_the_cut`, @@ -176,6 +188,9 @@ BranchLine mounts at the committed Dispatcher cutoff without reading historical `a_roster_and_an_identity_replay_separately_after_a_compaction`, `a_child_cut_after_a_roster_retires_it_and_one_cut_before_gets_nothing`, `the_roots_roster_from_before_the_key_split_is_retired_at_load`, +`an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster`, +`a_status_note_and_a_live_roster_do_not_retire_each_other`, +`a_user_opened_default_branch_coordinates_the_line_it_opens`, `a_line_messages_and_reads_its_parent_and_the_lines_it_opened`, `a_sibling_or_grandparent_is_refused_with_nothing_written`, `an_idle_line_is_told_its_parent_moved_without_being_woken`, From a411ded062951efeffaaa3b30096fa9d56ff84b7 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 13:44:56 +0800 Subject: [PATCH 5/8] test(branch): wait for both notes before counting them A move writes one note per participant from each line's own writer. The test counted the notes after only the former default branch's note had landed, so a slow writer could leave the new default branch's note out. The wait makes the count deterministic. --- crates/dim-agent-capabilities/tests/branch_flow.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 1b7a2c35f9..9283bbab3a 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -10473,6 +10473,10 @@ async fn a_former_default_branch_keeps_no_stale_instruction_and_ends_after_a_mov line_block(events).is_some_and(|(text, _)| text.contains(r#"default="false""#)) }) .await; + until_events(&session, &nested, |events| { + line_block(events).is_some_and(|(text, _)| text.contains(r#"default="true""#)) + }) + .await; assert_eq!( default_notes(&session, &["main", &a, &nested]).await, [("main".to_owned(), 0), (a.clone(), 2), (nested.clone(), 1)], From 93a7af630f99b0ff0c4d289ef6377eb692371ceb Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 14:56:50 +0800 Subject: [PATCH 6/8] fix(branch): order an open with default-branch moves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit create_child takes the tree's operations guard for its admission: the opener check, the cap, the branch/create append and the reservation. A move or an end that already holds the guard has applied its state, so an open no longer counts a protected path a committed move has left, and the opener it reads is the one the tree has after the move. The guard is released as soon as the reservation exists, before the child's build, and the wait for it stops on the call's cancellation (design §6.1, §14). The tests pause a move after its append: the root's open answers branch_limit_reached once the move settles, and the moving line's open answers branch_not_opener. A paused build does not keep a later move from settling, and an open admitted before a move still stands while the Session is over the cap. --- .../src/timeline_tree.rs | 20 +- .../tests/branch_flow.rs | 280 ++++++++++++++++++ 2 files changed, 296 insertions(+), 4 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 5325fd63b3..a3d305ef35 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -228,10 +228,10 @@ pub struct TimelineTree { /// waiters cannot both deliver and record it (design §10, §20.26b). retry: tokio::sync::Mutex<()>, /// Serialises the operations that read the tree and then write on it, an - /// end and a move: each admits under the state lock and keeps the lock - /// until its fact commits, so of two conflicting operations exactly one is - /// admitted and each reads what the other would have written (design §10, - /// §20.26). + /// open, an end and a move: each admits under the state lock and keeps the + /// lock until its fact commits, so of two conflicting operations exactly one + /// is admitted and each reads what the other would have written (design + /// §6.1, §10, §14, §20.26). operations: Arc>, /// The tasks that settle an admitted operation: each holds the operations /// guard, awaits its fact's publication and applies the live update, so a @@ -2312,6 +2312,11 @@ impl TimelineTree { let event = context.branch().input(data).await?; Self::published(timeline, event.sequence).await } + /// Reserves one line and answers once its build publishes it. The opener + /// check, the cap and the `branch/create` append decide under the + /// operations guard, so a move or an end that already holds it has applied + /// its state first (design §6.1, §10, §14). The guard is released as soon + /// as the reservation exists, before the build it started. fn create_child( &self, parent: String, @@ -2346,6 +2351,12 @@ impl TimelineTree { if parent_context.is_closing() { return Err(AgentError::Closed(parent.clone())); } + let operations = tokio::select! { + operations = self.operations.clone().lock_owned() => operations, + _ = admission.cancelled() => { + return Err(AgentError::Cancelled("branch admission".into())); + } + }; let mut ready = None; let _ = timeline.append_registered(EventKind::BranchCreate(original).into(), |event| { @@ -2403,6 +2414,7 @@ impl TimelineTree { )?); Ok(()) })?; + drop(operations); tokio::select! { result = Self::await_branch(ready.expect("committed branch reservation")) => result, _ = admission.cancelled() => Err(AgentError::Cancelled( diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 9283bbab3a..a67b5e0d8c 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -10,6 +10,7 @@ use dim_agent_capabilities::{ ToolExecutionContext, ToolHost, }, timeline_tree::{BranchToolConfig, TreeCommands}, + tool_registry::ToolRegistry, workspace_tools::{file_reads::FileReads, files::FileTools}, }; use dim_agent_runtime::testing::MinimalHost; @@ -156,6 +157,8 @@ struct Probe { child_builds: AtomicUsize, child_cleanups: Arc, commands: Mutex>>, + /// The Session's tool registry, so a test can call the `branch` tool itself. + tool_registry: Mutex>>, /// main's Timeline as its capabilities receive it, for direct writes. main_timeline: Mutex>>, /// A line's own Timeline: the binding its file tools keep reads in. @@ -194,6 +197,7 @@ struct ProbePlugin { dispatcher: Key, identity: Key, commands: Key, + registry: Key, } impl ProbePlugin { fn new(names: &Names<'_>, probe: Arc) -> rutis::Result { @@ -203,6 +207,7 @@ impl ProbePlugin { dispatcher: names.key()?, identity: names.key()?, commands: names.key()?, + registry: names.key()?, }) } } @@ -216,6 +221,7 @@ impl DynPlugin for ProbePlugin { self.dispatcher.erase(), self.identity.erase(), self.commands.erase(), + self.registry.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -224,8 +230,10 @@ impl DynPlugin for ProbePlugin { let dispatcher = ctx.require_at(&self.dispatcher)?; let identity = ctx.require_at(&self.identity)?; let commands = ctx.require_at(&self.commands)?; + let registry = ctx.require_at(&self.registry)?; let probe = self.probe.clone(); *probe.commands.lock().unwrap() = Some(commands); + *probe.tool_registry.lock().unwrap() = Some(registry); if identity.branch_id == "main" { *probe.main_timeline.lock().unwrap() = Some(timeline.clone()); if probe.read_while_opening.load(Ordering::SeqCst) { @@ -582,6 +590,20 @@ fn builder_with_store(probe: &Arc, store: Arc) -> Agen probe_features(&mut builder, probe); builder } +/// [`builder_with_store`](builder_with_store) with the branch texts at a +/// candidate's factory configuration. +fn builder_with_store_config( + probe: &Arc, + store: Arc, + config: BranchToolConfig, +) -> AgentBuilder { + let mut builder = AgentBuilder::new(AgentConfig::default()); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); + mock_hosts(&mut builder); + defaults::install_with_branch_config(&mut builder, config); + probe_features(&mut builder, probe); + builder +} /// [`builder_with`](builder_with) with `tools` in place of [`MockTools`]. fn builder_with_tools(probe: &Arc, tools: Arc) -> AgentBuilder { let mut builder = AgentBuilder::new(AgentConfig::default()); @@ -11919,6 +11941,64 @@ async fn switch(session: &Session, line: &str) { const NOT_OPENER: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; const LIMIT_REACHED: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; +/// The branch tool's own `create`, called as a tool call so a test can hold the +/// tree and stop the call at its admission, or let it answer there. +async fn open_with_tool( + probe: &Probe, + opener: &str, + at: u64, + prompt: &str, +) -> std::result::Result { + let registry = probe + .tool_registry + .lock() + .unwrap() + .clone() + .expect("the Session registers its tools"); + // A read takes in what is registered now, so the tool is in the snapshot. + registry.definitions(); + let tool = registry.contributed("branch").expect("the branch tool"); + tool.handler + .execute( + ToolCall { + id: "call".into(), + name: "branch".into(), + input: serde_json::json!({"action": "create", "prompt": prompt, "at": at}) + .as_object() + .cloned() + .unwrap_or_default(), + }, + ToolExecutionContext { + turn_id: "turn".into(), + request_id: "request".into(), + branch_id: opener.into(), + }, + CancellationToken::new(), + ) + .await +} + +/// The refusal a tool call answers, as the tool's structured error. +fn tool_refusal(result: &ToolResult) -> (String, String) { + let structured = result.structured_content.clone().unwrap_or_default(); + let field = |name: &str| { + structured + .get(name) + .and_then(|value| value.as_str()) + .unwrap_or_default() + .to_string() + }; + (field("error"), field("message")) +} + +/// The `branch/create` facts a line holds. +fn creates(events: &[Arc]) -> usize { + events + .iter() + .filter(|event| matches!(event.kind, EventKind::BranchCreate(_))) + .count() +} + /// §20.29: the root opens a line while another line is the default branch, so /// the new line starts from the root's history at the cut the root names, /// reports to the root, and the default branch hears nothing about it. @@ -12395,6 +12475,206 @@ async fn the_cap_is_refused_under_the_tree_lock() { soon(agent.close()).await.unwrap(); } +/// §6.1, §14: an open decides in one order with every move and end. The root's +/// `create` is called while `A → main` holds the tree lock, before its fact is +/// published: the open waits, and then counts A as off the protected path, so +/// the cap refuses it. The refusal writes nothing and adds no line. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_open_after_a_move_waits_and_counts_the_moves_result() { + let store = Arc::new(TestStore::default()); + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_store_config(&probe, store.clone(), capped(1))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + switch(&session, &a).await; + let tree = session.session_service::().unwrap(); + + store.hold_next_default("main"); + let mut moved = Box::pin(tree.set_default_branch( + "main".into(), + BranchSource::User { + operation_id: "move".into(), + }, + )); + tokio::select! { + result = &mut moved => panic!("the move answered before its fact committed: {result:?}"), + _ = store.wait_holding() => {} + } + let cut = session.sequence("main").unwrap(); + let before = line_ids(&session); + let written = creates(&local_events(&session, "main").await); + let mut created = Box::pin(open_with_tool(&probe, "main", cut, "b")); + assert!( + futures_util::poll!(created.as_mut()).is_pending(), + "the open waits for the move's admission" + ); + assert_eq!( + line_ids(&session), + before, + "no line is reserved while the move settles" + ); + store.release(); + assert_eq!(soon(&mut moved).await.unwrap(), "main"); + let created = soon(&mut created) + .await + .expect("the open answers a refusal"); + assert_eq!( + tool_refusal(&created), + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "A counts once the move is in force, which is the cap: {:?}", + created.content + ); + assert_eq!(line_ids(&session), before, "the refusal opened no line"); + assert_eq!( + creates(&local_events(&session, "main").await), + written, + "the refusal wrote nothing on the root" + ); + soon(agent.close()).await.unwrap(); +} + +/// §6.1, §14: the same order for the opener. `B` holds the role and opens a line +/// while `B → main` holds the tree lock: once the move settles, `B` is no longer +/// an opener, and the refusal writes nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_open_from_the_moving_line_is_refused_once_the_move_settles() { + let store = Arc::new(TestStore::default()); + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = open_line(&session, "b").await; + switch(&session, &b).await; + let tree = session.session_service::().unwrap(); + + store.hold_next_default("main"); + let mut moved = Box::pin(tree.set_default_branch( + "main".into(), + BranchSource::User { + operation_id: "move".into(), + }, + )); + tokio::select! { + result = &mut moved => panic!("the move answered before its fact committed: {result:?}"), + _ = store.wait_holding() => {} + } + let cut = session.sequence(&b).unwrap(); + let before = line_ids(&session); + let mut created = Box::pin(open_with_tool(&probe, &b, cut, "c")); + assert!( + futures_util::poll!(created.as_mut()).is_pending(), + "the open waits for the move's admission" + ); + assert_eq!( + line_ids(&session), + before, + "no line is reserved while the move settles" + ); + store.release(); + assert_eq!(soon(&mut moved).await.unwrap(), "main"); + let created = soon(&mut created) + .await + .expect("the open answers a refusal"); + assert_eq!( + tool_refusal(&created), + ("branch_not_opener".into(), NOT_OPENER.into()), + "B opens lines only while it holds the role: {:?}", + created.content + ); + assert_eq!(line_ids(&session), before, "the refusal opened no line"); + assert!( + !local_events(&session, &b) + .await + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreate(_))), + "the refusal wrote nothing on B" + ); + soon(agent.close()).await.unwrap(); +} + +/// §6.1, §14: the guard covers the admission only. A child whose build is paused +/// after its reservation does not keep a later move from settling. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_paused_build_does_not_hold_the_tree_lock() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + probe.delay_child.store(true, Ordering::SeqCst); + let builds = probe.child_builds.load(Ordering::SeqCst); + let cut = session.sequence("main").unwrap(); + let mut created = Box::pin(open_with_tool(&probe, "main", cut, "held")); + tokio::select! { + result = &mut created => panic!("the paused build answered: {result:?}"), + _ = async { + while probe.child_builds.load(Ordering::SeqCst) == builds { + probe.child_entered.notified().await; + } + } => {} + } + switch(&session, &a).await; + assert_eq!( + session.default_branch().unwrap(), + a, + "the move settled while the child's build was paused" + ); + probe.delay_child.store(false, Ordering::SeqCst); + probe.child_release.notify_one(); + let failed = patient(&mut created).await; + assert!( + failed.is_err(), + "the held child's build fails, as its apply does: {failed:?}" + ); + until_events(&session, "main", |events| { + events + .iter() + .any(|event| matches!(event.kind, EventKind::BranchCreateFailed(_))) + }) + .await; + soon(agent.close()).await.unwrap(); +} + +/// §6.1, §20.31: an open admitted before a move stands. It counts after the +/// move, which can leave the Session over the cap, and the next open is what +/// refuses. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_open_admitted_before_a_move_still_stands() { + let probe = Arc::new(Probe::default()); + let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(1))) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let a = open_line(&session, "a").await; + switch(&session, &a).await; + let b = open_line(&session, "b").await; + switch(&session, "main").await; + let open = line_ids(&session); + assert!( + open.contains(&a) && open.contains(&b), + "the move closed neither line: {open:?}" + ); + assert_eq!( + tool_refusal(&tool_call(&session, "main", r#"{"action":"create","prompt":"c"}"#).await), + ("branch_limit_reached".into(), LIMIT_REACHED.into()), + "A counts again with B, which is over the cap of one" + ); + assert_eq!(line_ids(&session), open, "the refusal closed nothing"); + soon(agent.close()).await.unwrap(); +} + /// The opener's two keys stay apart: a line that is not the root keeps the /// identity its move wrote and the roster of the lines it opened. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] From c5928e75cc6dc9431f3dd8cafd6d67dcb66bc673 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 14:56:51 +0800 Subject: [PATCH 7/8] fix(branch): replace a default branch's stale note at load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit write_load_note compared only the role a line's latest branch:line block states. The note now grants create to the default branch, so a Session that made a line the default under the previous text keeps a note that forbids opening while the tool admits the line's create. The line the tree reports as the default branch, never the root, also compares that block's text with the note this code writes for it, with the counterpart read from the latest branch/default's from as the load already reads it. A difference writes the current note once before the line's next model request, and a load that finds them equal writes nothing (design §5). The tests store the older text byte for byte as the previous code writes it, for a tool line and for a line the user opened, and assert one replacement before the first request and none on a second load. --- .../src/timeline_tree.rs | 29 ++- .../tests/branch_flow.rs | 196 ++++++++++++++++++ .../rust-agent/plugins/BranchTool.md | 3 +- .../rust-agent/plugins/TimelineTree.md | 2 +- docs/design/timeline-branches.md | 2 +- docs/zh/design/timeline-branches.md | 2 +- 6 files changed, 224 insertions(+), 10 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index a3d305ef35..442fba082f 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -4599,12 +4599,14 @@ impl BranchLine { }; Ok(prompt.clone()) } - /// Writes the note a load owes, comparing one thing only: whether this - /// line is the default branch now, against the role its latest - /// `branch:line` block states, where a missing `default` attribute means - /// not default. A line that took no part in the latest move keeps the + /// Writes the note a load owes, comparing two things: whether this line is + /// the default branch now, against the role its latest `branch:line` block + /// states, where a missing `default` attribute means not default; and, for + /// the tree's current default branch alone, the text of that block against + /// the note this code writes for the line, so a note an older rule set left + /// is replaced once. A line that took no part in the latest move keeps the /// counterpart its own note named, so a move between other lines does not - /// rewrite it, and a load that finds the roles in agreement writes nothing + /// rewrite it, and a load that finds both in agreement writes nothing /// (design §5). async fn write_load_note(&self, role: LineRole, parent: Option<&str>) -> Result<()> { if !receives_note(role) { @@ -4628,12 +4630,27 @@ impl BranchLine { } else { None }; - if self.record_status(block).unwrap_or(false) == is_default { + let agrees = self.record_status(block).unwrap_or(false) == is_default; + if agrees && !is_default { return Ok(()); } let Some(text) = self.note_text(parent, is_default, &other).await? else { return Ok(()); }; + // The line is the tree's default branch, so its latest note was written + // by the move that made it the default and carries this code's text: a + // note an older rule set left differs and is replaced once (design §5). + let in_force = agrees + && self + .view + .lock() + .unwrap() + .identity + .as_ref() + .is_some_and(|(latest, retired)| !retired && latest == &text); + if in_force { + return Ok(()); + } let data = InputMessageData { blocks: vec![crate::context_block::raw(text.clone(), Some(line_key()))], mode: Some(InputMode::Append), diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index a67b5e0d8c..448c5d6b98 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -11072,6 +11072,202 @@ async fn a_clean_restart_writes_no_status_note() { soon(again.close()).await.unwrap(); } +/// The `` note origin/main (fc46080) wrote when a tool line +/// became the default branch, rendered by its own `status_note` and +/// `tool_line_body`: the birth bullet forbids opening lines, and the change +/// names no right to open one. `{line}`, `{parent}` and `{prompt}` stand where +/// that code substituted them. +const OLD_TOOL_NOTE: &str = r#" +You are line {line} of this session. Line {parent} opened you at this point of its history to work in parallel with it. You are the same agent as {parent}: everything above is your own history, and you continue from here on your own line. {parent} keeps working on its line; you can read its work after this point, and it can read yours. Messages above that were addressed to {parent}, such as its list of open lines, are {parent}'s, not yours. + +Your purpose, as {parent} wrote it: +{prompt} + +How you work with {parent}: +- Work on this purpose only. You cannot open lines; if more parallel work is needed, tell {parent}. +- Read {parent} with the branch tool (action read, branch "{parent}") when what {parent} did or decided since your cut changes your work; the parent block reports when {parent} has moved. Message {parent} only for what it must act on: a decision that changes its work, a blocker only the user can settle, a conflict with another line, or a change to your purpose. Use mode "steer" for what {parent} must act on now, "append" for what {parent} should see at its next step. Do not send {parent} a progress report it can read, and do not page through {parent}'s whole stream: read the page that answers your question, then act. +- You share the workspace with {parent} and its other lines. Change only the files {parent} gave you; before changing any other file, tell {parent} which. If edit or write fails because the file was modified after it was last read, another line may have changed the file: read it again and tell {parent} before you continue. +- The user can talk to you directly. Answer the user, and ask with ask_user when only the user can decide. +- When your purpose is done, or cannot be done, call the branch tool with action "end" and content saying what you found, did, changed and left undone. If you already told {parent} that in a message, your end content carries only what is new. Read {parent} once more before you end if the parent block says {parent} has moved, so your last word still holds. That is your last action; {parent} receives it. + +This line is now the session's default branch, switched from line {parent}. While this block is your latest one: answer the user here; you send no automatic idle notice to {parent}; you cannot call end on yourself. Line {parent} stays open and keeps the lines it opened. +"#; + +/// The same for a line the user opened. +const OLD_USER_NOTE: &str = r#" +You are line {line} of this session, opened by the user from line {parent} at this point of its history. You are the same agent as {parent}: everything above is your own history, and you continue from here on your own line, in parallel with {parent}. You can read {parent}'s work after this point. Unless the user makes this line the default branch, you cannot call end on yourself. Messages above that were addressed to {parent} are {parent}'s, not yours. The message after this one is from the user for this line. + +The user has now made this line the session's default branch, switched from line {parent}. While this block is your latest one: answer the user here; you cannot call end on yourself; the user ends this line. Line {parent} stays open and keeps the lines it opened. +"#; + +/// §5: a Session that moved its default branch under the older rule keeps that +/// note on the line, and the tool admits its `create` while the note still +/// forbids it. The load replaces it once, before the line's first request, and a +/// second load writes nothing. +async fn a_stale_note_is_replaced_once(old: &str, user: bool) { + let purpose = "the purpose of B"; + let first = Arc::new(MemoryTimelineStore::default()); + let agent = MinimalHost::start(&builder_with_store( + &Arc::new(Probe::default()), + first.clone(), + )) + .await + .unwrap(); + let session = soon(agent.create_session(SessionConfig::default())) + .await + .unwrap(); + let b = if user { + let cut = session.sequence("main").unwrap(); + soon(session.branch( + "main".into(), + cut, + BranchOptions { + prompt: purpose.into(), + source: BranchSource::User { + operation_id: "client".into(), + }, + }, + )) + .await + .unwrap() + } else { + open_line(&session, purpose).await + }; + quiet(&session, &b).await; + switch(&session, &b).await; + owed_notes(&session, &b, 1).await; + let id = session.id().to_owned(); + soon(session.close()).await.unwrap(); + soon(agent.close()).await.unwrap(); + + // The store now holds the Session as the older code left it: B's latest + // note is the one that code wrote, byte for byte. + let old = old + .replace("{line}", &b) + .replace("{parent}", "main") + .replace("{prompt}", purpose); + let second = Arc::new(MemoryTimelineStore::default()); + copy_session(&first, &second, &id, |branch, mut records| { + if branch == b { + for record in &mut records { + let event = Arc::make_mut(&mut record.event); + let EventKind::InputMessage(data) = &mut event.kind else { + continue; + }; + for block in &mut data.blocks { + if let InputBlock::Raw { text, key, retire } = block + && key.as_deref() == Some("branch:line") + && !*retire + && text.contains(" default=\"") + { + *text = old.clone(); + } + } + } + } + records + }) + .await; + + // The writer is held, so only the load can write the note it owes, and the + // line's first request still carries it. + let mut held = dim_agent_capabilities::timeline_tree::testing::hold_writers(&id); + let agent = MinimalHost::start(&builder_with_store( + &Arc::new(Probe::default()), + second.clone(), + )) + .await + .unwrap(); + let session = soon(agent.restore_session(id.clone())).await.unwrap(); + assert_eq!(session.default_branch().unwrap(), b, "the fact stands"); + let stopped = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if held.arrived().await == b { + break; + } + } + }) + .await; + assert!( + stopped.is_ok(), + "line {b}'s writer never stopped at the test seam" + ); + soon(session.submit("next request".into(), InputMode::Queue, &b)) + .await + .unwrap(); + let events = until_events(&session, &b, |events| { + request_after_resume(events).is_some() + }) + .await; + let (at, request) = request_after_resume(&events).expect("B's first request exists"); + let before: Vec<_> = events + .iter() + .filter(|event| event.sequence < at) + .cloned() + .collect(); + let notes = status_notes(&before); + assert_eq!( + notes.len(), + 2, + "the load replaced the stale note exactly once: {notes:?}" + ); + assert_eq!( + notes[0], old, + "the stored note is the one older rules wrote" + ); + let note = ¬es[1]; + assert!(note.contains(r#"default="true""#), "{note}"); + assert!( + note.contains("you can open lines with create"), + "the replacement states the rule the tool applies: {note}" + ); + assert!( + note.contains(match user { + true => "opened by the user from line main", + false => "this block does not make it one: a status note would", + }), + "the replacement restates the current birth identity: {note}" + ); + assert!( + request + .request + .messages + .iter() + .any(|message| said(message).contains(note)), + "the first request carries the note the load wrote" + ); + held.release(); + drop(held); + soon(session.close()).await.unwrap(); + soon(agent.close()).await.unwrap(); + + let third = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), second)) + .await + .unwrap(); + let session = soon(third.restore_session(id)).await.unwrap(); + soon(session.idle(&b)).await.unwrap(); + assert_eq!( + status_notes(&local_events(&session, &b).await).len(), + 2, + "a second load finds the note it writes and adds none" + ); + soon(third.close()).await.unwrap(); +} + +/// §5: the reviewer's case. A tool line was made the default branch under the +/// older rule, so its stored note forbids the `create` the tool now admits. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_tool_lines_note_from_older_rules_is_replaced_once_at_load() { + a_stale_note_is_replaced_once(OLD_TOOL_NOTE, false).await; +} + +/// §5: the same for a line the user opened and made the default branch under +/// the older rule. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_user_lines_note_from_older_rules_is_replaced_once_at_load() { + a_stale_note_is_replaced_once(OLD_USER_NOTE, true).await; +} + /// A Session whose model compacts, over `store`, for a test that restarts it: /// the summary strategy [`Compact`] and the hosts the branch tool needs. fn compacting_builder(store: Arc) -> AgentBuilder { diff --git a/docs/architecture/rust-agent/plugins/BranchTool.md b/docs/architecture/rust-agent/plugins/BranchTool.md index 15ed7617ab..2dcb10a676 100644 --- a/docs/architecture/rust-agent/plugins/BranchTool.md +++ b/docs/architecture/rust-agent/plugins/BranchTool.md @@ -142,7 +142,8 @@ Consumes `branch/create`, `branch/create-failed`, `branch/ended`, `branch/end`, filled when the move committed, woken by its move signal. It restates the line's birth identity byte for byte and then the sentences the move changes; the root never receives one, and a load whose latest block disagrees with the tree writes the - missing note once (design [§5](../../../design/timeline-branches.md#5-parts), [§12.1](../../../design/timeline-branches.md#121-context-mapping)). + missing note once; on the tree's current default branch the load also compares that block's text + with the note this code writes, and replaces a note an older rule set left once (design [§5](../../../design/timeline-branches.md#5-parts), [§12.1](../../../design/timeline-branches.md#121-context-mapping)). - **Roster.** On a line that has opened tool lines, a keyed Append under `branch:roster` of `` lists the lines it opened with the tool that are still open, in the order it opened them, with the first line of each purpose; when none is open the key is retired. A plugin line is never on a roster, and neither is a line the user opened: it stays in the Session's directory and coordinates its own tool lines. A child whose inherited prefix holds a live roster gets one block in its opening input that retires that key, so a line that opened no tool line of its own keeps no list; TimelineTree writes it with the identity block (design [§7.1](../../../design/timeline-branches.md#71-keyed-state-branchline-branchroster-and-branchparent)). - **Parent block.** On a line that is not the root, one keyed Append of diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index 2186c72622..29cff9be40 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -12,7 +12,7 @@ only active lines read their opening source. Parent-child adjacency orders the d A Session with one line is on its root without a query; a Session with more reads the root's newest `branch/default` or `session/forked` through the kind index to find the default branch. The App Server only maps these owner-produced properties into its wire fields. -`TreeCommands.page_end` resolves a raw-event page endpoint using atomic-batch metadata through the live Timeline or the ended line’s store. It decodes no event body and has no wire binding. The default branch's answer and its write are `TreeCommands` methods too: `default_branch()` answers the line the Session's conversation is on, restored from the root's newest `branch/default` or `session/forked`, and `set_default_branch(id, source)` admits an open conversation line whose chain is not ending, then writes `branch/default` on the root. Its refusals are `branch_already_default`, `branch_not_selectable` and `branch_target_protected`, and it writes nothing for any of them. A move queues its transition on every participant that is not the root, so a line owes its note from the moment it can take part, and signals every line; each line's own BranchLine drains its queue and writes the one status note its role earns; a load whose latest `branch:line` block disagrees with the tree writes the missing note once. +`TreeCommands.page_end` resolves a raw-event page endpoint using atomic-batch metadata through the live Timeline or the ended line’s store. It decodes no event body and has no wire binding. The default branch's answer and its write are `TreeCommands` methods too: `default_branch()` answers the line the Session's conversation is on, restored from the root's newest `branch/default` or `session/forked`, and `set_default_branch(id, source)` admits an open conversation line whose chain is not ending, then writes `branch/default` on the root. Its refusals are `branch_already_default`, `branch_not_selectable` and `branch_target_protected`, and it writes nothing for any of them. A move queues its transition on every participant that is not the root, so a line owes its note from the moment it can take part, and signals every line; each line's own BranchLine drains its queue and writes the one status note its role earns; a load whose latest `branch:line` block disagrees with the tree writes the missing note once, and on the tree's current default branch a block whose text differs from the note this code writes is replaced once. ## TimelineTree diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 2b120d24c4..821888e671 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -113,7 +113,7 @@ BranchLine injects `B:Dispatcher`, `B:TimelineIdentity`, `B:BranchLifecycle` and It decides the way Goal does: from consumed state, through an owned write task that rechecks before writing, and only on live events after its load cutoff. A reload therefore writes nothing twice, with one exception: a load whose own history ends with a live roster key the fold does not match writes the roster once, because a restart that completed an ended line (§20.7) recorded `branch/ended` before `main`'s replay, so no live event follows it (§6.2). -The same exception reconciles a move that stopped between its fact and its notes. `branch/default` and each status note are separate batches (§4.5), so a daemon that stops after the fact commits leaves the fact in force and a note unwritten. On load, BranchLine compares two things for its own line: the `default` attribute of the latest live `branch:line` block on it, where a missing attribute means not default, and whether `TreeCommands` reports this line as the default branch now. When they differ it writes the note that matches the tree once, before the line's next model request, and a root never writes one. The new-default note names the line the move started from, so a reconciling load has to know that line: `branch/default` carries it, under the `from` field the note already needs (§16), which is what §4.9 admits a fact for, since the reconciled note decides with it. A load that finds its line's block and the tree in agreement writes nothing, so a second restart writes nothing. +The same exception reconciles a move that stopped between its fact and its notes. `branch/default` and each status note are separate batches (§4.5), so a daemon that stops after the fact commits leaves the fact in force and a note unwritten. On load, BranchLine compares two things for its own line: the `default` attribute of the latest live `branch:line` block on it, where a missing attribute means not default, and whether `TreeCommands` reports this line as the default branch now. When they differ it writes the note that matches the tree once, before the line's next model request, and a root never writes one. The new-default note names the line the move started from, so a reconciling load has to know that line: `branch/default` carries it, under the `from` field the note already needs (§16), which is what §4.9 admits a fact for, since the reconciled note decides with it. A load that finds its line's block and the tree in agreement writes nothing, so a second restart writes nothing. On the line the tree reports as the default branch alone, the comparison also reads the text of that block, so a note an older rule set wrote is replaced once at load. **Restoring the default branch.** A Session whose directory holds one line is on its root and reads nothing for it. A Session with more lines reads one fact: the newest `branch/default` or `session/forked` among the root's own events, through the existing `timeline_events_by_kind` index. A `branch/default` whose target is still open and can be selected names the default branch; a `session/forked` means the default branch is the root, because every `branch/default` the fork copied was written before its `session/forked` and is void; nothing recorded means the root. A target that is no longer open, one naming a plugin line and one naming a line created through a client before the upgrade all fall back to the root (§4). diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 3a32c7188b..4492fb426c 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -109,7 +109,7 @@ BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` 和 `S:TreeCommands`,提供 `B:BranchLine`。 -它的决定方式与 Goal 相同:依据已消费的状态,通过一个写入前会复核的自有写任务,并且只对加载截点之后的实时事件作决定。所以重载时什么都不会写两次,只有一个例外:如果加载时自己的历史里最后有一个仍在生效的名册键,而与折叠出的名册不一致,它就把名册写一次——因为补完一条已结束线的重启(§20.7)在根重放之前就记下了 `branch/ended`,之后没有实时事件跟随(§6.2)。同一条例外补上一次停在事实与说明之间的移动。`branch/default` 和每条状态说明分别是独立的批次(§4.5),所以进程在事实提交之后、某条说明写出之前停下时,事实照样生效、说明却缺了。加载时 BranchLine 对自己这条线比较两件事:它上面最新的有效 `branch:line` 块的 `default` 属性(没有这个属性就算不是默认分支),以及 `TreeCommands` 现在是否报告这条线是默认分支。两者不一致时,它在这条线的下一次模型请求之前补写与树一致的那条说明,一次;根永远不写。给新默认分支的说明会写出移动从哪条线开始,所以补写的加载必须知道那条线:`branch/default` 带着它,放在说明本来就需要的 `from` 字段里(§16),这正是 §4.9 允许一条事实存在的理由——补写的说明要用它来决定。把这条线的块与树对上的加载什么也不写,所以再次重启也不写。 +它的决定方式与 Goal 相同:依据已消费的状态,通过一个写入前会复核的自有写任务,并且只对加载截点之后的实时事件作决定。所以重载时什么都不会写两次,只有一个例外:如果加载时自己的历史里最后有一个仍在生效的名册键,而与折叠出的名册不一致,它就把名册写一次——因为补完一条已结束线的重启(§20.7)在根重放之前就记下了 `branch/ended`,之后没有实时事件跟随(§6.2)。同一条例外补上一次停在事实与说明之间的移动。`branch/default` 和每条状态说明分别是独立的批次(§4.5),所以进程在事实提交之后、某条说明写出之前停下时,事实照样生效、说明却缺了。加载时 BranchLine 对自己这条线比较两件事:它上面最新的有效 `branch:line` 块的 `default` 属性(没有这个属性就算不是默认分支),以及 `TreeCommands` 现在是否报告这条线是默认分支。两者不一致时,它在这条线的下一次模型请求之前补写与树一致的那条说明,一次;根永远不写。给新默认分支的说明会写出移动从哪条线开始,所以补写的加载必须知道那条线:`branch/default` 带着它,放在说明本来就需要的 `from` 字段里(§16),这正是 §4.9 允许一条事实存在的理由——补写的说明要用它来决定。把这条线的块与树对上的加载什么也不写,所以再次重启也不写。只有对树报告为默认分支的那条线,比较还会读这个块的文本,所以旧规则写下的说明在加载时被替换一次。 **默认分支的恢复。** 目录里只有一条线的 Session 就在根上,不为它读任何事实。有多条线的 Session 只读一条事实:在根自己的事件里,最新的一条 `branch/default` 或 `session/forked`,走现有的 `timeline_events_by_kind` 索引。目标仍未结束且可以被选中的 `branch/default` 指明默认分支;最新的一条是 `session/forked` 时,默认分支就是根,因为 fork 拷过来的所有 `branch/default` 都写在它的 `session/forked` 之前、一律失效;什么也没记就是根。目标已经不再是开着的线、指向插件线、以及指向升级前经客户端开出的线时,都回退到根(§4)。 From 90fb566115d2ac40099be93ae159afdb91e7881d Mon Sep 17 00:00:00 2001 From: huihui Date: Sat, 21 Nov 2026 00:18:42 +0800 Subject: [PATCH 8/8] test(branch): take an open cut from an idle opener The root and moving-line tests took the opener's head as the cut while the opener could still be in a turn, so the cut could fall inside an unfinished model output and the open was refused before it reached the tree lock. Take the cut while the opener is idle, before the turns the test starts, and pin the inherited prefix at the child's own branch/start instead of comparing the child's own sequences against the cut. --- .../tests/branch_flow.rs | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 448c5d6b98..314c759af4 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -12134,6 +12134,14 @@ async fn switch(session: &Session, line: &str) { .unwrap(); } +/// The head of `line` while it is idle: a committed boundary, so a turn that +/// starts afterwards cannot leave the position inside an unfinished model +/// output. +async fn idle_cut(session: &Session, line: &str) -> u64 { + soon(session.idle(line)).await.unwrap(); + session.sequence(line).unwrap() +} + const NOT_OPENER: &str = "Only the root and the default branch open lines. Tell one of them if more parallel work is needed."; const LIMIT_REACHED: &str = "This Session holds its limit of open lines. Continue on this line, or end one of its open lines first."; @@ -12205,6 +12213,12 @@ async fn the_root_opens_a_line_while_another_line_is_default() { let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); + // C inherits the root's history through a completed turn: the cut ends a + // committed batch, so no later turn can split it. + soon(session.submit("first turn".into(), InputMode::Queue, "main")) + .await + .unwrap(); + let cut = idle_cut(&session, "main").await; let b = open_line(&session, "b").await; switch(&session, &b).await; let note = line_block( @@ -12220,7 +12234,6 @@ async fn the_root_opens_a_line_while_another_line_is_default() { note.0 ); let before = line_ids(&session); - let cut = session.sequence("main").unwrap(); let result = tool_call( &session, "main", @@ -12246,9 +12259,14 @@ async fn the_root_opens_a_line_while_another_line_is_default() { ); let prefix = chain_events(&session, &c, ..=cut).await.unwrap(); assert_eq!(prefix[0].sequence, 1, "C inherits the root's history"); - assert!( - prefix.last().is_some_and(|event| event.sequence < cut), - "C inherits the root's history only through its cut" + let own = prefix + .iter() + .rposition(|event| matches!(event.kind, EventKind::BranchStart(_))) + .expect("C's own branch/start follows the inherited prefix"); + assert_eq!( + prefix[own - 1].sequence, + cut, + "C inherits the root's history through its cut and not past it" ); let roster = until_events(&session, "main", |events| { roster_block(events).is_some_and(|(text, retired)| !retired && text.contains(&c)) @@ -12685,6 +12703,7 @@ async fn an_open_after_a_move_waits_and_counts_the_moves_result() { let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); + let cut = idle_cut(&session, "main").await; let a = open_line(&session, "a").await; switch(&session, &a).await; let tree = session.session_service::().unwrap(); @@ -12700,7 +12719,6 @@ async fn an_open_after_a_move_waits_and_counts_the_moves_result() { result = &mut moved => panic!("the move answered before its fact committed: {result:?}"), _ = store.wait_holding() => {} } - let cut = session.sequence("main").unwrap(); let before = line_ids(&session); let written = creates(&local_events(&session, "main").await); let mut created = Box::pin(open_with_tool(&probe, "main", cut, "b")); @@ -12806,10 +12824,10 @@ async fn a_paused_build_does_not_hold_the_tree_lock() { let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); + let cut = idle_cut(&session, "main").await; let a = open_line(&session, "a").await; probe.delay_child.store(true, Ordering::SeqCst); let builds = probe.child_builds.load(Ordering::SeqCst); - let cut = session.sequence("main").unwrap(); let mut created = Box::pin(open_with_tool(&probe, "main", cut, "held")); tokio::select! { result = &mut created => panic!("the paused build answered: {result:?}"),