Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

perf(agent-runtime): coordinate file batches through Host identities

cauliflower20abd41b51bd
diff --cc crates/host-core/src/file_batches.rs
index 000000000,000000000..585b4f832
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/file_batches.rs
@@@ -1,0 -1,0 +1,392 @@@
++//! Bounded, process-local source-order records. Used under ToolBudget's mutex;
++//! no filesystem access or asynchronous work is allowed in this module.
++use std::collections::HashMap;
++use std::sync::Arc;
++use std::time::{Duration, Instant};
++
++use serde::{Deserialize, Serialize};
++use serde_json::Value;
++
++use crate::file_resources::{is_file_tool, is_write, FileResources};
++
++const MAX_CALLS: usize = 512;
++const MAX_BATCH_CALLS: usize = 128;
++const MAX_ARGUMENT_BYTES: usize = 32 * 1024 * 1024;
++const UNUSED_TTL: Duration = Duration::from_secs(15 * 60);
++
++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
++#[serde(rename_all = "camelCase", deny_unknown_fields)]
++pub struct BatchCall {
++ pub session_id: String,
++ pub delegation_id: Option<String>,
++ pub batch_id: String,
++ pub ordinal: u32,
++ pub tool_call_id: String,
++ pub tool_name: String,
++ pub args: Value,
++}
++
++struct Slot {
++ call: BatchCall,
++ argument_bytes: usize,
++ submitted: bool,
++ running: bool,
++ terminal: bool,
++ resources: Option<Arc<FileResources>>,
++}
++
++struct Batch {
++ session: String,
++ delegation: Option<String>,
++ tickets: Vec<String>,
++ sealed: bool,
++ closed: bool,
++ created: Instant,
++}
++
++#[derive(Default)]
++pub struct FileBatches {
++ batches: HashMap<String, Batch>,
++ slots: HashMap<String, Slot>,
++ argument_bytes: usize,
++}
++
++impl FileBatches {
++ pub fn register(&mut self, call: BatchCall) -> Result<String, &'static str> {
++ self.sweep();
++ if !is_file_tool(&call.tool_name)
++ || call.ordinal > 100_000
++ || [&call.session_id, &call.batch_id, &call.tool_call_id]
++ .iter()
++ .any(|s| s.is_empty() || s.len() > 256)
++ || call
++ .delegation_id
++ .as_ref()
++ .is_some_and(|s| s.is_empty() || s.len() > 256)
++ || !call.args.is_object()
++ {
++ return Err("invalid file batch call");
++ }
++ let bytes = serde_json::to_vec(&call.args)
++ .map_err(|_| "invalid arguments")?
++ .len();
++ if self.slots.len() >= MAX_CALLS
++ || self.argument_bytes.saturating_add(bytes) > MAX_ARGUMENT_BYTES
++ {
++ return Err("file batch registry is full");
++ }
++ let batch = self
++ .batches
++ .entry(call.batch_id.clone())
++ .or_insert_with(|| Batch {
++ session: call.session_id.clone(),
++ delegation: call.delegation_id.clone(),
++ tickets: Vec::new(),
++ sealed: false,
++ closed: false,
++ created: Instant::now(),
++ });
++ if batch.session != call.session_id
++ || batch.delegation != call.delegation_id
++ || batch.sealed
++ || batch.closed
++ || batch.tickets.len() >= MAX_BATCH_CALLS
++ || batch
++ .tickets
++ .last()
++ .and_then(|t| self.slots.get(t))
++ .is_some_and(|s| s.call.ordinal >= call.ordinal)
++ || batch
++ .tickets
++ .iter()
++ .filter_map(|t| self.slots.get(t))
++ .any(|s| s.call.tool_call_id == call.tool_call_id)
++ {
++ return Err("file batch ownership or source order mismatch");
++ }
++ let ticket = uuid::Uuid::new_v4().to_string();
++ batch.tickets.push(ticket.clone());
++ self.argument_bytes += bytes;
++ self.slots.insert(
++ ticket.clone(),
++ Slot {
++ call,
++ argument_bytes: bytes,
++ submitted: false,
++ running: false,
++ terminal: false,
++ resources: None,
++ },
++ );
++ Ok(ticket)
++ }
++
++ pub fn seal(&mut self, batch_id: &str, session: &str) -> Result<(), &'static str> {
++ let batch = self
++ .batches
++ .get_mut(batch_id)
++ .ok_or("file batch not found")?;
++ if batch.session != session || batch.closed {
++ return Err("file batch ownership mismatch");
++ }
++ batch.sealed = true;
++ Ok(())
++ }
++
++ pub fn begin(
++ &mut self,
++ ticket: &str,
++ session: &str,
++ delegation: Option<&str>,
++ id: &str,
++ name: &str,
++ args: &Value,
++ ) -> Result<(), &'static str> {
++ let slot = self
++ .slots
++ .get_mut(ticket)
++ .ok_or("file batch ticket not found")?;
++ let batch = self
++ .batches
++ .get(&slot.call.batch_id)
++ .ok_or("file batch not found")?;
++ if !batch.sealed
++ || batch.closed
++ || slot.submitted
++ || slot.terminal
++ || slot.call.session_id != session
++ || slot.call.delegation_id.as_deref() != delegation
++ || slot.call.tool_call_id != id
++ || slot.call.tool_name != name
++ || slot.call.args != *args
++ {
++ return Err("invalid, changed or already consumed file batch ticket");
++ }
++ slot.submitted = true;
++ Ok(())
++ }
++
++ pub fn classify(&mut self, ticket: &str, resources: Arc<FileResources>) {
++ if let Some(slot) = self.slots.get_mut(ticket) {
++ slot.resources = Some(resources);
++ }
++ }
++
++ pub fn can_run(&self, ticket: &str, claims: &FileResources) -> bool {
++ let Some(slot) = self.slots.get(ticket) else {
++ return false;
++ };
++ let Some(batch) = self.batches.get(&slot.call.batch_id) else {
++ return false;
++ };
++ if slot.terminal || !slot.submitted {
++ return false;
++ }
++ batch
++ .tickets
++ .iter()
++ .take_while(|t| t.as_str() != ticket)
++ .all(|t| {
++ self.slots.get(t).is_none_or(|prior| {
++ prior.terminal
++ || match &prior.resources {
++ Some(resources) => !resources.conflicts(claims),
++ None => !is_write(&prior.call.tool_name) && !claims.exclusive,
++ }
++ })
++ })
++ }
++
++ pub fn precedes(&self, first: &str, second: &str) -> bool {
++ match (self.slots.get(first), self.slots.get(second)) {
++ (Some(a), Some(b)) => {
++ a.call.batch_id == b.call.batch_id && a.call.ordinal < b.call.ordinal
++ }
++ _ => false,
++ }
++ }
++
++ pub fn start(&mut self, ticket: &str) {
++ if let Some(slot) = self.slots.get_mut(ticket) {
++ slot.running = true;
++ }
++ }
++
++ /// The execution permit alone can complete a running slot. Dropping the
++ /// transport waiter or closing a batch never releases active disk work.
++ pub fn finish(&mut self, ticket: &str, execution_finished: bool) {
++ if let Some(slot) = self.slots.get_mut(ticket) {
++ if !slot.running || execution_finished {
++ slot.terminal = true;
++ slot.resources = None;
++ }
++ }
++ self.collect_closed();
++ }
++
++ pub fn abandon(&mut self, ticket: &str, session: &str) -> Result<(), &'static str> {
++ let slot = self
++ .slots
++ .get(ticket)
++ .ok_or("file batch ticket not found")?;
++ if slot.call.session_id != session {
++ return Err("file batch ownership mismatch");
++ }
++ if !slot.submitted {
++ self.finish(ticket, false);
++ }
++ Ok(())
++ }
++
++ pub fn close(&mut self, batch_id: &str, session: &str) -> Result<(), &'static str> {
++ let Some(batch) = self.batches.get_mut(batch_id) else {
++ return Ok(());
++ };
++ if batch.session != session {
++ return Err("file batch ownership mismatch");
++ }
++ batch.closed = true;
++ for ticket in &batch.tickets {
++ if let Some(slot) = self.slots.get_mut(ticket) {
++ if !slot.submitted {
++ slot.terminal = true;
++ slot.resources = None;
++ }
++ }
++ }
++ self.collect_closed();
++ Ok(())
++ }
++
++ fn collect_closed(&mut self) {
++ self.batches.retain(|_, batch| {
++ let collect = batch.closed
++ && batch
++ .tickets
++ .iter()
++ .all(|t| self.slots.get(t).is_none_or(|s| s.terminal));
++ if collect {
++ for t in &batch.tickets {
++ if let Some(slot) = self.slots.remove(t) {
++ self.argument_bytes -= slot.argument_bytes;
++ }
++ }
++ }
++ !collect
++ });
++ }
++
++ fn sweep(&mut self) {
++ for batch in self.batches.values_mut() {
++ if batch.created.elapsed() > UNUSED_TTL
++ && batch
++ .tickets
++ .iter()
++ .all(|t| self.slots.get(t).is_none_or(|s| !s.submitted || s.terminal))
++ {
++ batch.closed = true;
++ for ticket in &batch.tickets {
++ if let Some(slot) = self.slots.get_mut(ticket) {
++ slot.terminal = true;
++ slot.resources = None;
++ }
++ }
++ }
++ }
++ self.collect_closed();
++ }
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++ use serde_json::json;
++ fn call(ordinal: u32, name: &str) -> BatchCall {
++ BatchCall {
++ session_id: "s".into(),
++ delegation_id: None,
++ batch_id: "b".into(),
++ ordinal,
++ tool_call_id: ordinal.to_string(),
++ tool_name: name.into(),
++ args: json!({"path":"a"}),
++ }
++ }
++ #[test]
++ fn unknown_predecessor_and_reversed_execution_cannot_reorder_writes() {
++ let mut registry = FileBatches::default();
++ let first = registry.register(call(0, "Read")).unwrap();
++ let second_call = call(1, "Write");
++ let second = registry.register(second_call.clone()).unwrap();
++ registry.seal("b", "s").unwrap();
++ registry
++ .begin(&second, "s", None, "1", "Write", &second_call.args)
++ .unwrap();
++ assert!(!registry.can_run(&second, &FileResources::fence(true)));
++ registry.finish(&first, false);
++ assert!(registry.can_run(&second, &FileResources::fence(true)));
++ }
++ #[test]
++ fn validates_binding_sealing_replay_and_running_cleanup() {
++ let mut r = FileBatches::default();
++ let c = call(0, "Write");
++ let t = r.register(c.clone()).unwrap();
++ assert!(r.begin(&t, "s", None, "0", "Write", &c.args).is_err());
++ r.seal("b", "s").unwrap();
++ assert!(r.begin(&t, "other", None, "0", "Write", &c.args).is_err());
++ assert!(r
++ .begin(&t, "s", Some("other-delegate"), "0", "Write", &c.args)
++ .is_err());
++ assert!(r
++ .begin(&t, "s", None, "other-call", "Write", &c.args)
++ .is_err());
++ assert!(r.begin(&t, "s", None, "0", "Read", &c.args).is_err());
++ assert!(r
++ .begin(&t, "s", None, "0", "Write", &json!({"path":"changed"}))
++ .is_err());
++ r.begin(&t, "s", None, "0", "Write", &c.args).unwrap();
++ assert!(r.begin(&t, "s", None, "0", "Write", &c.args).is_err());
++ r.start(&t);
++ r.close("b", "s").unwrap();
++ r.finish(&t, false);
++ assert!(!r.slots[&t].terminal);
++ r.finish(&t, true);
++ assert!(r.slots.is_empty());
++ }
++
++ #[test]
++ fn bounded_registry_reclaims_closed_calls_and_preserves_live_approvals() {
++ let mut r = FileBatches::default();
++ for index in 0..MAX_BATCH_CALLS {
++ r.register(call(index as u32, "Read")).unwrap();
++ }
++ assert!(r.register(call(MAX_BATCH_CALLS as u32, "Read")).is_err());
++ r.close("b", "s").unwrap();
++ assert!(r.slots.is_empty());
++ assert_eq!(r.argument_bytes, 0);
++ let c = call(0, "Write");
++ let t = r.register(c.clone()).unwrap();
++ r.seal("b", "s").unwrap();
++ r.begin(&t, "s", None, "0", "Write", &c.args).unwrap();
++ r.batches.get_mut("b").unwrap().created =
++ Instant::now() - UNUSED_TTL - Duration::from_secs(1);
++ r.sweep();
++ assert!(
++ !r.slots[&t].terminal,
++ "an indefinite permission wait must not expire"
++ );
++ r.finish(&t, false);
++ r.close("b", "s").unwrap();
++ assert!(r.slots.is_empty());
++ }
++
++ #[test]
++ fn source_registration_rejects_unknown_tools_and_duplicate_ordinals() {
++ let mut r = FileBatches::default();
++ assert!(r.register(call(0, "plugin_Read")).is_err());
++ r.register(call(0, "Read")).unwrap();
++ assert!(r.register(call(0, "Write")).is_err());
++ r.seal("b", "s").unwrap();
++ assert!(r.register(call(1, "Write")).is_err());
++ }
++}
diff --cc crates/host-core/src/file_resources.rs
index 000000000,000000000..94b954694
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/file_resources.rs
@@@ -1,0 -1,0 +1,267 @@@
++//! Host-owned identities for the file tools. Paths are addresses, not identities.
++//! Unknown identities and namespace-changing operations use a host-wide fence.
++use std::fs::File;
++use std::path::{Path, PathBuf};
++use std::sync::Arc;
++
++use serde_json::Value;
++
++use crate::workspace::{resolve_tool_path_with_external, ContainedRoots};
++
++#[derive(Debug, Clone, PartialEq, Eq)]
++struct FileId(u64, u128);
++
++#[derive(Debug)]
++pub struct FileResources {
++ pub exclusive: bool,
++ identity: Option<FileId>,
++ address: Option<PathBuf>,
++ // Keep the object alive while its ID is used, including queued admission.
++ _file: Option<File>,
++}
++
++pub fn is_file_tool(name: &str) -> bool {
++ matches!(name, "Read" | "Glob" | "Grep" | "Write" | "Edit")
++}
++
++pub fn is_write(name: &str) -> bool {
++ matches!(name, "Write" | "Edit")
++}
++
++impl FileResources {
++ pub fn fence(exclusive: bool) -> Arc<Self> {
++ Arc::new(Self {
++ exclusive,
++ identity: None,
++ address: None,
++ _file: None,
++ })
++ }
++
++ pub fn conflicts(&self, other: &Self) -> bool {
++ (self.exclusive || other.exclusive)
++ && (self.identity.is_none()
++ || other.identity.is_none()
++ || self.identity == other.identity
++ || self.address == other.address)
++ }
++
++ /// Called only after the existing permission decision. No contents are read.
++ pub fn resolve(
++ root: Option<&Path>,
++ roots: &ContainedRoots,
++ name: &str,
++ args: &Value,
++ external: bool,
++ ) -> Arc<Self> {
++ let exclusive = is_write(name);
++ let Some(root) = root else {
++ return Self::fence(exclusive);
++ };
++ // Namespace changes and session registers conservatively fence all file
++ // tools, including paths approved outside the workspace.
++ if matches!(name, "Glob" | "Grep") || (name == "Edit" && structural_edit(args)) {
++ return Self::fence(exclusive);
++ }
++ let Some(path) = args.get("path").and_then(Value::as_str) else {
++ return Self::fence(exclusive);
++ };
++ let Ok((address, _)) = resolve_tool_path_with_external(root, roots, path, external) else {
++ // Execution still reports the original permission/path/I/O failure.
++ return Self::fence(exclusive);
++ };
++ let Ok(file) = File::open(&address) else {
++ return Self::fence(exclusive);
++ };
++ let Ok(metadata) = file.metadata() else {
++ return Self::fence(exclusive);
++ };
++ if !metadata.is_file() {
++ return Self::fence(exclusive);
++ }
++ let Some(identity) = file_id(&file, &address) else {
++ return Self::fence(exclusive);
++ };
++ Arc::new(Self {
++ exclusive,
++ identity: Some(identity),
++ address: Some(address),
++ _file: Some(file),
++ })
++ }
++
++ /// Revalidate under the granted lease before snapshotting and in the actual
++ /// blocking task. A changed binding fails before mutation; it is never replayed.
++ pub fn validate(
++ &self,
++ root: Option<&Path>,
++ roots: &ContainedRoots,
++ name: &str,
++ args: &Value,
++ external: bool,
++ ) -> Result<(), String> {
++ if self.identity.is_none() {
++ return Ok(());
++ }
++ let current = Self::resolve(root, roots, name, args, external);
++ if self.identity == current.identity && self.address == current.address {
++ Ok(())
++ } else {
++ Err("file identity changed while awaiting admission; read the path again before retrying".into())
++ }
++ }
++}
++
++fn structural_edit(args: &Value) -> bool {
++ args.get("ops").and_then(Value::as_str).is_some_and(|ops| {
++ ops.lines().any(|line| {
++ let mut words = line.split_whitespace();
++ matches!(words.next(), Some("MV" | "REM"))
++ || (matches!(line.split_whitespace().next(), Some("CUT" | "PUT"))
++ && words.any(|word| word.starts_with('@')))
++ })
++ })
++}
++
++#[cfg(unix)]
++fn file_id(file: &File, _address: &Path) -> Option<FileId> {
++ use std::os::fd::AsRawFd;
++ use std::os::unix::fs::MetadataExt;
++ // Only local filesystems with trustworthy object IDs may prove independence.
++ let mut fs = std::mem::MaybeUninit::<libc::statfs>::uninit();
++ if unsafe { libc::fstatfs(file.as_raw_fd(), fs.as_mut_ptr()) } != 0 {
++ return None;
++ }
++ let fs = unsafe { fs.assume_init() };
++ #[cfg(target_os = "linux")]
++ if !matches!(
++ fs.f_type as u64,
++ 0xEF53 | 0x58465342 | 0x9123683E | 0x01021994 | 0x794C7630
++ ) {
++ return None;
++ }
++ #[cfg(target_os = "macos")]
++ if fs.f_flags & libc::MNT_LOCAL == 0 {
++ return None;
++ }
++ let metadata = file.metadata().ok()?;
++ Some(FileId(metadata.dev(), u128::from(metadata.ino())))
++}
++
++#[cfg(windows)]
++fn file_id(file: &File, address: &Path) -> Option<FileId> {
++ use std::os::windows::io::AsRawHandle;
++ use windows_sys::Win32::Storage::FileSystem::{
++ FileIdInfo, GetDriveTypeW, GetFileInformationByHandleEx, FILE_ID_INFO,
++ };
++ let spelling = address.to_string_lossy();
++ let bytes = spelling.as_bytes();
++ if bytes.len() < 3 || bytes[1] != b':' {
++ return None;
++ }
++ let root: Vec<u16> = format!("{}:\\", bytes[0] as char)
++ .encode_utf16()
++ .chain(Some(0))
++ .collect();
++ // DRIVE_FIXED / DRIVE_REMOVABLE only. UNC and mapped network drives fence.
++ if !matches!(unsafe { GetDriveTypeW(root.as_ptr()) }, 2 | 3) {
++ return None;
++ }
++ let mut info = std::mem::MaybeUninit::<FILE_ID_INFO>::uninit();
++ let ok = unsafe {
++ GetFileInformationByHandleEx(
++ file.as_raw_handle().cast(),
++ FileIdInfo,
++ info.as_mut_ptr().cast(),
++ std::mem::size_of::<FILE_ID_INFO>() as u32,
++ )
++ };
++ if ok == 0 {
++ return None;
++ }
++ let info = unsafe { info.assume_init() };
++ Some(FileId(
++ info.VolumeSerialNumber,
++ u128::from_le_bytes(info.FileId.Identifier),
++ ))
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++ use serde_json::json;
++
++ fn claims(root: &Path, name: &str, path: &str) -> Arc<FileResources> {
++ FileResources::resolve(
++ Some(root),
++ &ContainedRoots::new(),
++ name,
++ &json!({"path":path}),
++ false,
++ )
++ }
++
++ #[test]
++ fn hard_links_conflict_and_independent_files_overlap() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("actual"), "a").unwrap();
++ std::fs::hard_link(dir.path().join("actual"), dir.path().join("alias")).unwrap();
++ std::fs::write(dir.path().join("other"), "b").unwrap();
++ let read = claims(dir.path(), "Read", "alias");
++ let write = claims(dir.path(), "Write", "actual");
++ assert!(read.conflicts(&write));
++ assert!(!read.conflicts(&claims(dir.path(), "Write", "other")));
++ assert!(!read.conflicts(&claims(dir.path(), "Read", "actual")));
++ }
++
++ #[test]
++ fn missing_targets_and_structural_edits_fence() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("a"), "a").unwrap();
++ let read = claims(dir.path(), "Read", "a");
++ assert!(read.conflicts(&claims(dir.path(), "Write", "missing")));
++ for ops in ["MV other", "REM", "CUT 1.=2 @r", "PUT <1 @r"] {
++ let edit = FileResources::resolve(
++ Some(dir.path()),
++ &ContainedRoots::new(),
++ "Edit",
++ &json!({"path":"a", "ops":ops}),
++ false,
++ );
++ assert!(edit.identity.is_none());
++ assert!(read.conflicts(&edit));
++ }
++ }
++
++ #[cfg(unix)]
++ #[test]
++ fn symbolic_links_and_cross_root_hard_links_share_identity() {
++ let dir = tempfile::tempdir().unwrap();
++ let a = dir.path().join("root-a");
++ let b = dir.path().join("root-b");
++ std::fs::create_dir_all(&a).unwrap();
++ std::fs::create_dir_all(&b).unwrap();
++ std::fs::write(a.join("actual"), "a").unwrap();
++ std::os::unix::fs::symlink("actual", a.join("alias")).unwrap();
++ std::fs::hard_link(a.join("actual"), b.join("different")).unwrap();
++ assert!(claims(&a, "Read", "alias").conflicts(&claims(&b, "Write", "different")));
++ }
++
++ #[test]
++ fn replaced_object_is_rejected_before_writing() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("a"), "a").unwrap();
++ let write = claims(dir.path(), "Write", "a");
++ std::fs::rename(dir.path().join("a"), dir.path().join("old")).unwrap();
++ std::fs::write(dir.path().join("a"), "replacement").unwrap();
++ assert!(write
++ .validate(
++ Some(dir.path()),
++ &ContainedRoots::new(),
++ "Write",
++ &json!({"path":"a"}),
++ false
++ )
++ .is_err());
++ }
++}
diff --cc crates/host-core/src/main.rs
index cca6c6826,cca6c6826..601ece190
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@@ -6,6 -6,6 +6,8 @@@ mod background_tasks
mod config_sync;
mod data_relocation;
mod db;
++mod file_batches;
++mod file_resources;
mod keyboard;
mod mcp_servers;
mod network_policy;
diff --cc crates/host-core/src/rpc/file_batches.rs
index 000000000,000000000..e16287a94
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/rpc/file_batches.rs
@@@ -1,0 -1,0 +1,112 @@@
++//! Internal batch metadata protocol. Registration grants neither permission nor
++//! execution capacity and performs no filesystem lookup.
++use super::*;
++use crate::file_batches::BatchCall;
++#[cfg(test)]
++mod tests;
++
++#[derive(Deserialize)]
++#[serde(rename_all = "camelCase", deny_unknown_fields)]
++struct BatchAction {
++ session_id: String,
++ batch_id: Option<String>,
++ ticket: Option<String>,
++}
++
++/// Approval/admission may await arbitrary user or tool work. Do not execute
++/// against a root captured before that wait if its persisted binding changed.
++pub(super) fn verify_root(
++ state: &AppState,
++ call: &ToolsExecuteParams,
++ expected: Option<&str>,
++) -> Result<bool, JsonRpcError> {
++ if remote_tools::session_remote_workspace_optional(state, &call.session_id)?.is_some() {
++ return Err(rpc_err(
++ 1002,
++ "tool workspace changed during admission",
++ "TOOL_CONTEXT_CHANGED",
++ ));
++ }
++ let delegated = crate::session_worktrees::delegate::tool_root(
++ &state.db,
++ &call.session_id,
++ call.delegation_id.as_deref(),
++ )
++ .map_err(worktree_rpc::to_rpc)?;
++ let own = delegated.is_some();
++ let current = match delegated {
++ Some(path) => Some(path.to_string_lossy().into_owned()),
++ None => resolve_tool_workspace_for_call(state, &call.session_id, &call.args)?,
++ };
++ if current.as_deref() != expected {
++ return Err(rpc_err(
++ 1002,
++ "tool workspace changed during admission",
++ "TOOL_CONTEXT_CHANGED",
++ ));
++ }
++ Ok(own)
++}
++
++pub(super) async fn handle(
++ state: Arc<Mutex<AppState>>,
++ method: &str,
++ params: Value,
++) -> Result<Value, JsonRpcError> {
++ if method == "tools.fileBatchRegister" {
++ let call: BatchCall = serde_json::from_value(params)
++ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
++ let st = state.lock().await;
++ if remote_tools::session_remote_workspace(&st, &call.session_id)?.is_some() {
++ return Err(rpc_err(
++ 1002,
++ "remote Host file batches are unavailable",
++ "CAPABILITY_UNAVAILABLE",
++ ));
++ }
++ let ticket = st
++ .tool_budget
++ .register_file_call(call)
++ .map_err(|e| rpc_err(1002, e, "INVALID_PARAMS"))?;
++ return Ok(json!({"ticket":ticket}));
++ }
++ let action: BatchAction = serde_json::from_value(params)
++ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
++ let st = state.lock().await;
++ if method == "tools.fileBatchCapabilities" {
++ let local = remote_tools::session_remote_workspace(&st, &action.session_id)?.is_none();
++ return Ok(json!({"version":1,"supported":local}));
++ }
++ let result = match method {
++ "tools.fileBatchSeal" => st.tool_budget.seal_file_batch(
++ action
++ .batch_id
++ .as_deref()
++ .ok_or_else(|| rpc_err(1002, "batchId required", "INVALID_PARAMS"))?,
++ &action.session_id,
++ ),
++ "tools.fileBatchClose" => st.tool_budget.close_file_batch(
++ action
++ .batch_id
++ .as_deref()
++ .ok_or_else(|| rpc_err(1002, "batchId required", "INVALID_PARAMS"))?,
++ &action.session_id,
++ ),
++ "tools.fileBatchAbandon" => st.tool_budget.abandon_file_call(
++ action
++ .ticket
++ .as_deref()
++ .ok_or_else(|| rpc_err(1002, "ticket required", "INVALID_PARAMS"))?,
++ &action.session_id,
++ ),
++ _ => {
++ return Err(rpc_err(
++ -32601,
++ "unknown file batch method",
++ "METHOD_NOT_FOUND",
++ ))
++ }
++ };
++ result.map_err(|e| rpc_err(1002, e, "INVALID_PARAMS"))?;
++ Ok(json!({"ok":true}))
++}
diff --cc crates/host-core/src/rpc/file_batches/tests.rs
index 000000000,000000000..5cb1841a6
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/rpc/file_batches/tests.rs
@@@ -1,0 -1,0 +1,207 @@@
++use super::super::handle_request;
++use crate::{sessions, state::AppState};
++use serde_json::{json, Value};
++use std::future::{poll_fn, Future};
++use std::sync::Arc;
++use std::task::Poll;
++use tokio::sync::{mpsc, Mutex};
++
++async fn setup() -> (tempfile::TempDir, Arc<Mutex<AppState>>, String) {
++ let dir = tempfile::tempdir().unwrap();
++ let project = dir.path().join("project");
++ std::fs::create_dir(&project).unwrap();
++ std::fs::write(project.join("actual"), "before").unwrap();
++ std::fs::hard_link(project.join("actual"), project.join("alias")).unwrap();
++ let mut app = AppState::open(dir.path()).unwrap();
++ app.handshook = true;
++ let session = sessions::create_session(
++ &app.db,
++ None,
++ Some("agent".into()),
++ None,
++ None,
++ Some(project.to_string_lossy().into_owned()),
++ )
++ .unwrap();
++ sessions::configure_session_with_thinking(
++ &app.db,
++ &session.id,
++ "agent",
++ None,
++ None,
++ None,
++ Some("auto"),
++ )
++ .unwrap();
++ (dir, Arc::new(Mutex::new(app)), session.id)
++}
++
++async fn request(
++ state: &Arc<Mutex<AppState>>,
++ method: &str,
++ params: Value,
++) -> Result<Value, super::super::JsonRpcError> {
++ handle_request(state.clone(), method, params, mpsc::unbounded_channel().0).await
++}
++
++#[tokio::test]
++async fn file_batch_rpc_orders_real_hard_link_tools_despite_reversed_arrival() {
++ for write_first in [false, true] {
++ let (dir, state, session) = setup().await;
++ assert_eq!(
++ request(
++ &state,
++ "tools.fileBatchCapabilities",
++ json!({"sessionId":session})
++ )
++ .await
++ .unwrap()["supported"],
++ true
++ );
++ let names = if write_first {
++ ["Write", "Read"]
++ } else {
++ ["Read", "Write"]
++ };
++ let args = [
++ json!({"path":"alias","content":"after"}),
++ json!({"path":"actual","content":"after"}),
++ ];
++ let mut tickets = Vec::new();
++ for i in 0..2 {
++ let response=request(&state,"tools.fileBatchRegister",json!({
++ "sessionId":session,"batchId":"batch","ordinal":i,"toolCallId":i.to_string(),"toolName":names[i],"args":args[i]
++ })).await.unwrap();
++ tickets.push(response["ticket"].as_str().unwrap().to_owned());
++ }
++ request(
++ &state,
++ "tools.fileBatchSeal",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++ let budget = state.lock().await.tool_budget.clone();
++ let later_params = json!({"sessionId":session,"mode":"agent","toolCallId":"1","toolName":names[1],"args":args[1],"fileBatchTicket":tickets[1]});
++ let mut later = Box::pin(request(&state, "tools.execute", later_params));
++ // Poll through actual permission and blocking-pool identity resolution,
++ // stopping exactly when the later call is queued behind its predecessor.
++ poll_fn(|cx| {
++ assert!(
++ later.as_mut().poll(cx).is_pending(),
++ "later RPC executed before its registered predecessor"
++ );
++ if budget.snapshot().queued == 1 {
++ Poll::Ready(())
++ } else {
++ Poll::Pending
++ }
++ })
++ .await;
++ assert_eq!(budget.snapshot().active, 0);
++ let first=request(&state,"tools.execute",json!({"sessionId":session,"mode":"agent","toolCallId":"0","toolName":names[0],"args":args[0],"fileBatchTicket":tickets[0]})).await.unwrap();
++ let second = later.await.unwrap();
++ assert_eq!(first["ok"], true, "{first}");
++ assert_eq!(second["ok"], true, "{second}");
++ let read = if write_first { &second } else { &first };
++ assert!(
++ read["content"]
++ .to_string()
++ .contains(if write_first { "after" } else { "before" }),
++ "{read}"
++ );
++ assert_eq!(
++ std::fs::read_to_string(dir.path().join("project/actual")).unwrap(),
++ "after"
++ );
++ request(
++ &state,
++ "tools.fileBatchClose",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++ assert_eq!(budget.snapshot().active, 0);
++ assert_eq!(budget.snapshot().queued, 0);
++ }
++}
++
++#[tokio::test]
++async fn file_batch_rpc_rejects_changed_arguments_and_replay_without_writing() {
++ let (dir, state, session) = setup().await;
++ let registration = json!({"sessionId":session,"batchId":"batch","ordinal":0,"toolCallId":"w","toolName":"Write","args":{"path":"actual","content":"allowed"}});
++ let ticket = request(&state, "tools.fileBatchRegister", registration)
++ .await
++ .unwrap()["ticket"]
++ .clone();
++ request(
++ &state,
++ "tools.fileBatchSeal",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++ let call = json!({"sessionId":session,"mode":"agent","toolCallId":"w","toolName":"Write","args":{"path":"actual","content":"allowed"},"fileBatchTicket":ticket});
++ let mut changed = call.clone();
++ changed["args"]["content"] = json!("tampered");
++ assert!(request(&state, "tools.execute", changed).await.is_err());
++ assert_eq!(
++ std::fs::read_to_string(dir.path().join("project/actual")).unwrap(),
++ "before"
++ );
++ assert_eq!(
++ request(&state, "tools.execute", call.clone())
++ .await
++ .unwrap()["ok"],
++ true
++ );
++ assert!(request(&state, "tools.execute", call).await.is_err());
++ assert_eq!(
++ std::fs::read_to_string(dir.path().join("project/actual")).unwrap(),
++ "allowed"
++ );
++ request(
++ &state,
++ "tools.fileBatchClose",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++}
++
++#[tokio::test]
++async fn file_batch_registration_does_not_grant_permission_to_write_in_plan_mode() {
++ let (dir, state, session) = setup().await;
++ sessions::configure_session_with_thinking(
++ &state.lock().await.db,
++ &session,
++ "plan",
++ None,
++ None,
++ None,
++ Some("auto"),
++ )
++ .unwrap();
++ let ticket=request(&state,"tools.fileBatchRegister",json!({"sessionId":session,"batchId":"batch","ordinal":0,"toolCallId":"w","toolName":"Write","args":{"path":"actual","content":"forbidden"}})).await.unwrap()["ticket"].clone();
++ request(
++ &state,
++ "tools.fileBatchSeal",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++ let result=request(&state,"tools.execute",json!({"sessionId":session,"mode":"agent","toolCallId":"w","toolName":"Write","args":{"path":"actual","content":"forbidden"},"fileBatchTicket":ticket})).await.unwrap();
++ assert_eq!(result["ok"], false);
++ assert_eq!(result["errorCode"], "WRITE_DISABLED_IN_PLAN");
++ assert_eq!(
++ std::fs::read_to_string(dir.path().join("project/actual")).unwrap(),
++ "before"
++ );
++ request(
++ &state,
++ "tools.fileBatchClose",
++ json!({"sessionId":session,"batchId":"batch"}),
++ )
++ .await
++ .unwrap();
++}
diff --cc crates/host-core/src/rpc/mod.rs
index 089a140d6,089a140d6..49958a549
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@@ -1,4 -1,4 +1,5 @@@
mod config_sync_rpc;
++mod file_batches;
mod gen_ui;
mod plugin_reviews_rpc;
mod remote_tools;
@@@ -1935,6 -1935,6 +1936,10 @@@ async fn handle_request
.map_err(config_sync_rpc_err);
}
++ if method.starts_with("tools.fileBatch") {
++ return file_batches::handle(state, method, params).await;
++ }
++
match method {
"visualizations.readFragment" => gen_ui::read_fragment(state, params).await,
"tools.remoteComplete" | "tools.workspaceExecute" | "tools.workspaceAbort" => {
@@@ -2357,22 -2357,22 +2362,54 @@@
.get("snapshotId")
.and_then(|value| value.as_str())
.ok_or_else(|| rpc_err(1002, "snapshotId required", "INVALID_PARAMS"))?;
++ let budget = {
++ let st = state.lock().await;
++ if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
++ return Err(rpc_err(
++ 1002,
++ "remote workspace rollback is unavailable",
++ "CAPABILITY_UNAVAILABLE",
++ ));
++ }
++ st.tool_budget.clone()
++ };
++ let permit = Arc::new(
++ budget
++ .acquire_files(
++ session_id,
++ "Write",
++ false,
++ crate::file_resources::FileResources::fence(true),
++ None,
++ )
++ .await
++ .map_err(|e| rpc_err(1000, e.message(), e.code()))?,
++ );
++ let _rollback_lease = permit.clone();
++ let (data_dir, workspace_root) = {
++ let st = state.lock().await;
++ // Session/worktree state may have changed while admission waited.
++ (
++ st.data_dir.clone(),
++ resolve_tool_workspace(&st, session_id)?,
++ )
++ };
++ let session = session_id.to_string();
++ let snapshot = snapshot_id.to_string();
++ let root = workspace_root.clone();
++ let outcome = tokio::task::spawn_blocking(move || {
++ let _permit = permit;
++ review::rollback_change(
++ &data_dir,
++ &session,
++ &snapshot,
++ root.as_deref().map(Path::new),
++ )
++ })
++ .await
++ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
++ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
let st = state.lock().await;
-- if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
-- return Err(rpc_err(
-- 1002,
-- "remote workspace rollback is unavailable",
-- "CAPABILITY_UNAVAILABLE",
-- ));
-- }
-- let workspace_root = resolve_tool_workspace(&st, session_id)?;
-- let outcome = review::rollback_change(
-- &st.data_dir,
-- session_id,
-- snapshot_id,
-- workspace_root.as_deref().map(std::path::Path::new),
-- )
-- .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
if matches!(outcome.status, "rolledBack" | "alreadyRolledBack") {
if let Some(root) = workspace_root.as_deref() {
let resolved = std::path::Path::new(root).join(&outcome.path);
@@@ -4044,6 -4044,6 +4081,25 @@@
let call_started = std::time::Instant::now();
let p: ToolsExecuteParams = serde_json::from_value(params.clone())
.map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
++ let _pending_file_call = if let Some(ticket) = p.file_batch_ticket.as_deref() {
++ Some(
++ state
++ .lock()
++ .await
++ .tool_budget
++ .begin_file_call(
++ ticket,
++ &p.session_id,
++ p.delegation_id.as_deref(),
++ &p.tool_call_id,
++ &p.tool_name,
++ &p.args,
++ )
++ .map_err(|e| rpc_err(1002, e, "INVALID_PARAMS"))?,
++ )
++ } else {
++ None
++ };
let execution_timeout_ms = tools::effective_timeout_ms(&p.tool_name, p.timeout_ms);
let remote_workspace = {
@@@ -4450,20 -4450,20 +4506,55 @@@
// stopped while its session's worktree is held for a merge.
let (tool_budget, own_worktree) = {
let st = state.lock().await;
-- let own = matches!(
-- crate::session_worktrees::delegate::tool_root(
-- &st.db,
-- &p.session_id,
-- p.delegation_id.as_deref(),
-- ),
-- Ok(Some(_))
-- );
++ let own = if remote_workspace.is_none()
++ && crate::file_resources::is_file_tool(&p.tool_name)
++ {
++ file_batches::verify_root(&st, &p, workspace_path.as_deref())?
++ } else {
++ matches!(
++ crate::session_worktrees::delegate::tool_root(
++ &st.db,
++ &p.session_id,
++ p.delegation_id.as_deref(),
++ ),
++ Ok(Some(_))
++ )
++ };
(st.tool_budget.clone(), own)
};
++ let file_resources = if remote_workspace.is_none()
++ && crate::file_resources::is_file_tool(&p.tool_name)
++ {
++ let root = workspace_path.clone().map(PathBuf::from);
++ let roots = {
++ let st = state.lock().await;
++ local_contained_roots(&st.data_dir, &p.session_id, false)
++ };
++ let name = p.tool_name.clone();
++ let args = p.args.clone();
++ Some(
++ tokio::task::spawn_blocking(move || {
++ crate::file_resources::FileResources::resolve(
++ root.as_deref(),
++ &roots,
++ &name,
++ &args,
++ external_path_permission,
++ )
++ })
++ .await
++ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
++ )
++ } else {
++ None
++ };
let mut admission_cancellation = cancellation_receiver.clone();
let admitted = tokio::select! {
result = async {
-- if own_worktree {
++ if let Some(resources) = &file_resources {
++ tool_budget.acquire_files(&p.session_id, &p.tool_name, own_worktree,
++ resources.clone(), p.file_batch_ticket.clone()).await
++ } else if own_worktree {
tool_budget
.acquire_in_own_worktree(&p.session_id, &p.tool_name)
.await
@@@ -4476,8 -4476,8 +4567,8 @@@
.map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"));
}
};
-- let _tool_permit = match admitted {
-- Ok(permit) => permit,
++ let tool_permit = match admitted {
++ Ok(permit) => Arc::new(permit),
Err(error) => {
tracing::warn!(
tool = %p.tool_name,
@@@ -4505,6 -4505,6 +4596,28 @@@
};
let ws_path = workspace_path.map(PathBuf::from);
++ tracing::debug!(tool = %p.tool_name, admission_wait_ms = tool_permit.wait_ms,
++ initial_wait_reason = tool_permit.initial_wait_reason, "tool admitted");
++ if let Some(resources) = &file_resources {
++ let roots = {
++ let st = state.lock().await;
++ file_batches::verify_root(
++ &st,
++ &p,
++ ws_path.as_deref().and_then(Path::to_str),
++ )?;
++ local_contained_roots(&st.data_dir, &p.session_id, false)
++ };
++ resources
++ .validate(
++ ws_path.as_deref(),
++ &roots,
++ &p.tool_name,
++ &p.args,
++ external_path_permission,
++ )
++ .map_err(|e| rpc_err(1000, e, "TOOL_FAILED"))?;
++ }
let (data_dir, hashline_store, worktree_env) = {
let st = state.lock().await;
(
@@@ -4642,7 -4642,7 +4755,7 @@@
)
.await
} else {
-- let execute = tools::execute_tool_with_path_access(
++ let execute = tools::execute_tool_with_file_lease(
ws_path.as_deref(),
scratch_path.as_deref(),
&p.tool_name,
@@@ -4654,6 -4654,6 +4767,8 @@@
hashline: Some(hashline_ctx),
visualization_root: visualization_path.as_deref(),
},
++ Some(tool_permit.clone()),
++ file_resources.clone(),
);
if matches!(p.tool_name.as_str(), "Read" | "Glob" | "Grep") {
let mut read_cancellation = cancellation_receiver.clone();
@@@ -4756,6 -4756,6 +4871,8 @@@
"errorCode": result.error_code,
"prompted": prompted,
"permissionWaitMs": permission_wait_ms,
++ "admissionWaitMs": tool_permit.wait_ms,
++ "admissionInitialWaitReason": tool_permit.initial_wait_reason,
"overheadMs": overhead_ms,
"totalMs": total_ms
});
diff --cc crates/host-core/src/tool_budget.rs
index 45da954a9,45da954a9..d4f8a4764
--- a/crates/host-core/src/tool_budget.rs
+++ b/crates/host-core/src/tool_budget.rs
@@@ -1,7 -1,7 +1,9 @@@
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard};
--use std::time::Duration;
++use std::time::{Duration, Instant};
++use crate::file_batches::{BatchCall, FileBatches};
++use crate::file_resources::FileResources;
use tokio::sync::Notify;
pub const MAX_IN_FLIGHT_TOOLS: usize = 16;
@@@ -64,8 -64,8 +66,13 @@@ impl AdmissionError
pub struct ToolPermit {
budget: ToolBudget,
request: Request,
++ pub wait_ms: u64,
++ pub initial_wait_reason: &'static str,
}
++#[cfg(test)]
++mod file_tests;
++
impl Drop for ToolPermit {
fn drop(&mut self) {
let mut state = self.budget.lock();
@@@ -76,6 -76,6 +83,21 @@@
}
}
++/// Owns a submitted ticket across permission, validation and admission failures.
++/// Once running, only ToolPermit (also held by the disk task) may settle it.
++pub struct PendingFileCall {
++ budget: ToolBudget,
++ ticket: String,
++}
++
++impl Drop for PendingFileCall {
++ fn drop(&mut self) {
++ let mut state = self.budget.lock();
++ state.batches.finish(&self.ticket, false);
++ state.dispatch();
++ }
++}
++
/// Marks a session whose exclusive permit is awaited; see `BudgetState::
/// exclusive_pending`.
struct PendingExclusive {
@@@ -146,6 -146,6 +168,8 @@@ struct Request
/// Runs in a subagent's own worktree (ADR 0329), so holding the session
/// for work in the session worktree does not need to stop it.
own_worktree: bool,
++ resources: Option<Arc<FileResources>>,
++ ticket: Option<String>,
}
#[derive(Default)]
@@@ -161,6 -161,6 +185,8 @@@ struct WaitingRequest
request: Request,
ready: Arc<Notify>,
granted: bool,
++ queued_at: Instant,
++ initial_wait_reason: &'static str,
}
#[derive(Default)]
@@@ -176,6 -176,6 +202,8 @@@ struct BudgetState
/// Sessions whose exclusive permit is being awaited; their new calls wait
/// too, so steady traffic cannot keep the session from ever going quiet.
exclusive_pending: HashMap<String, usize>,
++ batches: FileBatches,
++ file_holders: Vec<Arc<FileResources>>,
}
impl ToolClass {
@@@ -190,7 -190,7 +218,37 @@@
}
impl BudgetState {
++ fn wait_reason(&self, request: &Request) -> &'static str {
++ if let Some(resources) = &request.resources {
++ if request
++ .ticket
++ .as_deref()
++ .is_some_and(|t| !self.batches.can_run(t, resources))
++ {
++ return "source_order";
++ }
++ if self.file_holders.iter().any(|r| r.conflicts(resources))
++ || !self.can_pass_waiters(request, self.waiting.len())
++ {
++ return "resource";
++ }
++ }
++ "capacity"
++ }
fn can_admit(&self, request: &Request) -> bool {
++ if let Some(resources) = &request.resources {
++ if self
++ .file_holders
++ .iter()
++ .any(|held| held.conflicts(resources))
++ || request
++ .ticket
++ .as_deref()
++ .is_some_and(|ticket| !self.batches.can_run(ticket, resources))
++ {
++ return false;
++ }
++ }
if self.active >= MAX_IN_FLIGHT_TOOLS
|| self.classes[request.class as usize] >= request.class.limit()
{
@@@ -210,6 -210,6 +268,12 @@@
}
fn reserve(&mut self, request: &Request) {
++ if let Some(resources) = &request.resources {
++ self.file_holders.push(resources.clone());
++ }
++ if let Some(ticket) = &request.ticket {
++ self.batches.start(ticket);
++ }
self.active += 1;
self.classes[request.class as usize] += 1;
let usage = self.sessions.entry(request.session_id.clone()).or_default();
@@@ -223,6 -223,6 +287,18 @@@
}
fn release(&mut self, request: &Request) {
++ if let Some(resources) = &request.resources {
++ if let Some(index) = self
++ .file_holders
++ .iter()
++ .position(|held| Arc::ptr_eq(held, resources))
++ {
++ self.file_holders.remove(index);
++ }
++ }
++ if let Some(ticket) = &request.ticket {
++ self.batches.finish(ticket, true);
++ }
self.active -= 1;
self.classes[request.class as usize] -= 1;
let usage = self
@@@ -246,7 -246,7 +322,10 @@@
// must not prevent unrelated runnable work from using spare capacity.
for index in 0..self.waiting.len() {
let entry = &self.waiting[index];
-- if entry.granted || !self.can_admit(&entry.request) {
++ if entry.granted
++ || !self.can_admit(&entry.request)
++ || !self.can_pass_waiters(&entry.request, index)
++ {
continue;
}
let request = entry.request.clone();
@@@ -258,6 -258,6 +337,38 @@@
entry.ready.notify_one();
}
}
++
++ fn can_pass_waiters(&self, request: &Request, before: usize) -> bool {
++ let Some(resources) = &request.resources else {
++ return true;
++ };
++ self.waiting.iter().take(before).all(|entry| {
++ entry.granted
++ || match &entry.request.resources {
++ Some(prior) => {
++ // An unready DAG successor cannot become a fairness
++ // barrier for another batch: that batch could otherwise
++ // block the successor's own predecessor and form a cycle.
++ if entry
++ .request
++ .ticket
++ .as_deref()
++ .is_some_and(|ticket| !self.batches.can_run(ticket, prior))
++ {
++ return true;
++ }
++ // Source-order predecessors must pass a later call that arrived
++ // first; otherwise RPC arrival fairness would deadlock the DAG.
++ let source_predecessor = match (&request.ticket, &entry.request.ticket) {
++ (Some(ours), Some(theirs)) => self.batches.precedes(ours, theirs),
++ _ => false,
++ };
++ source_predecessor || !resources.conflicts(prior)
++ }
++ None => true,
++ }
++ })
++ }
}
// Own the queue entry across every await. Cancellation may occur after
@@@ -284,6 -284,6 +395,8 @@@ impl QueueGuard
ToolPermit {
budget: self.budget.clone(),
request: entry.request,
++ wait_ms: entry.queued_at.elapsed().as_millis() as u64,
++ initial_wait_reason: entry.initial_wait_reason,
}
}
}
@@@ -327,6 -327,6 +440,72 @@@ impl ToolBudget
Self::default()
}
++ pub fn register_file_call(&self, call: BatchCall) -> Result<String, &'static str> {
++ self.lock().batches.register(call)
++ }
++
++ pub fn seal_file_batch(&self, batch: &str, session: &str) -> Result<(), &'static str> {
++ self.lock().batches.seal(batch, session)
++ }
++
++ pub fn close_file_batch(&self, batch: &str, session: &str) -> Result<(), &'static str> {
++ let mut state = self.lock();
++ state.batches.close(batch, session)?;
++ state.dispatch();
++ Ok(())
++ }
++
++ pub fn abandon_file_call(&self, ticket: &str, session: &str) -> Result<(), &'static str> {
++ let mut state = self.lock();
++ state.batches.abandon(ticket, session)?;
++ state.dispatch();
++ Ok(())
++ }
++
++ pub fn begin_file_call(
++ &self,
++ ticket: &str,
++ session: &str,
++ delegation: Option<&str>,
++ id: &str,
++ name: &str,
++ args: &serde_json::Value,
++ ) -> Result<PendingFileCall, &'static str> {
++ self.lock()
++ .batches
++ .begin(ticket, session, delegation, id, name, args)?;
++ Ok(PendingFileCall {
++ budget: self.clone(),
++ ticket: ticket.into(),
++ })
++ }
++
++ pub async fn acquire_files(
++ &self,
++ session: &str,
++ name: &str,
++ own_worktree: bool,
++ resources: Arc<FileResources>,
++ ticket: Option<String>,
++ ) -> Result<ToolPermit, AdmissionError> {
++ if let Some(ticket) = &ticket {
++ let mut state = self.lock();
++ state.batches.classify(ticket, resources.clone());
++ state.dispatch();
++ }
++ self.acquire_request(
++ Request {
++ session_id: session.into(),
++ class: ToolClass::from_name(name),
++ own_worktree,
++ resources: Some(resources),
++ ticket,
++ },
++ QUEUE_WAIT,
++ )
++ .await
++ }
++
fn lock(&self) -> MutexGuard<'_, BudgetState> {
// Only bounded in-memory bookkeeping runs under this synchronous lock.
// No filesystem operation, callback, or await is allowed here.
@@@ -366,15 -366,15 +545,27 @@@
session_id: session_id.to_string(),
class: ToolClass::from_name(tool_name),
own_worktree,
++ resources: None,
++ ticket: None,
};
++ self.acquire_request(request, wait).await
++ }
++
++ async fn acquire_request(
++ &self,
++ request: Request,
++ wait: Duration,
++ ) -> Result<ToolPermit, AdmissionError> {
let ready = Arc::new(Notify::new());
let guard = {
let mut state = self.lock();
-- if state.can_admit(&request) {
++ if state.can_admit(&request) && state.can_pass_waiters(&request, state.waiting.len()) {
state.reserve(&request);
return Ok(ToolPermit {
budget: self.clone(),
request,
++ wait_ms: 0,
++ initial_wait_reason: "none",
});
}
let queue_depth = state.queued + 1;
@@@ -384,11 -384,11 +575,14 @@@
let id = state.next_id;
state.next_id = state.next_id.wrapping_add(1);
state.queued += 1;
++ let initial_wait_reason = state.wait_reason(&request);
state.waiting.push_back(WaitingRequest {
id,
request,
ready: ready.clone(),
granted: false,
++ queued_at: Instant::now(),
++ initial_wait_reason,
});
QueueGuard {
budget: self.clone(),
diff --cc crates/host-core/src/tool_budget/file_tests.rs
index 000000000,000000000..b8652aa91
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/tool_budget/file_tests.rs
@@@ -1,0 -1,0 +1,201 @@@
++use super::*;
++use crate::file_batches::BatchCall;
++use crate::workspace::ContainedRoots;
++use serde_json::json;
++use std::future::{poll_fn, Future};
++use std::pin::Pin;
++use std::task::Poll;
++
++#[tokio::test]
++async fn unready_successor_cannot_form_a_fairness_cycle_through_another_batch() {
++ let budget = ToolBudget::new();
++ let a = call(0, "Read", "a");
++ let b = call(1, "Write", "a");
++ let ta = budget.register_file_call(a.clone()).unwrap();
++ let tb = budget.register_file_call(b.clone()).unwrap();
++ budget.seal_file_batch("batch", "s").unwrap();
++ let _later = budget
++ .begin_file_call(&tb, "s", None, "1", "Write", &b.args)
++ .unwrap();
++ let mut later =
++ Box::pin(budget.acquire_files("s", "Write", false, FileResources::fence(true), Some(tb)));
++ pending(later.as_mut()).await;
++ let external = budget
++ .acquire_files("external", "Write", false, FileResources::fence(true), None)
++ .await
++ .unwrap();
++ let _first = budget
++ .begin_file_call(&ta, "s", None, "0", "Read", &a.args)
++ .unwrap();
++ let mut first =
++ Box::pin(budget.acquire_files("s", "Read", false, FileResources::fence(false), Some(ta)));
++ pending(first.as_mut()).await;
++ drop(external);
++ drop(first.await.unwrap());
++ drop(later.await.unwrap());
++ budget.close_file_batch("batch", "s").unwrap();
++ assert_eq!(budget.snapshot().active, 0);
++}
++
++async fn pending<T>(future: Pin<&mut impl Future<Output = T>>) {
++ let mut future = future;
++ poll_fn(|cx| {
++ assert!(
++ future.as_mut().poll(cx).is_pending(),
++ "request overtook its resource/source-order predecessor"
++ );
++ Poll::Ready(())
++ })
++ .await;
++}
++
++fn call(index: u32, name: &str, path: &str) -> BatchCall {
++ BatchCall {
++ session_id: "s".into(),
++ delegation_id: None,
++ batch_id: "batch".into(),
++ ordinal: index,
++ tool_call_id: index.to_string(),
++ tool_name: name.into(),
++ args: json!({"path":path}),
++ }
++}
++
++#[tokio::test]
++async fn hard_link_source_order_survives_reversed_rpc_arrival_in_both_directions() {
++ for write_first in [false, true] {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("actual"), "before").unwrap();
++ std::fs::hard_link(dir.path().join("actual"), dir.path().join("alias")).unwrap();
++ let budget = ToolBudget::new();
++ let first = call(0, if write_first { "Write" } else { "Read" }, "alias");
++ let second = call(1, if write_first { "Read" } else { "Write" }, "actual");
++ let a = budget.register_file_call(first.clone()).unwrap();
++ let b = budget.register_file_call(second.clone()).unwrap();
++ budget.seal_file_batch("batch", "s").unwrap();
++ let _second = budget
++ .begin_file_call(&b, "s", None, "1", &second.tool_name, &second.args)
++ .unwrap();
++ let claims_b = FileResources::resolve(
++ Some(dir.path()),
++ &ContainedRoots::new(),
++ &second.tool_name,
++ &second.args,
++ false,
++ );
++ let mut later =
++ Box::pin(budget.acquire_files("s", &second.tool_name, false, claims_b, Some(b)));
++ pending(later.as_mut()).await;
++ assert_eq!(
++ budget.snapshot().active,
++ 0,
++ "waiting for an unknown predecessor must not occupy capacity"
++ );
++ let _first = budget
++ .begin_file_call(&a, "s", None, "0", &first.tool_name, &first.args)
++ .unwrap();
++ let claims_a = FileResources::resolve(
++ Some(dir.path()),
++ &ContainedRoots::new(),
++ &first.tool_name,
++ &first.args,
++ false,
++ );
++ let earlier = budget
++ .acquire_files("s", &first.tool_name, false, claims_a, Some(a))
++ .await
++ .unwrap();
++ pending(later.as_mut()).await;
++ drop(earlier);
++ let later = later.await.unwrap();
++ drop(later);
++ budget.close_file_batch("batch", "s").unwrap();
++ assert_eq!(budget.snapshot().active, 0);
++ assert_eq!(budget.snapshot().queued, 0);
++ }
++}
++
++#[tokio::test]
++async fn denied_predecessor_releases_later_call_without_consuming_capacity() {
++ let budget = ToolBudget::new();
++ let a = call(0, "Write", "a");
++ let b = call(1, "Read", "b");
++ let ta = budget.register_file_call(a.clone()).unwrap();
++ let tb = budget.register_file_call(b.clone()).unwrap();
++ budget.seal_file_batch("batch", "s").unwrap();
++ let approval = budget
++ .begin_file_call(&ta, "s", None, "0", "Write", &a.args)
++ .unwrap();
++ let _read = budget
++ .begin_file_call(&tb, "s", None, "1", "Read", &b.args)
++ .unwrap();
++ let mut read =
++ Box::pin(budget.acquire_files("s", "Read", false, FileResources::fence(false), Some(tb)));
++ pending(read.as_mut()).await;
++ assert_eq!(budget.snapshot().active, 0);
++ drop(approval); // Permission denial before any identity lookup/admission.
++ drop(read.await.unwrap());
++ budget.close_file_batch("batch", "s").unwrap();
++}
++
++#[tokio::test]
++async fn cross_session_aliases_conflict_but_independent_read_and_write_overlap() {
++ let dir = tempfile::tempdir().unwrap();
++ for name in ["a", "b"] {
++ std::fs::write(dir.path().join(name), name).unwrap();
++ }
++ std::fs::hard_link(dir.path().join("a"), dir.path().join("alias")).unwrap();
++ let resolve = |name, path| {
++ FileResources::resolve(
++ Some(dir.path()),
++ &ContainedRoots::new(),
++ name,
++ &json!({"path":path}),
++ false,
++ )
++ };
++ let budget = ToolBudget::new();
++ let read = budget
++ .acquire_files("parent", "Read", false, resolve("Read", "alias"), None)
++ .await
++ .unwrap();
++ let independent = budget
++ .acquire_files("child", "Write", true, resolve("Write", "b"), None)
++ .await
++ .unwrap();
++ let mut conflict = Box::pin(budget.acquire_files(
++ "other-session",
++ "Write",
++ false,
++ resolve("Write", "a"),
++ None,
++ ));
++ pending(conflict.as_mut()).await;
++ drop(independent);
++ pending(conflict.as_mut()).await;
++ drop(read);
++ drop(conflict.await.unwrap());
++ assert_eq!(budget.snapshot().active, 0);
++}
++
++#[tokio::test]
++async fn cancelled_queue_entries_release_resources_and_do_not_starve_writers() {
++ let budget = ToolBudget::new();
++ let read = budget
++ .acquire_files("r", "Read", false, FileResources::fence(false), None)
++ .await
++ .unwrap();
++ let mut writer =
++ Box::pin(budget.acquire_files("w", "Write", false, FileResources::fence(true), None));
++ pending(writer.as_mut()).await;
++ let mut later_read =
++ Box::pin(budget.acquire_files("later", "Read", false, FileResources::fence(false), None));
++ pending(later_read.as_mut()).await;
++ drop(read);
++ // Writer was granted before its waiter consumed the permit. Cancelling at
++ // exactly this point must undo both capacity and its resource reservation.
++ drop(writer);
++ drop(later_read.await.unwrap());
++ assert_eq!(budget.snapshot().active, 0);
++ assert_eq!(budget.snapshot().queued, 0);
++}
diff --cc crates/host-core/src/tools/file_lease_tests.rs
index 000000000,000000000..aa6c4a3fa
new file mode 100644
--- /dev/null
+++ b/crates/host-core/src/tools/file_lease_tests.rs
@@@ -1,0 -1,0 +1,103 @@@
++//! Deterministic gate at the real blocking-pool boundary, keyed by test workspace.
++use super::*;
++use std::collections::HashMap;
++use std::future::{poll_fn, Future};
++use std::sync::{Mutex as StdMutex, OnceLock};
++use std::task::Poll;
++
++struct Gate {
++ entered: StdMutex<Option<tokio::sync::oneshot::Sender<()>>>,
++ leave: StdMutex<std::sync::mpsc::Receiver<()>>,
++}
++static GATES: OnceLock<StdMutex<HashMap<PathBuf, Arc<Gate>>>> = OnceLock::new();
++
++pub(super) fn pause(root: Option<&Path>) {
++ let Some(gates) = GATES.get() else { return };
++ let gate = gates
++ .lock()
++ .unwrap()
++ .get(root.unwrap_or(Path::new("")))
++ .cloned();
++ if let Some(gate) = gate {
++ if let Some(entered) = gate.entered.lock().unwrap().take() {
++ let _ = entered.send(());
++ }
++ // The sender is test-owned: a panic drops it and unblocks the worker.
++ let _ = gate.leave.lock().unwrap().recv();
++ }
++}
++
++#[tokio::test]
++async fn cancelling_transport_waiter_does_not_release_a_running_blocking_read_lease() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("actual"), "before").unwrap();
++ std::fs::hard_link(dir.path().join("actual"), dir.path().join("alias")).unwrap();
++ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
++ let (leave_tx, leave_rx) = std::sync::mpsc::channel();
++ GATES.get_or_init(Default::default).lock().unwrap().insert(
++ dir.path().to_owned(),
++ Arc::new(Gate {
++ entered: StdMutex::new(Some(entered_tx)),
++ leave: StdMutex::new(leave_rx),
++ }),
++ );
++ let budget = crate::tool_budget::ToolBudget::new();
++ let roots = ContainedRoots::new();
++ let args = json!({"path":"alias"});
++ let resources = crate::file_resources::FileResources::resolve(
++ Some(dir.path()),
++ &roots,
++ "Read",
++ &args,
++ false,
++ );
++ let permit = Arc::new(
++ budget
++ .acquire_files("s", "Read", false, resources.clone(), None)
++ .await
++ .unwrap(),
++ );
++ let mut execution = Box::pin(execute_tool_with_file_lease(
++ Some(dir.path()),
++ None,
++ "Read",
++ &args,
++ ToolExecutionOptions {
++ timeout_ms: None,
++ bash_options: None,
++ allow_external_paths: false,
++ hashline: None,
++ visualization_root: None,
++ },
++ Some(permit),
++ Some(resources),
++ ));
++ poll_fn(|cx| {
++ assert!(execution.as_mut().poll(cx).is_pending());
++ Poll::Ready(())
++ })
++ .await;
++ entered_rx.await.unwrap();
++ drop(execution); // Equivalent to the RPC select cancelling its outer future.
++ let write_resources = crate::file_resources::FileResources::resolve(
++ Some(dir.path()),
++ &roots,
++ "Write",
++ &json!({"path":"actual"}),
++ false,
++ );
++ let mut write = Box::pin(budget.acquire_files("other", "Write", false, write_resources, None));
++ poll_fn(|cx| {
++ assert!(
++ write.as_mut().poll(cx).is_pending(),
++ "read lease was released before disk work ended"
++ );
++ Poll::Ready(())
++ })
++ .await;
++ assert_eq!(budget.snapshot().active, 1);
++ leave_tx.send(()).unwrap();
++ drop(write.await.unwrap());
++ assert_eq!(budget.snapshot().active, 0);
++ GATES.get().unwrap().lock().unwrap().remove(dir.path());
++}
diff --cc crates/host-core/src/tools/mod.rs
index d77f9760a,d77f9760a..271c7b0b3
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@@ -23,6 -23,6 +23,8 @@@ use crate::workspace::
resolve_tool_path_with_external, simple_canonicalize, ContainedRoots, ToolRoot,
};
++#[cfg(test)]
++mod file_lease_tests;
mod grep_rg;
pub mod hashline;
pub mod ignore_rules;
@@@ -647,6 -647,6 +649,9 @@@ pub struct ToolsExecuteParams
pub tool_call_id: String,
pub tool_name: String,
pub args: Value,
++ /// Host-issued source-order binding, not a permission or resource claim.
++ #[serde(default)]
++ pub file_batch_ticket: Option<String>,
#[serde(rename = "mode")]
pub _mode: String,
#[serde(default)]
@@@ -1155,6 -1155,6 +1160,10 @@@ async fn run_file_tool
args: &Value,
allow_external_paths: bool,
hashline: Option<&HashlineContext<'_>>,
++ lease: Option<(
++ Arc<crate::tool_budget::ToolPermit>,
++ Arc<crate::file_resources::FileResources>,
++ )>,
) -> Result<Value, hashline::ToolError> {
let workspace = workspace.map(Path::to_path_buf);
let tool_name = tool_name.to_string();
@@@ -1163,6 -1163,6 +1172,22 @@@
#[cfg(test)]
let test_rg = grep_rg::current_test_rg();
tokio::task::spawn_blocking(move || {
++ // Dropping the transport future does not stop this closure. It must
++ // retain the lease until the actual filesystem body has returned.
++ let _file_lease = lease;
++ #[cfg(test)]
++ file_lease_tests::pause(workspace.as_deref());
++ if let Some((_, resources)) = &_file_lease {
++ resources
++ .validate(
++ workspace.as_deref(),
++ &roots,
++ &tool_name,
++ &args,
++ allow_external_paths,
++ )
++ .map_err(|e| hashline::ToolError::new("TOOL_FAILED", e))?;
++ }
// The test rg override is thread-local; carry it onto the blocking
// thread for the duration of the body.
#[cfg(test)]
@@@ -1197,6 -1197,6 +1222,18 @@@ pub async fn execute_tool_with_path_acc
tool_name: &str,
args: &Value,
options: ToolExecutionOptions<'_>,
++) -> ToolsExecuteResult {
++ execute_tool_with_file_lease(workspace, scratch, tool_name, args, options, None, None).await
++}
++
++pub async fn execute_tool_with_file_lease(
++ workspace: Option<&Path>,
++ scratch: Option<&Path>,
++ tool_name: &str,
++ args: &Value,
++ options: ToolExecutionOptions<'_>,
++ file_lease: Option<Arc<crate::tool_budget::ToolPermit>>,
++ resources: Option<Arc<crate::file_resources::FileResources>>,
) -> ToolsExecuteResult {
let ToolExecutionOptions {
timeout_ms: requested_timeout_ms,
@@@ -1250,6 -1250,6 +1287,7 @@@
args,
allow_external_paths,
hashline.as_ref(),
++ file_lease.zip(resources),
)
.await
}
diff --cc docs/adr/0062-bounded-subagents-behind-a-task-tool.md
index c30569638,cc34ecfd1..7d5547c05
--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
@@@ -85,12 -85,10 +85,16 @@@ must never silently spend the expensiv
### 4. Delegation is one Agent-mode tool, and parallel by construction
-Proposed amendment: [parallel read batches](parallel-read-batches.md) allows
-Read/Glob/Grep candidates, isolates delegate path-instruction preparation, and
-keeps Task mixed with those reads behind the delegate completion boundary. The
-original only-Task batch policy below is historical.
+Proposed amendment: [parallel file batches](parallel-read-batches.md) allows
+Read/Glob/Grep/Write/Edit candidates, isolates delegate path-instruction
+preparation, keeps a batch that mixes Task with those file tools sequential, and
+holds a read or search ordered after a writable Task behind the delegate
+completion boundary. The
- original only-Task batch policy below is historical.
++original only-Task batch policy below is historical. The
++[Host file admission amendment](host-file-batch-admission.md) replaces lexical
++file coordination on supported local Hosts, including delegate calls; legacy
++Hosts retain sequential writes and the original sidecar lock. Write quotas and
++Task's background contract are unchanged.
The `Task` tool takes `agent`, `task` and an optional short `description`. The
catalog of available delegates rides in the tool description rather than the
diff --cc docs/adr/README.md
index ae251122d,dbcb2b26e..07ca0ca51
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@@ -31,7 -32,7 +32,8 @@@ Each ADR includes
| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 |
| remote-provider-import | [Explicit provider import into a running remote Host](remote-provider-import.md) | Accepted for the experimental SSH MVP |
| remote-project-home-workflow | [Remote projects in the shared Chat home workflow](remote-project-home-workflow.md) | Accepted |
-| parallel-read-batches | [Ordered preparation and parallel read batches](parallel-read-batches.md) | Proposed |
+| parallel-read-batches | [Ordered preparation and parallel file batches](parallel-read-batches.md) | Proposed |
++| host-file-batch-admission | [Host file identities and ordered batch admission](host-file-batch-admission.md) | Proposed |
| composer-mcp-invocations | [Composer MCP Invocations](composer-mcp-invocations.md) | Accepted |
| chronological-system-transcript | [Preserve chronological model system state](chronological-system-transcript.md) | Accepted |
| mcp-tool-approval-risk | [User MCP tools keep the normal approval path](mcp-tool-approval-risk.md) | Accepted |
diff --cc docs/adr/host-file-batch-admission.md
index 000000000,000000000..604a6007c
new file mode 100644
--- /dev/null
+++ b/docs/adr/host-file-batch-admission.md
@@@ -1,0 -1,0 +1,97 @@@
++# ADR: Host file identities and ordered batch admission
++
++- Status: Proposed
++- Date: 2026-10-30
++- Related: #1982, #1908, ADR 0062, ADR 0329, parallel-read-batches
++
++## Context
++
++The first #1982 candidate classified file conflicts using lexical path keys and
++a basename fallback. A differently named symbolic link or hard link bypasses
++that rule. Sidecar PathMutex uses lexical keys too; Host's per-session mutation
++cap excludes a second write, not a concurrent read. Independent-path read/write
++parallelism therefore needs trusted resource identity before it can be safe.
++
++The executor must also preserve the assistant's source order. Locking only on
++RPC arrival can let a later approved call run before an earlier pending one.
++File bodies use spawn_blocking, so cancelling the transport waiter is not proof
++that disk work has stopped. Review snapshots and rollback are filesystem work,
++not separate exceptions to the exclusion rule.
++
++## Decision
++
++Host owns resource classification and admission. Runtime registers only logical
++calls in pi's ordered prepare phase and seals the batch before dispatch. The
++five version-1 internal methods are tools.fileBatchCapabilities, Register,
++Seal, Abandon and Close (each with the full tools.fileBatch prefix). A ticket
++binds session, optional delegation, batch/ordinal, tool call/name and normalized
++arguments. It is single-use and is not an access permission. Registration does
++no file lookup and takes no execution capacity. Unstarted failed calls are
++abandoned and turn-end closes metadata; running work cannot be released by
++close or by metadata expiry.
++
++Host applies existing permissions before classification. Unknown earlier calls
++conservatively block potentially conflicting same-batch successors. Approved
++calls use native object IDs from pinned handles, plus resolved path addresses.
++Equal IDs conflict across roots; roots are not namespaces for physical IDs.
++Windows uses local-disk volume/FILE_ID_INFO; supported Unix local filesystems use
++dev/ino. Missing/unknown targets, structural edits and named registers use a
++Host-wide file-domain fence. Searches use that domain shared. Permission and
++I/O failures still fail in their original execution path; unknown identity is
++never used as evidence of independence.
++
++ToolBudget checks batch predecessors, active resources, conflicting waiters and
++capacity in one synchronous reservation. No capacity is held while awaiting a
++resource. Source predecessors may bypass a later same-batch RPC-arrival waiter;
++otherwise a reversed arrival could deadlock. Conflicting later shared requests
++do not bypass an exclusive waiter. Existing capacity limits and 30-second
++HOST_OVERLOADED behavior stay unchanged. Local diagnostics report total
++admission wait and the initial reason, not invented non-overlapping timings.
++
++After admission, the persisted workspace binding and resource identity/address
++are revalidated before snapshots and again in the blocking body. A changed
++binding fails before mutation without replay. The actual blocking task retains
++an Arc of the execution permit even if its RPC future is cancelled. Snapshot,
++execution, Hashline updates and review finalization share the lease; rollback
++also joins the domain without holding AppState while waiting.
++
++On the negotiated path Host resources replace sidecar PathMutex around file
++execution, avoiding a second lock-order authority. Legacy calls retain the old
++sidecar policy; calls without tickets still take Host resource leases but lack
++batch source-order metadata. The capability is stable for a runtime/connection
++so a later parent prompt cannot switch a live delegate's lock protocol.
++Tickets travel in AsyncLocalStorage, not a shared provider-call-ID map.
++
++Remote workspaces do not yet expose this execution-end protocol. They and old
++Hosts retain sequential write batches; the desktop never stats a remote path
++locally. Bash, Task's delegation lifecycle, plugin/MCP policy, write quotas and
++persistence formats are unchanged. Coordination covers participating file
++tools and rollback in one Host process, not arbitrary external writers, shell
++processes or other Host instances. It is not OS-wide transaction isolation or a
++new defense against malicious external path replacement.
++
++## Alternatives
++
++- Realpath/basename only: misses hard links and unknown filesystem identities.
++- Return an identity token and keep arrival-order admission: loses source order
++ when approvals/RPCs arrive in another order; stale identities can also escape.
++- Keep every write as a batch-local full barrier: safe fallback, but discards
++ independent-file read/write overlap even on a capable local Host.
++- Reimplement pi execution: duplicates its ordered preparation/result contract.
++- Adopt the whole #1908 roadmap: unrelated quota, background-job and MCP changes
++ are not required to repair the current concurrency boundary.
++
++## Consequences and verification
++
++This is a cross-runtime/Host protocol amendment, not a TS-only optimization.
++It adds bounded process-local metadata and registration/sealing overhead, which
++must be included in performance measurements. It does not raise per-session
++write throughput: one mutation per session still applies. Registry bounds and
++unknown identities may reject/degrade work conservatively.
++
++Regression evidence must cover actual differently named links in both orders,
++reversed RPC/approval arrival, parent/delegate wiring, cross-session aliases,
++independent resources, cancellation during blocking work, queue cleanup,
++permission denial, argument tampering/replay, review rollback and legacy remote
++fallback. Diagrams and source inspection are not substitutes for execution.
++See E2E-TOOLS-parallel-read-batches and the corresponding Rust/runtime tests.
diff --cc docs/adr/parallel-read-batches.md
index f6eedf9e0,66762cb4f..f3ff13889
--- a/docs/adr/parallel-read-batches.md
+++ b/docs/adr/parallel-read-batches.md
@@@ -2,89 -2,54 +2,58 @@@
- Status: Proposed
- Date: 2026-10-12
- - Amended: 2026-10-29 by #1982 (Write/Edit join parallel batches, ordered by
- resource claims)
++- Amended: 2026-10-30 by #1982; see [Host file admission](host-file-batch-admission.md)
## Context
--The runtime globally permits parallel execution but overrides every tool except
--Task to sequential. pi consequently serializes independent Read/Glob/Grep calls.
--Simply changing those flags is unsafe: file preflight currently changes the
--parent prompt, including when invoked through delegated tool closures.
++Independent Read/Glob/Grep calls were serialized. Simply changing execution
++flags was unsafe because preflight mutated the prompt in completion order and
++Task could start a writable delegate beside a parent read. The initial #1982
++amendment later tried lexical-path claims for Write/Edit; review demonstrated
++that different file names can reference the same object.
## Decision
--Use pi-agent-core's ordered preparation / concurrent execution /
--ordered result submission contract. Centralize the Read/Glob/Grep candidate
--allowlist and the batch rule that keeps Task mixed with those reads sequential;
--unknown tools default to sequential. Keep existing Host permission and capacity
--ownership. Do not introduce another batch executor.
-
- Amendment (2026-10-28): Write and Edit join the candidates. The allowlist
- becomes one execution spec table in `tool-execution-policy.ts`: each candidate
- declares its pi mode and, for file tools, the resources one call claims (a
- shared or exclusive claim on a lexical path key or on the whole workspace). A
- batch-local planner orders a parallel batch by those claims: each call waits
- only for earlier calls of the same assistant message whose claims conflict.
- Claims are registered at the end of the runtime's `beforeToolCall`; waiting and
- releasing wrap the catalog executor outside the mode guard and every argument
- check (a delegate's scoping wrapper calls that same executor), so a call that
- throws, is rejected or aborts still releases its successors. A Task mixed
- with any file tool, including Write and Edit, keeps the whole batch sequential.
- Host-core, `PathMutex`, Bash/Task semantics and the delegate completion barrier
- for reads are unchanged.
--
--Move parent file preflight after mode and extension checks in beforeToolCall.
--Use a weak argument-identity map to bind canonical parameters to the validated
--call; unused records are collectible after cancellation or rejection. Direct
--invocations still run preflight. Delegate preparation has an explicit prompt
--sink, and AsyncLocalStorage preserves that sink for direct delegated executions
--without sharing mutable current-agent state. Delegate prompt updates use the
--same chronological system transcript sections as the parent.
++Use pi-agent-core's ordered preparation, concurrent execution and source-order
++result submission contract. Native path instruction preparation follows parent
++mode/extension checks; children only mutate their own prompt. Prepared argument
++identity keeps execution on the same normalized parameters. Direct calls retain
++preflight. Do not fork pi or add another executor.
++
++Read/Glob/Grep remain parallel candidates. A supported local Host allows
++Write/Edit to join; legacy and remote Hosts retain sequential writes. Task-only
++fan-out is preserved; Task mixed with any file tool keeps the entire batch
++sequential. Reads/searches after a writable Task still wait for that delegate's
++completion; Task itself returns its started notice immediately.
++
++Eligible parallel file calls register in source order, seal before dispatch,
++and carry Host tickets. The Host owns actual identity, conflicts, capacity and
++execution lease lifetime as specified in the companion ADR. Basename and
++lexical keys no longer authorize overlap. Outer executor cleanup includes
++argument failures, mode denials, cancellation and calls that never reach Host.
++Batch-end cleanup only abandons unstarted records, never active disk work.
## Consequences
--Independent reads/searches overlap without changing writes or Bash policy.
--Task-only batches retain fan-out, while a mixed Task/read batch is kept
--sequential: a read ordered before `Task` finishes before the delegate starts, and
--a read ordered after a writable `Task` in the same batch waits for that delegate
--to settle before dispatching to Host, while `Task` itself still returns its ADR
--0089 started notice immediately. Per-path shared-read / exclusive-write
--locking in `PathMutex` also prevents a parent `Read` from overlapping an
--in-flight shared-workspace delegate `Write` or `Edit` on the same file.
--Regression tests pin both model orders (read then `Task`, and `Task` then read),
--Task-only fan-out, read-only batches, same-path `Edit` vs `Read` serialization,
--and a failed delegate that still lets the parent read proceed. Delegate path
--rules now follow their own ordered calls instead of mutating the parent.
--Instruction resolution claims remain immutable, per-prompt cached promises;
--shared caching does not share the prompt mutation sink. Source-order results
--still come from pi.
--
--Existing running file RPCs drain on Stop; finer cancellation and Host-owned
--file resource leases belong to separate changes.
-
- With the amendment, a read and an unrelated write in one batch overlap, and
- same-file work keeps source order (for example `[Read a, Edit a, Read b, Write
- c]` holds only Edit a behind Read a). The rules are conservative: Glob and Grep
- claim the whole workspace, so they keep source order against every write in the
- batch; an Edit with `MV`, `REM` or a named `@register` (kept per session by
- host-core) claims the whole workspace exclusively; two
- paths with the same file name are treated as one file, because host-core writes
- are not atomic and a lexical key cannot see every alias. Host still admits one
- mutation per session, so several non-conflicting writes of one batch queue in
- Host, may run out of source order and are subject to its 30-second admission
- timeout; results still reach the model in source order. Bash, TodoWrite,
- plugin/MCP and unknown tools keep their batch sequential. A Rust-side mirror of
- the claim table and Host resource leases are deferred to the Host change that
- would consume them.
++Independent known-file reads and writes may overlap while aliases keep source
++order. Uncertain paths, namespace changes, searches and registers conservatively
++coordinate through the Host file domain. Per-session write capacity remains
++one. Results still enter the model in source order. Task/Bash semantics and
++permissions are unchanged. Legacy PathMutex behavior remains only on the legacy
++path; the negotiated path uses the Host authority for participating parent,
++delegate and session calls.
++
++Regression tests must distinguish RPC submission from actual file-body order.
++Real Host tests cover differently named links and reversed RPC arrival; a
++blocking-pool gate proves cancellation cannot release a running file lease.
++Local-provider E2E covers parent/delegate wiring, results, real-tag Edit,
++approvals, aliases and rollback. Performance measurements include metadata RPCs
++and do not claim the diagram's illustrative timings as observed throughput.
## Alternatives
--- Parallelize execute while retaining prompt updates there: completion order
-- would select sibling rules and delegates would still overwrite parent state.
--- Serialize all reads behind a prompt mutex: would preserve the bottleneck.
--- Fork pi's batch executor: duplicates an already-supported contract.
- - Keep Write/Edit sequential and rely on `PathMutex`: any write still
- serializes its whole batch, including unrelated reads.
- - Wait and release inside the builtin executor: argument validation and the
- mode guard can fail before that code runs, leaving successors waiting forever.
++- Completion-order preflight: sibling calls race to choose prompt instructions.
++- Sidecar lexical locks: miss aliases and other sessions.
++- Write-only Host capacity: does not exclude a read of the same file.
++- Waiting/releasing only inside the builtin body: validation/mode errors can
++ strand registered successors before reaching that body.
diff --cc docs/spec/03-runtime/02-agent-runtime.md
index 83bbccf1a,a32bec52f..f5304b1fe
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@@ -1784,26 -1794,23 +1794,20 @@@ merging to the user, and how to resolv
| tools | sequential by default |
| `Task` calls in one assistant message | parallel; 10 running delegates per session (ADR 0089) |
- Tool concurrency is expressed through pi execution modes. In parallel file
- batches, `Read`, `Glob`, `Grep`, `Write` and `Edit` are parallel candidates; all
- other catalog tools remain sequential. Inside a parallel batch a call waits only
- for earlier calls of the same assistant message whose resource claims conflict
- (`03-tools-and-permissions.md` §0, "Parallel file batches"). Task-only batches
- retain parallel fan-out, while a batch that mixes `Task` with any of those file
- tools is kept sequential: a file call before `Task` finishes before the delegate
- starts, and a read or search after a writable `Task` waits for that delegate to
- settle before dispatching to Host, while `Task` stays non-blocking inside that
- batch too (ADR 0089). Parent and delegate path
-Tool concurrency is expressed through pi execution modes. In the parallel read batches,
-`Read`, `Glob` and `Grep` are parallel candidates; all other catalog tools remain
-sequential. Task-only batches retain parallel fan-out, while a batch that mixes
-`Task` with any of those file-reading tools is kept sequential: a read before
-`Task` finishes before the delegate starts, and a read after a writable `Task`
-waits for that delegate to settle before dispatching to Host, while `Task` stays
-non-blocking inside that batch too (ADR 0089). Parent and delegate path
--instruction updates happen during ordered preparation before parallel execution,
--and mutate only their own prompt.
--Delegates issue
--host calls independently, and host-core's one-mutation-per-session admission
--keeps writes from tearing but leaves two same-path mutations unordered, so the
--sidecar serializes `Write`/`Edit` calls (and coordinates `Read` against in-flight
--`Write`/`Edit` on the same workspace path) that target the same normalized path
--before they reach the host; calls on different paths never wait on each other.
--This is what keeps the per-path edit-recovery rules of
--`03-tools-and-permissions.md` §4d meaningful under fan-out.
++Tool concurrency uses pi's ordered preparation and source-order result contract.
++Read/Glob/Grep remain parallel; Write/Edit join only after the local Host
++file-batch capability handshake. Legacy and remote Hosts keep write batches
++sequential. Eligible batches register calls in source order and seal before
++execution. Host permission checks precede identity resolution; Host orders
++conflicting same-batch calls by source ordinal and atomically grants resources
++with capacity. Native file identities cover aliases across parent/delegate and
++session calls. Unknown identities and namespace changes fence conservatively.
++The actual blocking task retains its permit after transport cancellation.
++Supported calls bypass sidecar PathMutex; legacy calls retain it. Existing
++mutation-recovery rules remain in force. See `03-tools-and-permissions.md` §0
++and ADR `host-file-batch-admission` for identity, lifecycle and scope limits.
++Task-only fan-out and Task/file mixed-batch completion barriers are unchanged;
++parent and child path instruction preparation only updates their own prompt.
Selecting another project tab affects only the visible shell workspace. It
does not dispose, abort, or re-root a runtime belonging to another session.
diff --cc docs/spec/03-runtime/03-tools-and-permissions.md
index 820179db4,42fe8271c..eb988f726
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@@ -5,87 -5,39 +5,94 @@@
## 0. Frozen policy summary
-### Parallel read batches
-
-Read, Glob and Grep are the first parallel batch candidates. Task-only batches
-retain their existing parallel fan-out; a batch that mixes Task with Read, Glob
-or Grep is kept sequential: a read ordered before Task finishes before the
-delegate starts, and a read ordered after a writable Task waits for that
-delegate to settle before dispatching to Host. Task keeps its ADR 0089 contract
-inside that batch: it reports a started delegation and the parent converges with
-TaskWait. Any other sequential tool (including Write, Edit, Bash and unknown
-tools) makes its entire assistant batch sequential. This is a per-agent batch
-rule, not application-wide exclusion or a Shell safety lock. Only the selected
-builtin executor receives this allowlist and native path preparation. Same-name
-dynamic tools remain sequential. Delegates retain their startup catalog's policy
-and provenance across later parent catalog rebuilds.
-
-The pinned pi-agent-core prepares all parallel calls in source order before
-launching their execution bodies. Path instruction resolution and prompt updates
-occur during that preparation, after existing parent mode/extension checks.
-Execution consumes the same normalized arguments. Direct internal invocations
-retain preflight. Child preflight updates the child's system transcript only;
-it never replaces parent instructions. Sibling instruction chains replace one
-another according to preparation order, regardless of completion order.
-
-Permissions, Host capacities, mutation recovery, Hashline validation and tool
-result IDs remain authoritative. Completion events may arrive out of order;
-model tool results remain in source order. Alongside the mixed Task/read batch
-barrier, `PathMutex` coordinates shared reads against exclusive `Write`/`Edit`
-calls on the same normalized workspace path so a parent `Read` does not overlap
-an in-flight delegate mutation on that file. Stop skips unstarted calls; already
-started file RPCs drain through their existing Host lifecycle. Host file
-cancellation and resource coordination are separate follow-up work.
-
-See [the ADR](../../adr/parallel-read-batches.md).
+### Parallel file batches
+
- Read, Glob, Grep, Write and Edit are parallel batch candidates. Task-only
- batches retain their existing parallel fan-out; a batch that mixes Task with
- Read, Glob, Grep, Write or Edit is kept sequential: a file call ordered before
- Task finishes before the delegate starts, and a Read, Glob or Grep ordered after
- a writable Task waits for that delegate to settle before dispatching to Host. A
- Write or Edit ordered after Task only runs after the Task call returns; it does
- not wait for the delegate to settle. Task keeps its ADR 0089 contract inside
- that batch: it reports a started delegation and the parent converges with
- TaskWait. Any other sequential tool (including Bash, TodoWrite, plugin/MCP and
- unknown tools) makes its entire assistant batch sequential. This is a per-agent
- batch rule, not application-wide exclusion or a Shell safety lock. Only the
- selected builtin executor receives this allowlist, native path preparation and
- resource claims. Same-name dynamic tools remain sequential. Delegates retain
- their startup catalog's policy and provenance across later parent catalog
- rebuilds.
++Read, Glob and Grep are parallel candidates. Write and Edit join them only
++when the runtime negotiates version 1 of the actual local Host file-batch
++protocol. Capability is fixed for that runtime/connection, including background
++delegates. Legacy Hosts and remote workspaces retain Write/Edit as sequential,
++so pi serializes any batch containing a write. No sidecar filesystem lookup is
++used to classify a remote path.
+
- Inside a parallel batch, calls are ordered by the resources they claim. Each
- builtin file call records its claims at the end of the runtime's
- `beforeToolCall` preparation, after every runtime check that can block it. At
- execution it waits only for earlier calls of the same assistant message whose
- claims conflict; the batch does not hold back any other call.
++Task-only fan-out is unchanged. Task mixed with any file tool remains a whole-
++batch sequential boundary. Reads/searches ordered after a writable Task wait
++for the delegate to settle; writes only wait for the Task call to return its
++started notice. Bash, TodoWrite, unknown, plugin and MCP tools keep their
++existing sequential policy. Only the selected builtin executor receives native
++preparation and file-batch bindings; same-name dynamic tools remain sequential.
+
- | Tool | Claim |
- |---|---|
- | Read | shared on its `path`; shared on the whole workspace without a `path` |
- | Glob, Grep | shared on the whole workspace |
- | Write | exclusive on its `path`; exclusive on the whole workspace without a `path` |
- | Edit | exclusive on its `path`; exclusive on the whole workspace when an `ops` line starts (after optional whitespace) with `MV` or `REM`, when a `CUT` or `PUT` header names an `@register`, or without a `path` |
++For an eligible parallel batch, preparation validates arguments and loads path
++instructions in source order, then registers each file call with Host. A record
++contains session/delegation, a fresh batch ID, the original ordinal, tool call
++ID, tool name and normalized arguments. Host returns an opaque, single-use
++ticket. Registration performs no file lookup, grants no permission and takes
++no execution capacity. After preparation finishes, executors share one batch
++seal operation before submitting `tools.execute` with their ticket. Sequential
++batches do not register a partial batch. Tickets are bound to the exact call;
++changed arguments, cross-owner use, replay and execution before sealing fail.
++They are carried in asynchronous execution context, not a global call-ID map,
++so independent delegates cannot overwrite each other's bindings.
++
++Host first applies the existing mode and permission checks. Only approved calls
++resolve trusted file resources through the session/delegation tool root and
++existing external-path resolver. A pending approval holds neither an active
++lease nor capacity. Until a potentially conflicting earlier call is classified
++or terminal, a later same-batch call waits conservatively. Once both identities
++are known, only conflicting predecessors enforce source order; predecessor
++failure or denial does not cascade. There is no model source order across
++independent batches/sessions, only active resource exclusion and queue fairness.
+
- Two shared claims never conflict. Any exclusive claim conflicts with a
- whole-workspace claim and with a path claim on the same file. So Glob and Grep
- keep source order against every Write and Edit in the batch, and an Edit with
- `MV`, `REM` or a named register keeps source order against every other file call
- in the batch. Named registers are kept per session by host-core, so a `CUT @x`
- and a later `PUT @x` on another file must not reorder.
- For example, `[Read a, Edit a, Read b, Write c]` starts Read a, Read b and
- Write c together, and Edit a starts after Read a ends.
++| Tool / target | Host resource declaration |
++|---|---|
++| Existing regular-file Read | shared object identity and resolved address |
++| Existing regular-file Write / ordinary Edit | exclusive object identity and resolved address |
++| Glob / Grep | shared across the Host file coordination domain |
++| Missing target, unknown identity, unsupported filesystem | shared domain for a read; exclusive domain for a write |
++| Edit MV / REM or a named CUT/PUT register | exclusive domain |
++| Review rollback | exclusive domain, with the existing post-tool hash guard |
+
- Path keys are lexical and never touch the filesystem: backslashes become `/`,
- a relative path is joined to the session's workspace root (the project path
- unless the session is isolated), `.` and `..` segments collapse, a trailing
- `/` is dropped and the key is lowercased. Two keys also name the same file when
- their file names match: this basename fallback is deliberately conservative,
- because aliases a lexical key cannot see (symbolic links, a delegate's worktree
- spelling) would otherwise overlap a read with a non-atomic Host write.
- Same-named files in different directories only lose overlap.
++Unix identities use dev/ino from an open file on a supported local filesystem;
++Windows uses volume serial plus FILE_ID_INFO on a local disk. The handle stays
++alive while the identity is queued or active. Hard links and symbolic links
++must conflict even with different basenames or roots. Roots determine permission
++and address resolution, not separate namespaces for physical file IDs. File
++names, file size, lexical keys and realpath alone cannot prove independence.
++The global domain includes approved external paths. Two shared declarations do
++not conflict. A domain declaration conflicts with every exclusive declaration;
++otherwise equal object identities or resolved addresses conflict when either
++side is exclusive. Unknown identity never falls back to presumed independence.
+
- A call that fails, is rejected (for example by the mode guard after a
- mid-turn mode switch) or is aborted still releases the calls ordered behind it;
- failure does not cascade. A call still waiting for its turn when the user stops
- fails with `TOOL_ABORTED` before reaching Host. Claims order calls only inside
- one assistant message; they are not a cross-agent lock.
++ToolBudget grants all resources and execution capacity together. Waiting for a
++predecessor/resource does not occupy a capacity slot. Later conflicting calls
++cannot bypass an exclusive resource waiter; an earlier source-order call can
++bypass a later waiter from its own batch to avoid a queue/DAG deadlock. Existing
++limits remain: 16 total, 8 reads, 2 writes, 4 per session, 1 write per session.
++The bounded admission wait still returns HOST_OVERLOADED after 30 seconds.
++Audit/debug diagnostics record total admission wait and its initial reason
++(source_order, resource or capacity); these are not disjoint duration segments.
+
- The pinned pi-agent-core prepares all parallel calls in source order before
- launching their execution bodies. Path instruction resolution and prompt updates
- occur during that preparation, after existing parent mode/extension checks.
- Execution consumes the same normalized arguments. Direct internal invocations
- retain preflight and are not ordered by claims. Child preflight updates the
- child's system transcript only; it never replaces parent instructions. Sibling
- instruction chains replace one another according to preparation order,
- regardless of completion order.
++Identity/address is revalidated under the granted lease before review snapshots
++and in the actual blocking file task. A changed binding fails without writing
++or automatic replay. Namespace changes and missing-target writes use an
++exclusive domain fence. Snapshot, execution, Hashline state and final review
++snapshot share the lease; later rollback also acquires it without holding the
++AppState mutex while waiting. Cancelling an RPC future does not stop
++spawn_blocking: the blocking task retains the permit until its body ends.
++Unstarted calls are abandoned; a batch close cannot release active disk work.
++Registry limits are 512 calls globally, 128 per batch and 32 MiB of retained
++arguments. Unused metadata expires after 15 minutes; submitted/running calls
++are not expired through a pending permission decision or disk operation.
+
- Permissions, Host capacities, mutation recovery, Hashline validation and tool
- result IDs remain authoritative. Host still admits one mutation per session at
- a time, so non-conflicting Writes and Edits of one batch queue in Host and may
- run in a different order than the model wrote them; a call that waits in that
- queue longer than the Host's 30-second admission timeout fails with
- `HOST_OVERLOADED`.
- Permission approval happens before admission, so several same-batch calls can
- await approval together and each decision applies only to its own call.
- Completion events may arrive out of order; model tool results remain in source
- order. Alongside the mixed Task batch barrier, `PathMutex` coordinates shared
- reads against exclusive `Write`/`Edit` calls on the same normalized workspace
- path across the parent and its delegates, so a parent `Read` does not overlap an
- in-flight delegate mutation on that file. Stop skips unstarted calls; already
- started file RPCs drain through their existing Host lifecycle. Host file
- cancellation and resource coordination are separate follow-up work.
++Host resources replace sidecar PathMutex around calls on the supported path;
++the legacy path retains its original locking. Existing permission, Hashline,
++mutation-recovery and model result semantics remain in force. Parent/delegate
++path instructions still mutate only their own prompt. pi submits tool results
++in source order, irrespective of completion order. The guarantee covers file
++tools and rollback coordinated by one Host process; arbitrary external writers,
++Bash and another Host instance are not participants in this lease protocol.
+
- See [the ADR](../../adr/parallel-read-batches.md).
++See [ordered preparation](../../adr/parallel-read-batches.md) and
++[Host file admission](../../adr/host-file-batch-admission.md).
| Topic | Decision |
|---|---|
diff --cc docs/spec/03-runtime/06-host-rpc-protocol.md
index e81989966,e81989966..afa703b3a
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@@ -1497,3 -1497,3 +1497,27 @@@ metadata. Approval/rejection remain dig
supported; there is no old-data detection or migration. Disconnect removes
only current S3 credentials, keys and local sync metadata/staging; unrelated
files and remote objects remain intact. See `22-config-sync.md`.
++
++
++## Host file batch admission (version 1)
++
++The sidecar proxy explicitly allows tools.fileBatchCapabilities, tools.fileBatchRegister,
++tools.fileBatchSeal, tools.fileBatchAbandon and tools.fileBatchClose. No wildcard
++method authorization is added. Capabilities takes sessionId and returns
++{version:1,supported:boolean}; remote-workspace sessions return supported:false.
++Register takes sessionId, optional delegationId, batchId, ordinal, toolCallId,
++toolName and args, and returns {ticket}. Only builtin file tool names are
++accepted. Seal/Close take sessionId/batchId; Abandon takes sessionId/ticket.
++The latter methods return {ok:true}. Metadata is bounded (512 calls, 128 per
++batch, 32 MiB retained arguments), process-local and never grants permission.
++
++The additive tools.execute field fileBatchTicket binds the actual request to a
++sealed single-use registration. Session/delegation, call/name and args must
++match; replay, tampering and pre-seal execution fail. Existing callers without
++tickets still receive Host resource exclusion but cannot claim batch source
++order. Runtime only opens write parallelism after the capability handshake.
++Permissions, roots, leases and resource identities are recomputed by Host;
++clients never supply authoritative identities. A changed workspace binding
++reports TOOL_CONTEXT_CHANGED; an identity/address change fails before writing.
++Close/expiry cannot release a running disk task; no failed/uncertain write is
++automatically replayed. See the Host file admission ADR for lifecycle and limits.
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index 38a701f50,7bd8a6909..c86ce2a3d
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -231,56 -231,44 +231,40 @@@
compaction, and terminal Task snapshots through the real React rendering.
The headless command does not replace the rendered Electron check above.
- ### E2E-TOOLS-parallel-read-batches: ordered preparation and parallel file batches
-
- - Isolate data/project paths; never run against production profiles.
- - A local provider fixture emits two Read calls. Gate real tool-execution
- entrypoints until both enter, release them in reverse order, then inspect the
- follow-up model request: results must retain source toolCallId order and final
- sibling rules must follow preparation order. Repeat with a delegated reader
- and verify parent instructions and permission scope are isolated.
- - Add Bash to the batch: all tools must execute sequentially. Add Write or
- Edit instead: calls are ordered by resource conflicts. `[Read a, Write b,
- Read c]` must dispatch all three to Host before any response returns, write
- b's content and keep source-order results; `[Read a, Edit a]`, with the tag of
- a real Read, must reach Host as `read:start`, `read:end`, `edit:start` and
- succeed. Two same-batch Writes to different files must each leave a review
- snapshot that rolls back its own file; in ask mode both must await approval
- together and denying one must not affect the other. Stop before execution
- must skip unstarted calls; running file calls must drain.
- - Add Task with a delegate that edits a fixture file alongside a parent Read;
- the batch must stay sequential, Task keeps reporting a started delegation
- (ADR 0089), and the parent Read must not enter Host until the writable
- shared-workspace delegate settles its mutation. Task-only batches must still
- fan out.
- - Automated coverage: runtime.test.ts uses the production Runtime and pi loop
- with deterministic Host response barriers, including mixed Bash/Write/Edit
- batches and Stop, conflict-ordered file batches for the parent and a real
- delegate loop, calls that fail argument checks or the mode guard while still
- releasing their successors, mixed Task/Write batches in both orders, and the
- mixed Task/read regression in both model orders:
- the Task result stays a started notice, the parent read waits for the writable
- shared-workspace delegate's mutation to settle before entering Host, and a
- failed delegate still releases the batch. `scripts/e2e-task-read-batches.mjs`
- runs the same contract end to end with a real delegate loop: it asserts the
- Host dispatch order `write:start`, `write:end`, `read:start`, `read:end`, that
- the parent reads the written content, and that the Task tool result stays a
- background acknowledgement. subagent.test.ts checks conservative policy
- inheritance.
- - Run `node scripts/e2e-parallel-read-batches.mjs` after building agent-runtime,
- shared and host-core. Set `PI_DESKTOP_HOST_BIN` when reusing a shared target.
- It uses a local HTTP provider, real parent/delegate loops and a real Host in
- temporary directories. A gated response proves overlapping Read dispatch and
- overlapping `[Read, Write, Read]` dispatch; actual Read/Glob/Grep results,
- source-order model results, parent prompt isolation, the `[Read a, Edit a]`
- Host order with a real tag, two-Write rollback and concurrent ask-mode
- approvals are checked. This does not measure blocking filesystem-body overlap,
- production throughput or Electron UI behavior. UI-only project-edit E2E is
- not evidence for agent Edit scheduling.
- - Run `node scripts/e2e-task-read-batches.mjs` under the same build and
- `PI_DESKTOP_HOST_BIN` preconditions. Against the pre-fix implementation it
- fails with `read:start` before `write:start`, which is the regression the
- maintainer asked for.
-### E2E-TOOLS-parallel-read-batches: ordered preparation and parallel reads
++### E2E-TOOLS-parallel-read-batches: ordered preparation and Host file admission
+
-- Isolate data/project paths; never run against production profiles.
-- A local provider fixture emits two Read calls. Gate real tool-execution
- entrypoints until both enter, release them in reverse order, then inspect the
- follow-up model request: results must retain source toolCallId order and final
- sibling rules must follow preparation order. Repeat with a delegated reader
- and verify parent instructions and permission scope are isolated.
-- Add Bash or Edit to the batch: all tools must execute sequentially. Stop
- before execution must skip unstarted calls; running file calls must drain.
-- Add Task with a delegate that edits a fixture file alongside a parent Read;
- the batch must stay sequential, Task keeps reporting a started delegation
- (ADR 0089), and the parent Read must not enter Host until the writable
- shared-workspace delegate settles its mutation. Task-only batches must still
- fan out.
-- Automated coverage: runtime.test.ts uses the production Runtime and pi loop
- with deterministic Host response barriers, including mixed Bash/Write/Edit
- batches and Stop, plus the mixed Task/read regression in both model orders:
- the Task result stays a started notice, the parent read waits for the writable
- shared-workspace delegate's mutation to settle before entering Host, and a
- failed delegate still releases the batch. `scripts/e2e-task-read-batches.mjs`
- runs the same contract end to end with a real delegate loop: it asserts the
- Host dispatch order `write:start`, `write:end`, `read:start`, `read:end`, that
- the parent reads the written content, and that the Task tool result stays a
- background acknowledgement. subagent.test.ts checks conservative policy
- inheritance.
-- Run `node scripts/e2e-parallel-read-batches.mjs` after building agent-runtime,
- shared and host-core. Set `PI_DESKTOP_HOST_BIN` when reusing a shared target.
- It uses a local HTTP provider, real parent/delegate loops and a real Host in
- temporary directories. A gated response proves overlapping Read dispatch;
- actual Read/Glob/Grep results, source-order model results and parent prompt
- isolation are checked. This does not measure blocking filesystem-body overlap,
- production throughput or Electron UI behavior. UI-only project-edit E2E is
- not evidence for agent Edit scheduling.
-- Run `node scripts/e2e-task-read-batches.mjs` under the same build and
- `PI_DESKTOP_HOST_BIN` preconditions. Against the pre-fix implementation it
- fails with `read:start` before `write:start`, which is the regression the
- maintainer asked for.
++- Use isolated data/project paths and a local provider; no production profiles.
++- Run scripts/e2e-parallel-read-batches.mjs after building shared, agent-runtime
++ and the candidate Host. Set PI_DESKTOP_HOST_BIN when reusing a build cache.
++ It drives real parent/delegate pi loops through the real Host: independent
++ read dispatch, ordered results, prompt isolation, mixed Read/Write dispatch,
++ a successful real-tag Edit, differently named hard-link Read/Write in both
++ source orders, individual review rollback and simultaneous ask-mode approvals.
++ File symbolic links run where the OS grants creation; otherwise record an
++ explicit skip and retain hard-link coverage. This is dispatch/content evidence,
++ not a production throughput or Electron UI measurement.
++- Run scripts/e2e-task-read-batches.mjs for both Task/read model orders. Task
++ returns its started notice; the later parent read waits for the writable
++ shared-workspace delegate to settle. Task-only fan-out remains available.
++- Rust file_batches/file_resources/tool_budget::file_tests cover actual native
++ identities, cross-root aliases, unknown/missing targets, structural/register
++ fences, independent resources, queue fairness and cancellation. Native RPC
++ tests reverse tools.execute arrival and assert actual read contents in both
++ hard-link orders, permission-mode denial, changed arguments and ticket replay.
++- tools::file_lease_tests gates a real spawn_blocking body, drops the outer
++ future and proves a conflicting write cannot acquire until that body finishes.
++ Closing/abandoning metadata must not release running work. Snapshot/finalize
++ and later rollback participate in the same Host file domain.
++- Runtime/pi integration tests cover parent/delegate registration, preparation
++ order, validation/mode failures, Stop and model result order. Protocol adapter
++ tests cover sealing, cleanup, remote/legacy fallback and equal provider IDs in
++ independent asynchronous executors. host-runtime/file-batch-bridge.test.ts
++ verifies the explicit allowlist through a real stdio child.
++- Unknown capability/remote workspaces must retain whole-batch sequential writes;
++ no local filesystem identity is used for a remote path. Resource and batch
++ waits consume no capacity, and uncertain writes are not replayed.
++- Specs: tools-and-permissions §0, agent-runtime concurrency, Host RPC file batch
++ protocol; ADRs parallel-read-batches and host-file-batch-admission.
### E2E-STORAGE-custom-location-and-maintenance
diff --cc docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 018a7cb67,a8694c9f9..4352b49c8
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@@ -1213,20 -1213,18 +1213,14 @@@ sidecar 从不直接读取工作区指�
| 工具 | 默认情况下是顺序的 |
| `Task` 通过一条助理消息进行呼叫 | 并行,每会话 10 个运行委托 (ADR 0089) |
- 工具并发性通过 pi 执行模式来表示:Read、Glob、Grep、Write、Edit 是并行候选。
- 并行批次内,调用只等待同一条助理消息中更早且资源声明冲突的调用
- (见 `03-tools-and-permissions.md` §0“并行文件批次”)。仅含 Task 的批次保留并行扇出;
- Task 与这些文件工具混合时整批保持顺序:Task 之前的文件调用在委托启动前完成,
- 位于可写 Task 之后的同批父代理读取或搜索会等待该委托落定后再派发,而该批次里的
-工具并发性通过 pi 执行模式来表示:Read、Glob、Grep 是并行候选,
-仅含 Task 的批次保留并行扇出;Task 与这些读取工具混合时整批保持顺序,
-且位于可写 Task 之后的同批父代理读取会等待该委托落定后再派发,而该批次里的
--Task 自身仍然立即返回启动通知(ADR 0089),父代理用 TaskWait 收敛。其他工具仍为
--`sequential`,并且 pi 按顺序运行包含顺序工具的批处理。这样
--全 Task 批次仍可扇出,并且所有其他订购保证均不变。代表问题
--主机独立调用,以及 host-core 的每次会话一次突变准入
--防止写入撕裂,但留下两个无序的相同路径突变,因此
--sidecar 序列化针对相同标准化路径的 IPC/`sequential` 调用
--在到达宿主之前;不同路径上的调用永远不会相互等待。
--这就是保持每个路径编辑恢复规则的原因
--`03-tools-and-permissions.md` §4d 在扇出下有意义。
++工具并发使用 pi 的有序准备与源序结果契约。Read/Glob/Grep 保持并行;本地 Host
++文件批次能力握手成功后 Write/Edit 才加入。旧 Host 和远程 Host 保持含写整批串行。
++符合条件的批次按源序登记、执行前封存。Host 先检查权限,再解析文件身份,按原始
++序号排序同批冲突,并一次授予资源与容量。原生文件身份覆盖父子代理和会话之间的
++别名;未知身份与命名空间变化保守互斥。取消传输等待后,实际 blocking 任务继续
++持有 permit。支持路径绕过 sidecar PathMutex;legacy 路径保留原锁,变更恢复规则
++继续生效。身份、生命周期和保证范围见工具权限规格 §0 与 host-file-batch-admission ADR。
++仅含 Task 的扇出、Task/文件混批屏障不变;父子路径指令只更新各自提示词。
选择另一个项目选项卡仅影响可见的 shell 工作区。它
不会处置、中止或重新启动属于另一个会话的运行时。
diff --cc docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index 48aa2b366,89c3e192e..5ca73baf0
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@@ -8,62 -8,6 +8,67 @@@
## 0. 冻结政策总结
+### 并行文件批次
+
- Read、Glob、Grep、Write 和 Edit 是并行批次候选。仅含 Task 的批次保留原有的并行扇出;
- Task 与 Read、Glob、Grep、Write 或 Edit 混合的批次整批保持顺序:排在 Task 之前的文件
- 调用在委托启动前完成;排在可写 Task 之后的 Read、Glob 或 Grep 会等该委托落定后再派发到
- Host。排在 Task 之后的 Write 或 Edit 只在 Task 调用返回后运行,不等待委托落定。Task 在
- 该批次中保持 ADR 0089 契约:报告已启动的委托,父代理用 TaskWait 收敛。其他任何顺序工具
- (包括 Bash、TodoWrite、插件/MCP 和未知工具)都会让整个助理批次顺序执行。这是每个代理
- 的批次规则,不是应用级互斥,也不是 Shell 安全锁。只有被选中的内置执行器获得这份允许
- 列表、原生路径准备和资源声明。同名动态工具仍为顺序执行。委托在父代理之后重建目录时,
- 仍保留其启动目录的策略和来源。
-
- 在并行批次内,调用按其声明的资源排序。每个内置文件调用在 runtime 的 `beforeToolCall`
- 准备阶段末尾、所有可能拦截它的 runtime 检查之后记录声明。执行时,它只等待同一条助理
- 消息中更早且声明冲突的调用;批次不会拖住其他任何调用。
-
- | 工具 | 声明 |
++Read、Glob、Grep 是并行候选;只有 runtime 与实际本地 Host 协商文件批次协议版本 1
++成功后,Write、Edit 才加入并行候选。能力在一个 runtime/连接内固定,后台子代理也
++沿用它。旧 Host 和远程工作区保持 Write/Edit sequential,因此含写整批串行。
++sidecar 不查询本机文件系统来判断远程路径。
++
++仅含 Task 的批次保留扇出;Task 与任何文件工具混批仍整批串行。可写 Task 之后的
++读取或搜索等待委托落定;写只等待 Task 返回启动通知。Bash、TodoWrite、未知、插件、
++MCP 工具保留原有串行策略。只有选中的内建执行器接受原生预处理与批次绑定;同名
++动态工具仍为串行。
++
++符合条件的并行批次按源序校验参数、加载路径指令,再向 Host 登记每个文件调用。
++登记包含 session/delegation、新批次 ID、原始序号、调用 ID、工具名和规范参数;Host
++返回不透明的单次 ticket。登记不查询文件、不授予权限、不占执行容量。全部准备结束
++后,各执行器共用一次封存,再携带 ticket 提交 tools.execute。串行批次不登记不完整
++批次。改参、跨所有者使用、重放、封存前执行均失败。ticket 绑定异步执行上下文,
++不使用全局调用 ID 映射,避免父子代理同名 ID 相互覆盖。
++
++Host 保留现有模式和权限检查;只有已获授权的调用才通过 session/delegation 根和
++外部路径解析器识别资源。待审批调用不占活动租约或容量。较早调用身份未知且可能
++冲突时,同批后继保守等待;身份明确后只等待冲突前驱。前驱失败或拒绝不级联失败。
++不同批次或会话只保证资源互斥和排队公平,不虚构全局模型源顺序。
++
++| 工具 / 目标 | Host 资源声明 |
+|---|---|
- | Read | 对其 `path` 共享;没有 `path` 时对整个工作区共享 |
- | Glob、Grep | 对整个工作区共享 |
- | Write | 对其 `path` 独占;没有 `path` 时对整个工作区独占 |
- | Edit | 对其 `path` 独占;当 `ops` 某行(允许前导空白)以 `MV` 或 `REM` 开头、`CUT` 或 `PUT` 头带 `@寄存器`,或没有 `path` 时,对整个工作区独占 |
-
- 两个共享声明永不冲突。任何独占声明都与整个工作区的声明冲突,也与同一文件的路径声明
- 冲突。因此 Glob 和 Grep 与批次中的每个 Write、Edit 保持原顺序,带 `MV`、`REM` 或命名
- 寄存器的 Edit 与批次中其他每个文件调用保持原顺序。host-core 按会话保存命名寄存器,所以
- `CUT @x` 与之后另一个文件上的 `PUT @x` 不能乱序。例如 `[Read a, Edit a, Read b, Write c]`
- 会同时启动 Read a、Read b 和 Write c,Edit a 在 Read a 结束后启动。
-
- 路径键是纯字符串的,从不访问文件系统:反斜杠变为 `/`,相对路径拼接到会话的工作区根
- (非隔离会话为项目路径),`.` 和 `..` 段折叠,去掉末尾 `/`,并统一小写。文件名相同的
- 两个键也视为同一文件:这个 basename 兜底是有意保守的,因为纯字符串键看不到的别名
- (符号链接、委托 worktree 的写法)否则会让一次读取与 Host 的非原子写入重叠。同名但
- 位于不同目录的文件只是少一些重叠。
-
- 失败、被拒绝(例如回合中切换模式后被模式守卫拒绝)或被中止的调用,仍会释放排在其后的
- 调用;失败不会级联。用户停止时仍在等待的调用会在到达 Host 之前以 `TOOL_ABORTED` 失败。
- 声明只在一条助理消息内排序调用,不是跨代理的锁。
-
- 固定版本的 pi-agent-core 会先按原顺序准备全部并行调用,再启动它们的执行体。路径指令
- 解析和提示词更新发生在准备阶段,位于现有父代理模式/扩展检查之后。执行使用同一份规范化
- 参数。直接的内部调用保留预检,且不按声明排序。子代理预检只更新子代理自己的系统记录,
- 从不替换父代理的指令。同级指令链按准备顺序相互替换,与完成顺序无关。
-
- 权限、Host 容量、变更恢复、Hashline 校验和工具结果 ID 仍是权威。Host 仍然每个会话一次
- 只准入一个变更,所以同一批次中互不冲突的 Write 和 Edit 会在 Host 排队,实际执行顺序
- 可能与模型写出的顺序不同;在该队列中等待超过 Host 30 秒准入超时的调用会以
- `HOST_OVERLOADED` 失败。权限审批发生在准入之前,所以同一批次的多个调用可以同时等待
- 审批,每个决定只作用于它自己的调用。完成事件可能乱序到达;交给模型的工具结果保持原
- 顺序。除了 Task 混批屏障之外,`PathMutex` 在父代理及其委托之间,按同一规范化工作区
- 路径协调共享读取与独占的 `Write`/`Edit` 调用,因此父代理的 `Read` 不会与该文件上进行
- 中的委托变更重叠。停止会跳过尚未开始的调用;已经开始的文件 RPC 按现有 Host 生命周期
- 完成。Host 文件取消和资源协调属于后续工作。
-
- 参见 [ADR](/adr/parallel-read-batches)。
++| 已存在常规文件 Read | 文件对象身份及解析地址共享 |
++| 已存在常规文件 Write / 普通 Edit | 文件对象身份及解析地址独占 |
++| Glob / Grep | Host 文件协调域共享 |
++| 目标不存在、身份未知、文件系统不支持 | 读取持共享域;写入持独占域 |
++| Edit MV / REM 或 CUT/PUT 命名寄存器 | 协调域独占 |
++| review 回滚 | 协调域独占,保留写后内容哈希校验 |
++
++Unix 对支持的本地文件系统使用已打开文件的 dev/ino;Windows 对本地磁盘使用卷标识
++和 FILE_ID_INFO。句柄在排队及活动期间保持有效。不同名称、不同根的硬链接/符号链接
++仍必须冲突。根决定权限和地址解析,不能把物理文件 ID 按根分区。basename、文件大小、
++词法路径、单独 realpath 都不能证明独立。全域含已授权外部路径。两侧都是共享时不冲突;
++一侧独占时,域声明与所有文件资源冲突,否则按相同对象身份或地址冲突。未知不退回
++“推定独立”。
++
++ToolBudget 一次授予全部资源和容量;等待前驱或资源不占槽位。后来的冲突调用不能
++越过等待中的独占者;同批较早源序调用可越过后到达的后继,避免队列与依赖图死锁。
++额度仍为总 16、读 8、写 2、每会话 4、每会话写 1;准入等待 30 秒仍返回 HOST_OVERLOADED。
++本地 audit/debug 记录总准入等待与初始原因 source_order、resource、capacity;不将它们
++宣称为互不重叠的分段耗时。
++
++拿到租约后在 review 快照前和实际 blocking 文件任务内重验身份与地址。绑定变化则
++失败,不落盘、不自动重放。命名空间变化和创建目标使用全域独占屏障。before 快照、
++执行、Hashline 更新、after 快照共用租约;后续 rollback 也获取租约,等待时不持 AppState
++锁。取消 RPC future 不会停止 spawn_blocking,实际任务持有 permit 到执行结束。
++未开始项可放弃;关闭批次不能释放活动磁盘任务。登记表限制为全局 512 调用、每批
++128 调用、参数总计 32 MiB;未使用元数据 15 分钟过期,已提交的审批等待和实际任务
++不靠 TTL 回收。
++
++支持新协议的路径由 Host 资源协调替代 sidecar PathMutex;legacy 路径保留原锁。
++权限、Hashline、变更恢复和结果语义保持。父子路径指令只更新各自提示词;pi 保持源序
++提交工具结果。租约只覆盖单个 Host 内接入的文件工具和回滚,任意外部写者、Bash、
++另一个 Host 进程不自动参与。
++
++参见 [有序准备 ADR](/adr/parallel-read-batches) 和 [Host 准入 ADR](/adr/host-file-batch-admission)。
+
| 主题 | 决定 |
|---|---|
| 默认模式 | Agent |
diff --cc docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 12dccdee3,12dccdee3..5042c9b11
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@@ -1143,3 -1143,3 +1143,21 @@@ schedule,Manual 转 Hourly 继续使�
保存和读取工作区绑定时统一使用现有项目路径规范化规则。在 Windows 上,
斜杠方向、大小写、末尾分隔符和扩展路径前缀的差异不会再让同项目会话看不到任务。
缺失的旧版绑定与显式 null 仍保持不同语义;其他项目的工具不能查询或修改绑定任务。
++
++
++## Host 文件批次准入(版本 1)
++
++sidecar 代理明确允许 tools.fileBatchCapabilities、tools.fileBatchRegister、
++tools.fileBatchSeal、tools.fileBatchAbandon、tools.fileBatchClose,不添加通配权限。
++Capabilities 接收 sessionId,返回 {version:1,supported:boolean};远程工作区返回 false。
++Register 接收 sessionId、可选 delegationId、batchId、ordinal、toolCallId、toolName、args,
++返回 {ticket},只接受内建文件工具名。Seal/Close 接收 sessionId/batchId,Abandon 接收
++sessionId/ticket,返回 {ok:true}。登记为进程内有界元数据:全局 512 调用、每批 128 调用、
++参数总计 32 MiB,不授予文件权限。
++
++tools.execute 增加可选 fileBatchTicket,绑定封存后的单次调用。会话/委派、调用/工具名、
++参数必须匹配;重放、改参、封存前执行均失败。无 ticket 的旧调用仍获得 Host 资源互斥,
++但不具有批内源序信息。runtime 只在能力握手成功后开放写并行。权限、根、租约、文件身份
++由 Host 决定,客户端不提供权威身份。工作区绑定变化返回 TOOL_CONTEXT_CHANGED;文件身份
++或地址变化在写入前失败。Close/过期不能释放运行中的磁盘任务,不自动重放失败或结果不明
++的写。生命周期和限制见 Host 文件准入 ADR。
diff --cc packages/agent-runtime/src/batch-planner.test.ts
index 4c6312fe6,000000000..4970b5362
mode 100644,000000..100644
--- a/packages/agent-runtime/src/batch-planner.test.ts
+++ b/packages/agent-runtime/src/batch-planner.test.ts
@@@ -1,315 -1,0 +1,131 @@@
- import { describe, expect, it } from "vitest";
++import { describe, expect, it, vi } from "vitest";
+import { Type } from "typebox";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
- import { BatchPlanner, claimsConflict, sameFile, withBatchTurn } from "./batch-planner.js";
- import { resourcePathKey, TOOL_EXECUTION_SPECS, type ResourceClaim } from "./tool-execution-policy.js";
-
- const path = (key: string, access: "shared" | "exclusive"): ResourceClaim => ({ kind: "path", key, access });
- const tree = (access: "shared" | "exclusive"): ResourceClaim => ({ kind: "tree", access });
- const claims = (name: string, params: unknown, base = "/root") => TOOL_EXECUTION_SPECS[name]!.claims!(params, base);
-
- /** Resolves on the next macrotask, after every pending microtask has run. */
- const settledTurn = () => new Promise((resolve) => setTimeout(resolve, 0));
-
- function track(promise: Promise<unknown>) {
- const state = { done: false };
- void promise.then(() => { state.done = true; }, () => { state.done = true; });
- return state;
++import type { RuntimeHost } from "./host-client.js";
++import { BatchPlanner, withBatchTurn } from "./batch-planner.js";
++import { toolExecutionMode } from "./tool-execution-policy.js";
++
++function fixture(capability: unknown = { version: 1, supported: true }) {
++ const calls: Array<{ method: string; params: unknown }> = [];
++ const host: RuntimeHost = { call: async <T>(method: string, params?: unknown) => {
++ calls.push({ method, params });
++ return (method === "tools.fileBatchCapabilities" ? capability
++ : method === "tools.fileBatchRegister" ? { ticket: `ticket-${calls.length}` } : { ok: true }) as T;
++ } };
++ const planner = new BatchPlanner(host, "session");
++ const register = (batch: object, args: object, ordinal = 0) => planner.register(batch, args, {
++ ordinal, toolCallId: `call-${ordinal}`, toolName: "Write", args, delegationId: "delegate-root",
++ });
++ return { host, planner, calls, register };
+}
+
- describe("claim conflicts", () => {
- it.each([
- ["path S / path S", path("a", "shared"), path("a", "shared"), false],
- ["path X / path X, same file", path("/r/a", "exclusive"), path("/r/a", "exclusive"), true],
- ["path S / path X, same file", path("/r/a", "shared"), path("/r/a", "exclusive"), true],
- ["path X / path S, other file", path("/r/a", "exclusive"), path("/r/b", "shared"), false],
- ["tree S / tree S", tree("shared"), tree("shared"), false],
- ["tree S / path X", tree("shared"), path("/r/a", "exclusive"), true],
- ["path X / tree S", path("/r/a", "exclusive"), tree("shared"), true],
- ["tree S / path S", tree("shared"), path("/r/a", "shared"), false],
- ["tree X / path S", tree("exclusive"), path("/r/a", "shared"), true],
- ["tree X / tree S", tree("exclusive"), tree("shared"), true],
- ["path S / tree X", path("/r/a", "shared"), tree("exclusive"), true],
- ] as const)("%s → %s", (_label, a, b, expected) => {
- expect(claimsConflict([a], [b])).toBe(expected);
- });
-
- it("never orders a call that declares no claims", () => {
- expect(claimsConflict([], [tree("exclusive")])).toBe(false);
- expect(claimsConflict([tree("exclusive")], [])).toBe(false);
- });
- });
-
- describe("resource path keys", () => {
- const key = (raw: string) => resourcePathKey(raw, "/root");
-
- it.each([
- ["a.ts", "./a.ts"],
- ["src\\a.ts", "src/a.ts"],
- ["/root/a.ts", "a.ts"],
- ["A.ts", "a.ts"],
- ["src/../a.ts", "a.ts"],
- ["src/", "src"],
- ])("%s and %s name the same file", (left, right) => {
- expect(key(left)).toBe(key(right));
- expect(sameFile(key(left), key(right))).toBe(true);
- });
-
- it("keeps absolute Windows, POSIX and UNC paths off the base", () => {
- expect(resourcePathKey("C:\\Work\\A.ts", "/root")).toBe("c:/work/a.ts");
- expect(resourcePathKey("/etc/hosts", "C:/root")).toBe("/etc/hosts");
- expect(resourcePathKey("//server/share/a.ts", "/root")).toBe("/server/share/a.ts");
- expect(resourcePathKey("a.ts", "C:\\Root")).toBe("c:/root/a.ts");
- });
-
- it("treats a shared basename as the same file even in different directories", () => {
- expect(sameFile(key("x/a.ts"), key("y/a.ts"))).toBe(true);
- });
-
- it("keeps different files apart", () => {
- expect(sameFile(key("a.ts"), key("b.ts"))).toBe(false);
- });
- });
-
- describe("tool claims", () => {
- it("declares Read as a shared path and Glob/Grep as a shared tree", () => {
- expect(claims("Read", { path: "a.ts" })).toEqual([path("/root/a.ts", "shared")]);
- expect(claims("Read", {})).toEqual([tree("shared")]);
- expect(claims("Glob", { pattern: "*.ts" })).toEqual([tree("shared")]);
- expect(claims("Grep", { pattern: "x", path: "src" })).toEqual([tree("shared")]);
- });
-
- it("declares Write as an exclusive path, or the whole tree without a path", () => {
- expect(claims("Write", { path: "a.ts", content: "" })).toEqual([path("/root/a.ts", "exclusive")]);
- expect(claims("Write", { content: "" })).toEqual([tree("exclusive")]);
- });
-
- it.each([
- ["plain ops", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x" }, [path("/root/a.ts", "exclusive")]],
- ["MV", { path: "a.ts", tag: "ABCD", ops: "MV b.ts" }, [tree("exclusive")]],
- ["indented REM after another op", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x\n REM" }, [tree("exclusive")]],
- ["MV text inside a body row", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+MV b.ts" }, [path("/root/a.ts", "exclusive")]],
- ["CUT into a named register", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @moved" }, [tree("exclusive")]],
- ["PUT from a named register", { path: "b.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x\nPUT <1 @moved" }, [tree("exclusive")]],
- ["a register after U+0085, which host-core treats as whitespace", { path: "b.ts", tag: "ABCD", ops: "PUT\u0085<1\u0085@moved" }, [tree("exclusive")]],
- ["anonymous CUT and PUT in one call", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5\nPUT <1" }, [path("/root/a.ts", "exclusive")]],
- ["@ text inside a body row", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+mail @someone" }, [path("/root/a.ts", "exclusive")]],
- ["legacy old_string/new_string", { path: "a.ts", old_string: "a", new_string: "b" }, [path("/root/a.ts", "exclusive")]],
- ["missing path", { tag: "ABCD", ops: "PUT 1.=1:\n+x" }, [tree("exclusive")]],
- ["empty path", { path: " ", ops: "PUT 1.=1:\n+x" }, [tree("exclusive")]],
- ] as const)("declares Edit with %s", (_label, params, expected) => {
- expect(claims("Edit", params)).toEqual(expected);
- });
-
- it("gives Task no claims and leaves unlisted tools sequential without claims", () => {
- expect(TOOL_EXECUTION_SPECS.Task).toEqual({ mode: "parallel" });
- expect(TOOL_EXECUTION_SPECS.Bash).toBeUndefined();
- });
- });
-
- describe("BatchPlanner", () => {
- /** Registers calls in source order under one batch and returns their keys. */
- function plan(planner: BatchPlanner, batch: object, calls: Array<[string, unknown]>) {
- return calls.map(([name, params]) => {
- const key = { name, params };
- planner.register(batch, key, claims(name, params));
- return key;
- });
- }
-
- it("keeps a named-register CUT and PUT on different files in source order", async () => {
- const planner = new BatchPlanner();
- // Host keeps named registers per session, so the PUT must see this CUT.
- const [cut, put] = plan(planner, {}, [
- ["Edit", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @moved" }],
- ["Edit", { path: "b.ts", tag: "ABCD", ops: "PUT <1 @moved" }],
- ]);
- const waiting = track(planner.waitForTurn(put));
- await settledTurn();
- expect(waiting.done).toBe(false);
- planner.settle(cut);
- await settledTurn();
- expect(waiting.done).toBe(true);
- });
-
- it("orders only the conflicting call in [Read a, Edit a, Read b, Write c]", async () => {
- const planner = new BatchPlanner();
- const [readA, editA, readB, writeC] = plan(planner, {}, [
- ["Read", { path: "a.ts" }],
- ["Edit", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x" }],
- ["Read", { path: "b.ts" }],
- ["Write", { path: "c.ts", content: "" }],
- ]);
- const edit = track(planner.waitForTurn(editA));
- const others = [readA, readB, writeC].map((key) => track(planner.waitForTurn(key)));
- await settledTurn();
- expect(others.map((state) => state.done)).toEqual([true, true, true]);
- expect(edit.done).toBe(false);
- planner.settle(readA);
- await settledTurn();
- expect(edit.done).toBe(true);
- });
-
- it("waits for every conflicting predecessor", async () => {
- const planner = new BatchPlanner();
- const [first, second, third] = plan(planner, {}, [
- ["Read", { path: "a.ts" }],
- ["Read", { path: "./a.ts" }],
- ["Write", { path: "a.ts", content: "" }],
- ]);
- const write = track(planner.waitForTurn(third));
- planner.settle(first);
- await settledTurn();
- expect(write.done).toBe(false);
- planner.settle(second);
- await settledTurn();
- expect(write.done).toBe(true);
- });
-
- it("keeps batches apart", async () => {
- const planner = new BatchPlanner();
- const [parentRead] = plan(planner, {}, [["Read", { path: "a.ts" }]]);
- const [childWrite] = plan(planner, {}, [["Write", { path: "a.ts", content: "" }]]);
- await expect(planner.waitForTurn(childWrite)).resolves.toBeUndefined();
- planner.settle(parentRead);
- });
-
- it("returns at once for an unregistered call", async () => {
- await expect(new BatchPlanner().waitForTurn({})).resolves.toBeUndefined();
- });
-
- it("returns on abort while a predecessor is still running", async () => {
- const planner = new BatchPlanner();
- const [, edit] = plan(planner, {}, [
- ["Read", { path: "a.ts" }],
- ["Edit", { path: "a.ts", ops: "PUT 1.=1:\n+x" }],
- ]);
- const controller = new AbortController();
- const waiting = track(planner.waitForTurn(edit, controller.signal));
- await settledTurn();
- expect(waiting.done).toBe(false);
- controller.abort();
- await settledTurn();
- expect(waiting.done).toBe(true);
- });
-
- it("unblocks a successor when a registered predecessor never executes and the batch aborts", async () => {
- const planner = new BatchPlanner();
- const batch = {};
- // The predecessor is registered but never reaches waitForTurn/settle.
- const [, write] = plan(planner, batch, [
- ["Read", { path: "a.ts" }],
- ["Write", { path: "a.ts", content: "" }],
- ]);
- const controller = new AbortController();
- const waiting = track(planner.waitForTurn(write, controller.signal));
- await settledTurn();
- expect(waiting.done).toBe(false);
- controller.abort();
- await settledTurn();
- expect(waiting.done).toBe(true);
- // An already-aborted signal returns at once as well.
- await expect(planner.waitForTurn(write, controller.signal)).resolves.toBeUndefined();
- });
-
- it("settles every registration left in a batch at batch end", async () => {
- const planner = new BatchPlanner();
++describe("Host file batch bindings", () => {
++ it.each([undefined, {}, { version: 2, supported: true }, { version: 1, supported: false }])("keeps writes sequential without a supported capability: %s", async (response) => {
++ const { planner, register, calls } = fixture(response ?? null);
++ await planner.negotiate(false);
++ await register({}, {});
++ expect(planner.supported).toBe(false);
++ expect(calls.map((c) => c.method)).toEqual(["tools.fileBatchCapabilities"]);
++ expect(toolExecutionMode("Write", planner.supported)).toBe("sequential");
++ expect(toolExecutionMode("Edit", planner.supported)).toBe("sequential");
++ });
++
++ it("never looks up remote paths on the local Host", async () => {
++ const { planner, calls } = fixture();
++ await planner.negotiate(true);
++ expect(planner.supported).toBe(false);
++ expect(calls).toEqual([]);
++ });
++
++ it("only treats an unknown method as legacy, preserving real transport failures", async () => {
++ const { planner, host } = fixture();
++ host.call = vi.fn().mockRejectedValue(Object.assign(new Error("old Host"), { errorCode: "METHOD_NOT_FOUND" }));
++ await expect(planner.negotiate(false)).resolves.toBeUndefined();
++ const broken = fixture();
++ broken.host.call = vi.fn().mockRejectedValue(new Error("connection lost"));
++ await expect(broken.planner.negotiate(false)).rejects.toThrow("connection lost");
++ });
++
++ it("negotiates once per runtime, including a legacy numeric method error", async () => {
++ const { planner, host } = fixture();
++ host.call = vi.fn().mockRejectedValue(Object.assign(new Error("legacy"), { code: -32601, errorCode: "NOT_FOUND" }));
++ await planner.negotiate(false); await planner.negotiate(false);
++ expect(host.call).toHaveBeenCalledTimes(1);
++ expect(planner.supported).toBe(false);
++ });
++
++ it("closes failed registrations and blocks the rest of preparation without dispatch", async () => {
++ const { planner, host, register } = fixture(); await planner.negotiate(false);
++ const calls: string[] = [];
++ host.call = async <T>(method: string) => {
++ calls.push(method);
++ return (method === "tools.fileBatchRegister" ? {} : { ok: true }) as T;
++ };
+ const batch = {};
- const [, write] = plan(planner, batch, [
- ["Read", { path: "a.ts" }],
- ["Write", { path: "a.ts", content: "" }],
- ]);
- const waiting = track(planner.waitForTurn(write));
- planner.settleBatch(batch);
- await settledTurn();
- expect(waiting.done).toBe(true);
- });
-
- it("treats settle as idempotent and safe for unknown keys", async () => {
- const planner = new BatchPlanner();
- const [read, write] = plan(planner, {}, [
- ["Read", { path: "a.ts" }],
- ["Write", { path: "a.ts", content: "" }],
++ await expect(register(batch, {})).rejects.toThrow("invalid file batch ticket");
++ await expect(register(batch, {}, 1)).rejects.toThrow("invalid file batch ticket");
++ expect(calls).toEqual(["tools.fileBatchRegister", "tools.fileBatchClose"]);
++ });
++
++ it("registers in source order, binds delegation and seals once before any execute", async () => {
++ const { planner, calls, register } = fixture();
++ await planner.negotiate(false);
++ const batch = {}, a = { path: "a" }, b = { path: "b" };
++ await register(batch, a); await register(batch, b, 3);
++ await Promise.all([planner.waitForTurn(b), planner.waitForTurn(a)]);
++ expect(calls.map((c) => c.method)).toEqual([
++ "tools.fileBatchCapabilities", "tools.fileBatchRegister", "tools.fileBatchRegister", "tools.fileBatchSeal",
+ ]);
- planner.settle(read);
- planner.settle(read);
- planner.settle({});
- await expect(planner.waitForTurn(write)).resolves.toBeUndefined();
- });
- });
-
- describe("withBatchTurn releases every registered call", () => {
- function tool(execute: AgentTool["execute"]): AgentTool {
- return { name: "Read", label: "Read", description: "Read", parameters: Type.Object({}), execute };
- }
-
- /** [predecessor, successor] on one file; the successor waits for the predecessor. */
- function batch(planner: BatchPlanner) {
- const first = { path: "a.ts" };
- const second = { path: "a.ts", content: "" };
- const key = {};
- planner.register(key, first, claims("Read", first));
- planner.register(key, second, claims("Write", second));
- return { key, first, second };
- }
-
- it.each([
- ["throws synchronously", () => { throw new Error("invalid arguments"); }],
- ["rejects", async () => { throw new Error("mode denied"); }],
- ] as const)("when the inner execute %s", async (_label, execute) => {
- const planner = new BatchPlanner();
- const { first, second } = batch(planner);
- const failing = withBatchTurn(tool(execute as AgentTool["execute"]), planner);
- const next = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
- const successor = next.execute("second", second as never);
- await expect(failing.execute("first", first as never)).rejects.toThrow();
- await expect(successor).resolves.toEqual({ content: [], details: {} });
- });
-
- it("releases only after the inner execute settles", async () => {
- const planner = new BatchPlanner();
- const { first, second } = batch(planner);
- let finish!: () => void;
- const slow = withBatchTurn(tool(() => new Promise((resolve) => {
- finish = () => resolve({ content: [], details: {} });
- })), planner);
- const next = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
- const running = slow.execute("first", first as never);
- const waiting = track(next.execute("second", second as never));
- await settledTurn();
- expect(waiting.done).toBe(false);
- finish();
- await running;
- await settledTurn();
- expect(waiting.done).toBe(true);
- });
-
- it("releases a call that was aborted while waiting for its turn", async () => {
- const planner = new BatchPlanner();
- const { key, first, second } = batch(planner);
- // A later same-file Read in the same batch waits only for the Write; the
- // first Read keeps running and never settles in this test.
- const third = { path: "a.ts" };
- planner.register(key, third, claims("Read", third));
- const controller = new AbortController();
- const inner = async (_id: string, _args: unknown, signal?: AbortSignal) => {
- if (signal?.aborted) throw new Error("tool execution aborted before it started");
- return { content: [], details: {} };
- };
- const write = withBatchTurn(tool(inner as AgentTool["execute"]), planner);
- const read = withBatchTurn(tool(inner as AgentTool["execute"]), planner);
- const writing = write.execute("second", second as never, controller.signal);
- const reading = read.execute("third", third as never);
- controller.abort();
- await expect(writing).rejects.toThrow("aborted before it started");
- // The Write never ran but still released the Read ordered behind it.
- await expect(reading).resolves.toEqual({ content: [], details: {} });
- planner.settle(first);
- });
-
- it("is a no-op for a direct call that was never registered", async () => {
- const planner = new BatchPlanner();
- const wrapped = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
- await expect(wrapped.execute("direct", { path: "a.ts" } as never)).resolves.toEqual({ content: [], details: {} });
++ expect(calls[1].params).toMatchObject({ sessionId: "session", ordinal: 0, delegationId: "delegate-root", args: a });
++ expect(calls[2].params).toMatchObject({ ordinal: 3, args: b });
++ expect(await planner.execute(a, async () => planner.ticket("call-0"))).toBe("ticket-2");
++ await planner.settle(a);
++ expect(planner.ticket("call-0")).toBeUndefined();
++ planner.settleBatch(batch); await planner.drain();
++ expect(calls.at(-1)?.method).toBe("tools.fileBatchClose");
++ });
++
++ it.each(["argument validation", "mode denial"])("abandons a call rejected by %s outside the builtin executor", async (reason) => {
++ const { planner, calls, register } = fixture();
++ await planner.negotiate(false);
++ const args = {}, batch = {};
++ await register(batch, args);
++ const tool: AgentTool = { name: "Write", label: "Write", description: "test", parameters: Type.Object({}), execute: async () => { throw new Error(reason); } };
++ await expect(withBatchTurn(tool, planner).execute("call-0", args)).rejects.toThrow(reason);
++ expect(calls.at(-1)).toMatchObject({ method: "tools.fileBatchAbandon", params: { ticket: "ticket-2" } });
++ });
++
++ it("abandons an aborted unstarted call and never invokes its executor", async () => {
++ const { planner, register, calls } = fixture();
++ await planner.negotiate(false);
++ const args = {}; await register({}, args);
++ const execute = vi.fn(async () => ({ content: [], details: {} }));
++ const tool: AgentTool = { name: "Write", label: "Write", description: "test", parameters: Type.Object({}), execute };
++ await expect(withBatchTurn(tool, planner).execute("call-0", args, AbortSignal.abort())).rejects.toMatchObject({ name: "AbortError" });
++ expect(execute).not.toHaveBeenCalled();
++ expect(calls.at(-1)?.method).toBe("tools.fileBatchAbandon");
++ });
++
++ it("keeps unrelated batches separate and makes batch cleanup idempotent", async () => {
++ const { planner, register, calls } = fixture(); await planner.negotiate(false);
++ const a = {}, b = {}, argsA = {}, argsB = {};
++ await register(a, argsA); await register(b, argsB, 1);
++ planner.settleBatch(a); planner.settleBatch(a); await planner.drain();
++ expect(await planner.execute(argsB, async () => planner.ticket("call-1"))).toBeDefined();
++ expect(calls.filter((c) => c.method === "tools.fileBatchClose")).toHaveLength(1);
++ await planner.waitForTurn(argsB);
++ expect(calls.at(-1)?.method).toBe("tools.fileBatchSeal");
++ });
++
++ it("isolates equal provider call IDs in concurrent parent/delegate executors", async () => {
++ const { planner, register } = fixture(); await planner.negotiate(false);
++ const parent = {}, child = {};
++ await register({}, parent); await register({}, child);
++ let release: () => void = () => {};
++ const gate = new Promise<void>((resolve) => { release = resolve; });
++ const first = planner.execute(parent, async () => { await gate; return planner.ticket("call-0"); });
++ const second = planner.execute(child, async () => { release(); await gate; return planner.ticket("call-0"); });
++ expect(await Promise.all([first, second])).toEqual(["ticket-2", "ticket-3"]);
++ expect(planner.ticket("call-0")).toBeUndefined();
+ });
+});
diff --cc packages/agent-runtime/src/batch-planner.ts
index 4a17215a0,000000000..e26787ee8
mode 100644,000000..100644
--- a/packages/agent-runtime/src/batch-planner.ts
+++ b/packages/agent-runtime/src/batch-planner.ts
@@@ -1,128 -1,0 +1,138 @@@
- /**
- * Orders the calls of one parallel pi batch by the resources they claim.
- *
- * pi prepares every call of a parallel batch in source order and then starts
- * them all at once. Each prepared call registers its claims here; at execution
- * it waits only for earlier calls of the same batch whose claims conflict, so
- * unrelated reads and writes overlap while same-file work keeps source order.
- *
- * Batch-local only: the parent and its delegates still meet in `PathMutex` and
- * host-core admission.
- */
++/** Host batch bindings. Resource identity and conflict admission live in Host. */
++import { randomUUID } from "node:crypto";
++import { AsyncLocalStorage } from "node:async_hooks";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
- import type { ResourceClaim } from "./tool-execution-policy.js";
++import type { RuntimeHost } from "./host-client.js";
++import { FILE_BATCH_VERSION, type FileBatchRegistration } from "@pi-desktop/shared";
+
- type PlannedCall = {
- claims: ResourceClaim[];
- /** Earlier calls of the same batch that conflict; fixed at registration. */
- deps: PlannedCall[];
- settled: Promise<void>;
- resolve: () => void;
- };
-
- /**
- * True for two keys that may name one file: the same key, or the same file
- * name. The basename fallback is deliberately conservative — it also catches
- * aliases a lexical key cannot see (absolute vs. relative spellings of a
- * delegate worktree, symlinked directories) because host-core writes are not
- * atomic. Same-name files in different directories only lose overlap.
- */
- export function sameFile(left: string, right: string): boolean {
- return left === right || left.slice(left.lastIndexOf("/") + 1) === right.slice(right.lastIndexOf("/") + 1);
++type Batch = { id: string; seal?: Promise<unknown>; failure?: Error; calls: Map<object, string> };
++type Call = { batch: Batch; id: string; ticket: string };
++function record(value: unknown): value is Record<string, unknown> {
++ return typeof value === "object" && value !== null;
+}
+
- function claimConflicts(left: ResourceClaim, right: ResourceClaim): boolean {
- if (left.access === "shared" && right.access === "shared") return false;
- if (left.kind === "tree" || right.kind === "tree") return true;
- return sameFile(left.key, right.key);
- }
++export class BatchPlanner {
++ supported = false;
++ private batches = new WeakMap<object, Batch>();
++ private byArgs = new WeakMap<object, Call>();
++ private execution = new AsyncLocalStorage<Call | undefined>();
++ private pendingCleanup = new Set<Promise<unknown>>();
++ private negotiation?: Promise<void>;
+
- export function claimsConflict(left: readonly ResourceClaim[], right: readonly ResourceClaim[]): boolean {
- return left.some((a) => right.some((b) => claimConflicts(a, b)));
- }
++ constructor(private host: RuntimeHost, private sessionId: string) {}
+
- export class BatchPlanner {
- /** Keyed by the assistant message, so a finished batch is collected with it. */
- private batches = new WeakMap<object, PlannedCall[]>();
- /** Keyed by the args object pi passes to `execute` (see `preparedPathToolArgs`). */
- private byArgs = new WeakMap<object, PlannedCall>();
++ /** Capability belongs to the actual execution endpoint, never local stat. */
++ async negotiate(remote: boolean): Promise<void> {
++ // A runtime is bound to one Host connection/configuration. Background
++ // delegates must not switch lock protocols when a later prompt starts.
++ this.negotiation ??= this.loadCapabilities(remote);
++ await this.negotiation;
++ }
++
++ private async loadCapabilities(remote: boolean): Promise<void> {
++ if (remote) return;
++ let response: unknown;
++ try {
++ response = await this.host.call("tools.fileBatchCapabilities", { sessionId: this.sessionId });
++ } catch (error) {
++ if (record(error) && (error.code === -32601 || error.errorCode === "METHOD_NOT_FOUND"
++ || (record(error.rpc) && error.rpc.code === -32601))) return;
++ throw error;
++ }
++ this.supported = record(response) && response.version === FILE_BATCH_VERSION && response.supported === true;
++ }
+
- /** Called during preparation, which pi runs in source order. */
- register(batchKey: object, argsKey: object, claims: ResourceClaim[]): void {
++ async register(batchKey: object, argsKey: object, call: {
++ ordinal: number; toolCallId: string; toolName: string; args: unknown; delegationId?: string;
++ }): Promise<void> {
++ if (!this.supported) return;
+ let batch = this.batches.get(batchKey);
+ if (!batch) {
- batch = [];
++ batch = { id: randomUUID(), calls: new Map() };
+ this.batches.set(batchKey, batch);
+ }
- let resolve!: () => void;
- const settled = new Promise<void>((done) => { resolve = done; });
- const call: PlannedCall = {
- claims,
- deps: batch.filter((prior) => claimsConflict(prior.claims, claims)),
- settled,
- resolve,
++ if (batch.failure) throw batch.failure;
++ const registration: FileBatchRegistration = {
++ sessionId: this.sessionId, batchId: batch.id, ...call,
+ };
- batch.push(call);
- this.byArgs.set(argsKey, call);
++ let response: unknown;
++ try {
++ response = await this.host.call("tools.fileBatchRegister", registration);
++ if (!record(response) || typeof response.ticket !== "string" || !response.ticket) {
++ throw new Error("Host returned an invalid file batch ticket");
++ }
++ } catch (error) {
++ batch.failure = error instanceof Error ? error : new Error(String(error));
++ // No executor can have started during ordered preparation. Cancel the
++ // whole metadata batch instead of stranding successors behind an unknown
++ // ticket from a lost registration response. Never retry a write.
++ await this.host.call("tools.fileBatchClose", { sessionId: this.sessionId, batchId: batch.id });
++ throw batch.failure;
++ }
++ const prepared = { batch, id: call.toolCallId, ticket: response.ticket };
++ batch.calls.set(argsKey, call.toolCallId);
++ this.byArgs.set(argsKey, prepared);
+ }
+
- /**
- * Waits until every conflicting predecessor settles, or `signal` aborts; the
- * caller's own abort check then fails the call. Returns at once for a call
- * that was never registered (a direct, non-pi invocation). No timeout: every
- * wait ends at a call that really runs or at the batch's abort signal.
- */
+ async waitForTurn(argsKey: object, signal?: AbortSignal): Promise<void> {
+ const call = this.byArgs.get(argsKey);
- if (!call || call.deps.length === 0 || signal?.aborted) return;
- await new Promise<void>((resolve) => {
- const onAbort = () => resolve();
- signal?.addEventListener("abort", onAbort, { once: true });
- void Promise.all(call.deps.map((dep) => dep.settled)).then(() => {
- signal?.removeEventListener("abort", onAbort);
- resolve();
- });
++ if (!call) return;
++ if (call.batch.failure) throw call.batch.failure;
++ if (signal?.aborted) throw Object.assign(new Error("file call aborted before dispatch"), { name: "AbortError" });
++ // pi prepares the entire parallel batch before starting any executor.
++ // Sharing the seal promise prevents an executor from overtaking sealing.
++ call.batch.seal ??= this.host.call("tools.fileBatchSeal", {
++ sessionId: this.sessionId, batchId: call.batch.id,
+ });
++ await call.batch.seal;
++ if (signal?.aborted) throw Object.assign(new Error("file call aborted before dispatch"), { name: "AbortError" });
++ }
++
++ ticket(toolCallId: string): string | undefined {
++ const call = this.execution.getStore();
++ return call?.id === toolCallId ? call.ticket : undefined;
+ }
+
- /** Releases the calls ordered behind this one. Idempotent. */
- settle(argsKey: object): void {
++ execute<T>(argsKey: object, body: () => Promise<T>): Promise<T> {
++ // Provider call IDs may repeat in independent delegate conversations. Bind
++ // the ticket to this executor, not a process-global toolCallId map.
++ return this.execution.run(this.byArgs.get(argsKey), body);
++ }
++
++ async settle(argsKey: object): Promise<void> {
+ const call = this.byArgs.get(argsKey);
+ if (!call) return;
+ this.byArgs.delete(argsKey);
- call.resolve();
++ call.batch.calls.delete(argsKey);
++ if (call.batch.failure) return;
++ // Host only abandons a ticket that never reached tools.execute. Running
++ // disk work retains its permit even if the transport waiter was aborted.
++ await this.host.call("tools.fileBatchAbandon", { sessionId: this.sessionId, ticket: call.ticket });
+ }
+
- /**
- * Batch-end backstop: settles whatever the batch still holds, such as a call
- * pi prepared but never started because the run aborted. It cannot replace
- * {@link withBatchTurn}, because pi only ends a batch after every started
- * call has returned.
- */
+ settleBatch(batchKey: unknown): void {
- if (typeof batchKey !== "object" || batchKey === null) return;
- for (const call of this.batches.get(batchKey) ?? []) call.resolve();
++ if (!record(batchKey)) return;
++ const batch = this.batches.get(batchKey);
++ if (!batch) return;
+ this.batches.delete(batchKey);
++ for (const args of batch.calls.keys()) this.byArgs.delete(args);
++ batch.calls.clear();
++ const cleanup = this.host.call("tools.fileBatchClose", { sessionId: this.sessionId, batchId: batch.id });
++ this.pendingCleanup.add(cleanup);
++ void cleanup.catch((error: unknown) => {
++ console.warn("[agent-runtime] Host file batch cleanup failed", error instanceof Error ? error.message : String(error));
++ }).finally(() => this.pendingCleanup.delete(cleanup));
+ }
++
++ async drain(): Promise<void> { await Promise.all(this.pendingCleanup); }
+}
+
- /**
- * The catalog layer pi calls (a delegate's scoping wrapper calls it in turn).
- * Waiting and releasing live here, outside every check the tool makes (argument
- * validation, the mode guard), so a call that throws, rejects or aborts before
- * reaching the Host still releases its successors.
- */
++/** Wrap validation and mode guards so pre-Host failures abandon their ticket. */
+export function withBatchTurn(tool: AgentTool, planner: BatchPlanner): AgentTool {
- return {
- ...tool,
- execute: async (toolCallId, args, signal, onUpdate) => {
- const key = args as object;
- try {
- await planner.waitForTurn(key, signal);
- return await tool.execute(toolCallId, args, signal, onUpdate);
- } finally {
- planner.settle(key);
- }
- },
- };
++ return { ...tool, execute: async (id, args, signal, update) => {
++ try {
++ await planner.waitForTurn(args as object, signal);
++ return await planner.execute(args as object, () => tool.execute(id, args, signal, update));
++ } finally { await planner.settle(args as object); }
++ } };
+}
diff --cc packages/agent-runtime/src/context-usage-compaction.test.ts
index 000000000,9a419aa55..cce3bcdad
mode 000000,100644..100644
--- a/packages/agent-runtime/src/context-usage-compaction.test.ts
+++ b/packages/agent-runtime/src/context-usage-compaction.test.ts
@@@ -1,0 -1,165 +1,166 @@@
+ import { createServer, type ServerResponse } from "node:http";
+ import { afterEach, describe, expect, it } from "vitest";
+ import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
+ import { DesktopAgentRuntime } from "./runtime.js";
+ import type { RuntimeProviderConfig } from "./provider-binding.js";
+
+ type WireRequest = { input: unknown[] };
+ type WireUsage = {
+ input_tokens: number;
+ output_tokens: number;
+ total_tokens: number;
+ input_tokens_details?: { cached_tokens: number };
+ };
+ const highUsage: WireUsage = {
+ input_tokens: 80_000, output_tokens: 100, total_tokens: 20_100,
+ input_tokens_details: { cached_tokens: 60_000 },
+ };
+ const cleanups: Array<() => Promise<void>> = [];
+
+ afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+ });
+
+ function respond(response: ServerResponse, requestNumber: number, usage: WireUsage, toolFirst: boolean): void {
+ const text = `Fixture reply ${requestNumber}`;
+ const tool = toolFirst && requestNumber === 1;
+ const args = JSON.stringify({ path: "fixture.txt" });
+ const item = tool
+ ? { id: `item-${requestNumber}`, type: "function_call", call_id: `call-${requestNumber}`,
+ name: "Read", arguments: args, status: "completed" }
+ : { id: `message-${requestNumber}`, type: "message", role: "assistant", status: "completed",
+ content: [{ type: "output_text", text, annotations: [] }] };
+ const events = [
+ { type: "response.created", response: { id: `response-${requestNumber}` } },
+ { type: "response.output_item.added", output_index: 0,
+ item: tool ? { ...item, arguments: "", status: "in_progress" } : { ...item, content: [], status: "in_progress" } },
+ tool
+ ? { type: "response.function_call_arguments.delta", output_index: 0, delta: args }
+ : { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: text },
+ { type: "response.output_item.done", output_index: 0, item },
+ {
+ type: "response.completed",
+ response: {
+ id: `response-${requestNumber}`, status: "completed", output: [item],
+ usage: requestNumber === 1 ? usage : { input_tokens: 10, output_tokens: 1, total_tokens: 11 },
+ },
+ },
+ ];
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""));
+ }
+
+ async function fixture(history: UiMessage[] = [], usage: WireUsage = highUsage, toolFirst = false) {
+ const requests: WireRequest[] = [];
+ const timeline: string[] = [];
+ const events: AgentEventEnvelope[] = [];
+ const server = createServer(async (request, response) => {
+ let raw = "";
+ for await (const chunk of request) raw += chunk;
+ requests.push(JSON.parse(raw) as WireRequest);
+ timeline.push(`request:${requests.length}`);
+ respond(response, requests.length, usage, toolFirst);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ cleanups.push(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing fixture address");
+ const baseUrl = `http://127.0.0.1:${address.port}/v1`;
+ const provider: RuntimeProviderConfig = {
+ id: "fixture", name: "Fixture", baseUrl, modelId: "fixture-model", apiKey: "fixture-only",
+ apiStyle: "responses", supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: {
+ source: "generic", name: "Fixture model", baseUrl, reasoning: false, input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 100_000, maxTokens: 8_192,
+ },
+ };
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "usage-fixture", mode: "agent", provider, history, thinkingLevel: "off",
+ compactionStrategy: "fresh_window",
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ host: {
+ call: async <T>(method: string): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
+ if (method === "session.appendCompaction") timeline.push("checkpoint");
+ else if (method === "tools.execute") {
+ timeline.push("tool");
+ return { ok: true, content: "Fixture result." } as T;
+ } else if (method !== "session.appendMessage") throw new Error(`Unexpected host method: ${method}`);
+ return undefined as T;
+ },
+ onNotification: () => () => {},
+ },
+ onEvent: (event) => events.push(event),
+ });
+ cleanups.push(async () => { await runtime.dispose(); });
+ return { runtime, requests, timeline, events };
+ }
+
+ describe("reported context occupancy and compaction", () => {
+ it("compacts before a new request when cached input is absent from the reported total", async () => {
+ const f = await fixture();
+ await f.runtime.prompt("Start the task.", "user-1", "turn-1");
+ const first = f.events.find(({ event }) => event.type === "message_end" && event.message.role === "assistant");
+ expect(first?.event).toMatchObject({ type: "message_end", message: { usage: {
+ inputTokens: 20_000, outputTokens: 100, cacheReadTokens: 60_000, totalTokens: 20_100,
+ } } });
+
+ await f.runtime.prompt("Continue the task.", "user-2", "turn-2");
+
+ expect(f.timeline).toEqual(["request:1", "checkpoint", "request:2"]);
+ expect(f.events.some(({ event }) => event.type === "compaction_end" && event.ok)).toBe(true);
+ expect(JSON.stringify(f.requests[1].input)).toContain("Continue the task.");
+ });
+
+ it("uses the same occupancy after restoring a session", async () => {
+ const f = await fixture([
+ { id: "old-user", role: "user", content: "Previous task.", createdAt: "2026-10-01T00:00:00Z" },
+ { id: "old-answer", role: "assistant", content: "Previous response.", status: "complete",
+ createdAt: "2026-10-01T00:00:01Z", usage: {
+ inputTokens: 20_000, outputTokens: 100, cacheReadTokens: 60_000, totalTokens: 20_100,
+ } },
+ ]);
+
+ await f.runtime.prompt("Continue the restored task.", "new-user", "new-turn");
+
+ expect(f.timeline).toEqual(["checkpoint", "request:1"]);
+ expect(f.events.some(({ event }) => event.type === "compaction_end" && event.ok)).toBe(true);
+ expect(JSON.stringify(f.requests[0].input)).toContain("Continue the restored task.");
+ });
+
+ it("compacts between a tool result and the next provider request", async () => {
+ const f = await fixture([], highUsage, true);
+
+ await f.runtime.prompt("Read the fixture.", "user-1", "turn-1");
+
+ expect(f.timeline).toEqual(["request:1", "tool", "checkpoint", "request:2"]);
+ expect(f.events.some(({ event }) => event.type === "compaction_end" && event.ok)).toBe(true);
+ });
+
+ it("does not compact an under-budget request with consistent usage", async () => {
+ const f = await fixture([], {
+ input_tokens: 4_000, output_tokens: 10, total_tokens: 4_010,
+ input_tokens_details: { cached_tokens: 2_000 },
+ });
+
+ await f.runtime.prompt("Start the task.", "user-1", "turn-1");
+ await f.runtime.prompt("Continue the task.", "user-2", "turn-2");
+
+ expect(f.timeline).toEqual(["request:1", "request:2"]);
+ expect(f.events.some(({ event }) => event.type === "compaction_start")).toBe(false);
+ });
+
+ it("still compacts when only a partial bucket breakdown accompanies the total", async () => {
+ const f = await fixture([], { input_tokens: 0, output_tokens: 10, total_tokens: 80_000 });
+
+ await f.runtime.prompt("Start the task.", "user-1", "turn-1");
+ await f.runtime.prompt("Continue the task.", "user-2", "turn-2");
+
+ expect(f.timeline).toEqual(["request:1", "checkpoint", "request:2"]);
+ expect(f.events.some(({ event }) => event.type === "compaction_end" && event.ok)).toBe(true);
+ });
+ });
diff --cc packages/agent-runtime/src/extensions/context-event.test.ts
index 27d9e7fd9,27d9e7fd9..fe84757da
--- a/packages/agent-runtime/src/extensions/context-event.test.ts
+++ b/packages/agent-runtime/src/extensions/context-event.test.ts
@@@ -47,6 -47,6 +47,7 @@@ it("emits context before every provide
runtime = new DesktopAgentRuntime({
host: {
call: async <T>(method: string, params?: unknown): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") {
persisted.push((params as { message: unknown }).message);
return undefined as T;
diff --cc packages/agent-runtime/src/extensions/prompt-chain.test.ts
index 711a95059,711a95059..91b27b4ea
--- a/packages/agent-runtime/src/extensions/prompt-chain.test.ts
+++ b/packages/agent-runtime/src/extensions/prompt-chain.test.ts
@@@ -42,6 -42,6 +42,7 @@@ it.each(
runtime = new DesktopAgentRuntime({
host: {
call: async <T>(method: string): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") return undefined as T;
throw new Error(`Unexpected host call: ${method}`);
},
diff --cc packages/agent-runtime/src/fixed-tool-runtime.test.ts
index c160f2697,c160f2697..7aaf1873a
--- a/packages/agent-runtime/src/fixed-tool-runtime.test.ts
+++ b/packages/agent-runtime/src/fixed-tool-runtime.test.ts
@@@ -52,6 -52,6 +52,7 @@@ function runtimeFixture(history: UiMess
sessionId: "fixed-tools", mode, provider, thinkingLevel: "off", history: rows, pluginTools: tools,
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
host: { call: async <T>(method: string, params?: unknown): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") rows.push((params as { message: UiMessage }).message);
else if (method === "tools.execute") {
executed.push((params as { toolName: string }).toolName);
diff --cc packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts
index 2cfe343c3,2cfe343c3..8cf251900
--- a/packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts
+++ b/packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts
@@@ -52,6 -52,6 +52,7 @@@ async function writeThrough(args: Recor
visualizationsDir: DIR,
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
host: { call: async <T>(method: string, params?: unknown): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") rows.push((params as { message: UiMessage }).message);
else if (method === "tools.execute") {
return (hostOk ? { ok: true, content: "Wrote file" } : { ok: false, content: "EACCES" }) as T;
diff --cc packages/agent-runtime/src/mode-tool-access.test.ts
index 042010e7e,042010e7e..187eefc62
--- a/packages/agent-runtime/src/mode-tool-access.test.ts
+++ b/packages/agent-runtime/src/mode-tool-access.test.ts
@@@ -81,6 -81,6 +81,7 @@@ it.each(
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
subagents: [{ name: "worker", description: "Inspect", tools: ["Read"], prompt: "Inspect only.", source: "user" }],
host: { call: async <T>(method: string): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") return undefined as T;
hostCalls.push(method); throw new Error("blocked tools must never reach the host");
}, onNotification: () => () => {} },
diff --cc packages/agent-runtime/src/output-cap-request.test.ts
index d1b522518,d1b522518..7cf491b68
--- a/packages/agent-runtime/src/output-cap-request.test.ts
+++ b/packages/agent-runtime/src/output-cap-request.test.ts
@@@ -119,6 -119,6 +119,7 @@@ describe("output budget with supersede
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
host: {
call: async <T>(method: string): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") return undefined as T;
throw new Error(`Unexpected host method: ${method}`);
},
diff --cc packages/agent-runtime/src/provider-certificate-flow.test.ts
index c3f0d8911,c3f0d8911..438eacc4d
--- a/packages/agent-runtime/src/provider-certificate-flow.test.ts
+++ b/packages/agent-runtime/src/provider-certificate-flow.test.ts
@@@ -30,6 -30,6 +30,7 @@@ it.each(["session", "delegate"])
sessionId: "certificate-session", mode: "agent", provider,
thinkingLevel: "off", onEvent,
host: { call: async <T>(method: string): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") return undefined as T;
throw new Error("Unexpected host request");
} },
diff --cc packages/agent-runtime/src/provider-recovery-flow.test.ts
index b700b0552,b700b0552..bdc767516
--- a/packages/agent-runtime/src/provider-recovery-flow.test.ts
+++ b/packages/agent-runtime/src/provider-recovery-flow.test.ts
@@@ -100,6 -100,6 +100,7 @@@ function fixture(steps: Step[], retryAf
},
host: {
async call<T>(method: string): Promise<T> {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") return undefined as T;
if (method !== "tools.execute")
throw new Error(`Unexpected host method: ${method}`);
diff --cc packages/agent-runtime/src/read-only-stop.test.ts
index d7e9c3087,d7e9c3087..9957f5128
--- a/packages/agent-runtime/src/read-only-stop.test.ts
+++ b/packages/agent-runtime/src/read-only-stop.test.ts
@@@ -46,6 -46,6 +46,7 @@@ function fixture(toolName: ToolName)
supportsReasoning: false, supportedThinkingLevels: ["off"] },
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
host: { async call<T>(method: string): Promise<T> {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "tools.execute") { started.resolve(); return await execution.promise as T; }
if (method === "tools.abort") { abortRequested.resolve(); return await cancellation.promise as T; }
if (method === "session.appendMessage" || method === "project.instructions.resolve") return undefined as T;
diff --cc packages/agent-runtime/src/runtime.test.ts
index a17c4dd77,ff92c5cb0..2f622b309
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@@ -1,4 -1,4 +1,4 @@@
--import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
++import { link, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi, beforeEach } from "vitest";
@@@ -424,146 -423,6 +424,198 @@@ describe("ordered read preparation", (
});
});
+function toolCall(id: string, name: string, args: Record<string, unknown>) {
+ return { type: "toolCall", id, name, arguments: args };
+}
+
+/**
+ * pi stream that answers each request with the next scripted tool batch and,
+ * once the script runs out, a final text reply. Records every request.
+ */
+function scriptedStream(batches: unknown[][], requests: AgentMessage[][] = []) {
+ let turn = 0;
+ return (_model: unknown, context: { messages: AgentMessage[] }) => {
+ requests.push([...context.messages]);
+ const calls = batches[turn++];
+ const reason = calls ? "toolUse" : "stop";
+ const message = assistantMessage({
+ content: calls ?? [{ type: "text", text: "done" }],
+ stopReason: reason,
+ }) as AssistantMessage;
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message });
+ stream.push({ type: "done", reason, message });
+ stream.end(message);
+ });
+ return stream;
+ };
+}
+
+/** Host whose `tools.execute` responses are held until the test releases them. */
- function gatedHost() {
++function gatedHost(fileBatches = false) {
+ const entered: string[] = [];
+ const release = new Map<string, (result: unknown) => void>();
++ // External Host fixture with declared virtual identities. Real filesystem
++ // identity/admission is covered by Rust and the real-Host E2E suite.
++ const tickets = new Map<string, { batch: string; id: string; name: string; path: string;
++ tree: boolean; write: boolean; submitted: boolean; done: Promise<void>; finish: () => void }>();
++ const aborted = new Set<string>();
++ let draining = false;
+ const host = {
+ call: vi.fn(async (method: string, args: any) => {
+ if (method === "project.instructions.resolve") return { entries: [] };
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: fileBatches };
++ if (method === "tools.fileBatchRegister") {
++ const ticket = `ticket-${tickets.size}`;
++ let finish = () => {};
++ const done = new Promise<void>((resolve) => { finish = resolve; });
++ tickets.set(ticket, { batch: args.batchId, id: args.toolCallId, name: args.toolName,
++ path: String(args.args.path ?? "").replace(/^\/root\//, "").replace(/^\.\//, ""),
++ tree: ["Glob", "Grep"].includes(args.toolName) || /^(?:MV|REM)\b|@/m.test(args.args.ops ?? ""),
++ write: ["Write", "Edit"].includes(args.toolName), submitted: false, done, finish });
++ return { ticket };
++ }
++ if (method === "tools.fileBatchAbandon") {
++ const slot = tickets.get(args.ticket);
++ if (slot && !slot.submitted) slot.finish();
++ return { ok: true };
++ }
++ if (method === "tools.fileBatchClose") {
++ for (const slot of tickets.values()) if (slot.batch === args.batchId && !slot.submitted) slot.finish();
++ return { ok: true };
++ }
++ if (method === "tools.fileBatchSeal") return { ok: true };
++ if (method === "tools.abort") {
++ aborted.add(args.toolCallId);
++ const result = { ok: false, content: "TOOL_ABORTED", errorCode: "TOOL_ABORTED" };
++ release.get(args.toolCallId)?.(result);
++ for (const slot of tickets.values()) if (slot.id === args.toolCallId) slot.finish();
++ return { ok: true };
++ }
+ if (method !== "tools.execute") return undefined;
++ const slot = tickets.get(args.fileBatchTicket);
++ if (slot) {
++ slot.submitted = true;
++ const predecessors = [];
++ for (const prior of tickets.values()) {
++ if (prior === slot) break;
++ if (prior.batch === slot.batch && (prior.write || slot.write)
++ && (prior.tree || slot.tree || prior.path === slot.path)) predecessors.push(prior.done);
++ }
++ await Promise.all(predecessors);
++ }
++ if (aborted.has(args.toolCallId)) return { ok: false, content: "TOOL_ABORTED", errorCode: "TOOL_ABORTED" };
++ if (draining) return { ok: true, content: "cleanup" };
+ entered.push(args.toolCallId);
- return new Promise((resolve) => release.set(args.toolCallId, resolve));
++ try { return await new Promise((resolve) => release.set(args.toolCallId, resolve)); }
++ finally { slot?.finish(); }
+ }),
+ };
+ const finish = (id: string, result: unknown = { ok: true, content: id }) => release.get(id)!(result);
- const drain = () => { for (const resolve of release.values()) resolve({ ok: true, content: "cleanup" }); };
++ const drain = () => {
++ draining = true;
++ for (const resolve of release.values()) resolve({ ok: true, content: "cleanup" });
++ for (const slot of tickets.values()) slot.finish();
++ };
+ return { host, entered, finish, drain };
+}
+
+function toolResults(request: AgentMessage[]) {
+ return request
+ .filter((message) => message.role === "toolResult")
+ .map((message: any) => ({
+ id: message.toolCallId as string,
+ isError: message.isError as boolean,
+ text: JSON.stringify(message.content),
+ }));
+}
+
+describe("batch turn release", () => {
+ it("releases a parent call that fails argument checks before reaching the Host", async () => {
+ const { host, entered, finish, drain } = gatedHost();
+ const requests: AgentMessage[][] = [];
+ const runtime = createRuntime({ host, projectPath: "/root" });
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ // Grep without `pattern` passes the schema (the alias makes it optional)
+ // and then throws in execute; the Write is ordered behind its tree claim.
+ toolCall("grep", "Grep", { path: "src" }),
+ toolCall("write", "Write", { path: "x.txt", content: "x" }),
+ ]], requests) };
+ try {
+ const pending = runtime.prompt("Search, then write.");
+ await vi.waitFor(() => expect(entered).toEqual(["write"]));
+ finish("write");
+ await pending;
+ const results = toolResults(requests[1]);
+ expect(results.map(({ id, isError }) => [id, isError])).toEqual([["grep", true], ["write", false]]);
+ expect(results[0].text).toContain("`pattern` is required");
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+
+ it("releases a parent call rejected by the mode guard after a mid-turn mode switch", async () => {
+ const { host, entered, finish, drain } = gatedHost();
+ const requests: AgentMessage[][] = [];
+ const runtime = createRuntime({ host, projectPath: "/root" });
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ toolCall("read-1", "Read", { path: "x.txt" }),
+ toolCall("write", "Write", { path: "x.txt", content: "x" }),
+ toolCall("read-2", "Read", { path: "x.txt" }),
+ ]], requests) };
+ try {
+ const pending = runtime.prompt("Read, write, read.");
+ await vi.waitFor(() => expect(entered).toEqual(["read-1"]));
+ runtime.setMode("plan");
+ finish("read-1");
+ await vi.waitFor(() => expect(entered).toEqual(["read-1", "read-2"]));
+ finish("read-2");
+ await pending;
+ const results = toolResults(requests[1]);
+ expect(results.map(({ id, isError }) => [id, isError])).toEqual([
+ ["read-1", false], ["write", true], ["read-2", false],
+ ]);
+ expect(results[1].text).toContain("not allowed in plan");
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+
+ it("releases a delegate call that fails argument checks before reaching the Host", async () => {
+ const { SubagentRun: RealSubagentRun } = await vi.importActual<typeof import("./subagent.js")>("./subagent.js");
+ const { host, entered, finish, drain } = gatedHost();
+ const writer = { name: "writer", description: "Write", tools: ["Grep", "Write"], prompt: "Write", source: "builtin" as const };
+ const runtime = createRuntime({ host, projectPath: "/root", subagents: [writer] });
+ subagentRuns.calls.length = 0;
+ try {
+ await runtimeTool(runtime, "Task").execute("task-writer", { agent: "writer", task: "Search, then write." });
+ const options = subagentRuns.calls[0];
+ const child = new RealSubagentRun({ ...options, signal: undefined }) as unknown as {
+ agent: { streamFunction: unknown };
+ run: () => Promise<{ status: string }>;
+ };
+ const requests: AgentMessage[][] = [];
+ child.agent.streamFunction = scriptedStream([[
+ toolCall("child-grep", "Grep", { path: "src" }),
+ toolCall("child-write", "Write", { path: "x.txt", content: "x" }),
+ ]], requests);
+ const running = child.run();
+ await vi.waitFor(() => expect(entered).toEqual(["child-write"]));
+ finish("child-write");
+ await expect(running).resolves.toMatchObject({ status: "completed" });
+ expect(toolResults(requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["child-grep", true], ["child-write", false],
+ ]);
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+});
+
/** Minimal pi-ai assistant message; overrides carry the shape under test. */
function assistantMessage(overrides: {
content: unknown[];
@@@ -590,224 -449,6 +642,247 @@@
};
}
+describe("parallel file batches", () => {
++ it.each([false, true])("keeps hard-link aliases ordered without Host identity support (write first: %s)", async (writeFirst) => {
++ const root = await mkdtemp(join(tmpdir(), "pi-batch-alias-"));
++ await writeFile(join(root, "actual.txt"), "before");
++ await link(join(root, "actual.txt"), join(root, "alias.txt"));
++ const calls = [
++ toolCall("read-alias", "Read", { path: "alias.txt" }),
++ toolCall("write-actual", "Write", { path: "actual.txt", content: "after" }),
++ ];
++ if (writeFirst) calls.reverse();
++ const batch = startBatch(calls, { projectPath: root, fileBatches: false });
++ try {
++ await vi.waitFor(() => expect(batch.entered).toContain(calls[0].id));
++ await new Promise((resolve) => setTimeout(resolve, 0));
++ expect(batch.entered).toEqual([calls[0].id]);
++ batch.finish(calls[0].id);
++ await vi.waitFor(() => expect(batch.entered).toEqual(calls.map((call) => call.id)));
++ batch.finish(calls[1].id);
++ await batch.pending;
++ } finally {
++ await cleanup(batch);
++ await rm(root, { recursive: true, force: true });
++ }
++ });
+ /** Starts a parent turn whose first request returns `calls` as one batch. */
- function startBatch(calls: unknown[], options: { projectPath?: string } = {}) {
- const gate = gatedHost();
++ function startBatch(calls: unknown[], options: { projectPath?: string; fileBatches?: boolean } = {}) {
++ const gate = gatedHost(options.fileBatches ?? true);
+ const requests: AgentMessage[][] = [];
+ const events: any[] = [];
+ const runtime = createRuntime({
+ host: gate.host,
+ projectPath: options.projectPath ?? "/root",
+ onEvent: (envelope) => { events.push((envelope as any).event); },
+ });
+ (runtime as any).models = { streamSimple: scriptedStream([calls], requests) };
+ const pending = runtime.prompt("Run the file batch.");
+ return { ...gate, runtime, requests, events, pending };
+ }
+
+ async function cleanup(batch: ReturnType<typeof startBatch>) {
- await batch.runtime.abort();
+ batch.drain();
++ await batch.runtime.abort();
+ await batch.pending.catch(() => undefined);
+ await batch.runtime.dispose();
+ }
+
+ const editOps = { tag: "ABCD", ops: "PUT 1.=1:\n+x" };
+
+ it("starts [Read a, Read b, Read c, Edit d] together and keeps source-order results", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("read-b", "Read", { path: "b.ts" }),
+ toolCall("read-c", "Read", { path: "c.ts" }),
+ toolCall("edit-d", "Edit", { path: "d.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["edit-d", "read-a", "read-b", "read-c"]));
+ for (const id of ["edit-d", "read-c", "read-b", "read-a"]) {
+ batch.finish(id);
+ await Promise.resolve();
+ }
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id }) => id)).toEqual(["read-a", "read-b", "read-c", "edit-d"]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("holds only Edit a behind Read a in [Read a, Edit a, Read b, Write c]", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ toolCall("read-b", "Read", { path: "b.ts" }),
+ toolCall("write-c", "Write", { path: "c.ts", content: "c" }),
+ ]);
+ try {
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["read-a", "read-b", "write-c"]));
+ batch.finish("read-b");
+ batch.finish("write-c");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(batch.entered).not.toContain("edit-a");
+ batch.finish("read-a");
+ await vi.waitFor(() => expect(batch.entered.at(-1)).toBe("edit-a"));
+ batch.finish("edit-a");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id }) => id)).toEqual(["read-a", "edit-a", "read-b", "write-c"]);
+ } finally { await cleanup(batch); }
+ });
+
+ it.each([
+ ["[Write x, Grep]", [
+ toolCall("first", "Write", { path: "x.ts", content: "x" }),
+ toolCall("second", "Grep", { pattern: "foo" }),
+ ]],
+ ["[Edit a with MV, Read b]", [
+ toolCall("first", "Edit", { path: "a.ts", tag: "ABCD", ops: "MV moved.ts" }),
+ toolCall("second", "Read", { path: "b.ts" }),
+ ]],
+ ["[Edit a with CUT @r, Edit b with PUT @r] (named register)", [
+ toolCall("first", "Edit", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @r" }),
+ toolCall("second", "Edit", { path: "b.ts", tag: "ABCD", ops: "PUT <1 @r" }),
+ ]],
- ["[Read x/a.ts, Write y/a.ts] (basename fallback)", [
- toolCall("first", "Read", { path: "x/a.ts" }),
- toolCall("second", "Write", { path: "y/a.ts", content: "a" }),
++ ["[Read ./a.ts, Write a.ts] (Host-declared identity)", [
++ toolCall("first", "Read", { path: "./a.ts" }),
++ toolCall("second", "Write", { path: "a.ts", content: "a" }),
+ ]],
+ ] as const)("keeps %s in source order", async (_label, calls) => {
+ const batch = startBatch([...calls]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first"]));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(batch.entered).toEqual(["first"]);
+ batch.finish("first");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first", "second"]));
+ batch.finish("second");
+ await batch.pending;
+ } finally { await cleanup(batch); }
+ });
+
- it("orders an absolute and a workspace-relative spelling of one file by its full key", async () => {
++ it("sends absolute and relative spellings to the Host without inventing file identities", async () => {
+ const register = vi.spyOn(BatchPlanner.prototype, "register");
+ const batch = startBatch([
+ toolCall("first", "Read", { path: "/root/a.ts" }),
+ toolCall("second", "Write", { path: "a.ts", content: "a" }),
+ ], { projectPath: "/root" });
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first"]));
- // The keys match in full, not only through the basename fallback.
- expect(register.mock.calls.map(([, , claims]) => claims)).toEqual([
- [{ kind: "path", key: "/root/a.ts", access: "shared" }],
- [{ kind: "path", key: "/root/a.ts", access: "exclusive" }],
++ expect(register.mock.calls.map(([, , call]) => call)).toMatchObject([
++ { toolName: "Read", ordinal: 0, args: { path: "/root/a.ts" } },
++ { toolName: "Write", ordinal: 1, args: { path: "a.ts" } },
+ ]);
+ batch.finish("first");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first", "second"]));
+ batch.finish("second");
+ await batch.pending;
+ } finally {
+ register.mockRestore();
+ await cleanup(batch);
+ }
+ });
+
+ it("aborts an Edit still waiting behind a running Read without reaching the Host", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a"]));
+ await batch.runtime.abort();
+ await batch.pending.catch(() => undefined);
+ expect(batch.entered).toEqual(["read-a"]);
+ const edit = batch.events.find((event) => event.type === "tool_end" && event.toolCallId === "edit-a");
+ expect(edit.isError).toBe(true);
- // The TOOL_ABORTED error thrown before the Host call; pi keeps its message.
- expect(JSON.stringify(edit.result)).toContain("tool execution aborted before it started");
++ expect(JSON.stringify(edit.result)).toContain("TOOL_ABORTED");
+ } finally { await cleanup(batch); }
+ });
+
+ it("still runs Edit a after Read a fails", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a"]));
+ batch.finish("read-a", { ok: false, content: "FILE_NOT_FOUND" });
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a", "edit-a"]));
+ batch.finish("edit-a");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["read-a", true], ["edit-a", false],
+ ]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("keeps a denied Write from affecting its same-batch sibling", async () => {
+ const batch = startBatch([
+ toolCall("write-a", "Write", { path: "a.ts", content: "a" }),
+ toolCall("write-b", "Write", { path: "b.ts", content: "b" }),
+ ]);
+ try {
+ // Both reach the Host before either result returns.
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["write-a", "write-b"]));
+ batch.finish("write-a", { ok: false, denied: true, content: "Permission denied by the user." });
+ batch.finish("write-b");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["write-a", true], ["write-b", false],
+ ]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("orders a delegate's [Read a, Edit a, Write b] without touching a concurrent parent batch", async () => {
+ const { SubagentRun: RealSubagentRun } = await vi.importActual<typeof import("./subagent.js")>("./subagent.js");
+ const writer = { name: "writer", description: "Edit", tools: ["Read", "Edit", "Write"], prompt: "Edit", source: "builtin" as const };
- const gate = gatedHost();
++ const gate = gatedHost(true);
+ const runtime = createRuntime({ host: gate.host, projectPath: "/root", subagents: [writer] });
++ (runtime as any).models = { streamSimple: scriptedStream([], []) };
++ await runtime.prompt("Initialize Host capabilities.");
+ const parentRequests: AgentMessage[][] = [];
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ toolCall("parent-read", "Read", { path: "p.ts" }),
+ toolCall("parent-write", "Write", { path: "q.ts", content: "q" }),
+ ]], parentRequests) };
+ subagentRuns.calls.length = 0;
+ let parent: Promise<unknown> | undefined;
+ try {
+ await runtimeTool(runtime, "Task").execute("task-writer", { agent: "writer", task: "Edit a." });
+ const child = new RealSubagentRun({ ...subagentRuns.calls[0], signal: undefined }) as unknown as {
+ agent: { streamFunction: unknown };
+ run: () => Promise<{ status: string }>;
+ };
+ const childRequests: AgentMessage[][] = [];
+ child.agent.streamFunction = scriptedStream([[
+ toolCall("child-read-a", "Read", { path: "a.ts" }),
+ toolCall("child-edit-a", "Edit", { path: "a.ts", ...editOps }),
+ toolCall("child-write-b", "Write", { path: "b.ts", content: "b" }),
+ ]], childRequests);
+ parent = runtime.prompt("Read and write in the parent.");
+ await vi.waitFor(() => expect([...gate.entered].sort()).toEqual(["parent-read", "parent-write"]));
+ const running = child.run();
+ await vi.waitFor(() => expect(gate.entered.slice(2).sort()).toEqual(["child-read-a", "child-write-b"]));
+ gate.finish("child-write-b");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(gate.entered).not.toContain("child-edit-a");
+ gate.finish("child-read-a");
+ // The child Edit waits only for its own batch's Read; the parent batch is still held.
+ await vi.waitFor(() => expect(gate.entered.at(-1)).toBe("child-edit-a"));
+ gate.finish("child-edit-a");
+ await expect(running).resolves.toMatchObject({ status: "completed" });
+ expect(toolResults(childRequests[1]).map(({ id }) => id)).toEqual(["child-read-a", "child-edit-a", "child-write-b"]);
+ gate.finish("parent-read");
+ gate.finish("parent-write");
+ await parent;
+ expect(toolResults(parentRequests[1]).map(({ id }) => id)).toEqual(["parent-read", "parent-write"]);
+ } finally {
+ await runtime.abort();
+ gate.drain();
+ await parent?.catch(() => undefined);
+ await runtime.dispose();
+ }
+ });
+});
+
describe("Task/read batch execution policy", () => {
const message = (...names: string[]) => assistantMessage({
content: names.map((name, index) => ({
@@@ -9251,7 -9020,7 +9500,10 @@@ describe("DesktopAgentRuntime subagents
try {
await taskTool(runtime).execute("granted", { agent: "explorer", task: "Search.", model: "new/new-model" });
expect(subagentRuns.calls).toHaveLength(1);
-- host.call.mockRejectedValue(new Error("model is not enabled for delegation"));
++ host.call.mockImplementation(async (method: string) => {
++ if (method === "provider.resolveSubagentModel") throw new Error("model is not enabled for delegation");
++ return undefined;
++ });
expect(runtimeMatches(runtime)).toBe(true);
await runtime.prompt("Search again.");
const denied = await taskTool(runtime).execute("revoked", { agent: "explorer", task: "Search.", model: "new/new-model" });
@@@ -9263,7 -9032,7 +9515,8 @@@
it("discards an on-demand grant returned after its prompt ended (#841)", async () => {
let resolveGrant: (value: RuntimeProviderConfig) => void = () => {};
-- const host = { call: vi.fn().mockImplementation(() => new Promise<RuntimeProviderConfig>((resolve) => { resolveGrant = resolve; })) };
++ const host = { call: vi.fn().mockImplementation((method: string) => method === "provider.resolveSubagentModel"
++ ? new Promise<RuntimeProviderConfig>((resolve) => { resolveGrant = resolve; }) : Promise.resolve(undefined)) };
const runtime = createRuntime({ subagents: [explorer], host });
const agent = (runtime as unknown as { agent: Agent }).agent;
vi.spyOn(agent, "prompt").mockResolvedValue();
@@@ -9283,7 -9052,7 +9536,7 @@@
} finally { await runtime.dispose(); }
});
- it("allows only Task and file tools to run in parallel", async () => {
- it("allows only Task and read/search tools to run in parallel", async () => {
++ it("keeps Write/Edit sequential until Host file batch support is negotiated", async () => {
const runtime = createRuntime({ subagents: [explorer] });
const catalog = (runtime as any).toolCatalog as Map<string, any>;
diff --cc packages/agent-runtime/src/runtime.ts
index 4e6711515,3d393e7be..5f75e5892
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@@ -5,8 -5,7 +5,8 @@@ import
} from "./mutation-recovery.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
import { resolveMcpToolSelection } from "./mcp-tool-selection.js";
-import { toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
+import { BatchPlanner, withBatchTurn } from "./batch-planner.js";
- import { TOOL_EXECUTION_SPECS, toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
++import { TOOL_EXECUTION_SPECS, resolveBatchExecutionMode, toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
import { AsyncLocalStorage } from "node:async_hooks";
import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";
import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";
@@@ -1928,8 -1931,6 +1932,8 @@@ export class DesktopAgentRuntime
private delegateWorktrees = new Map<string, string>();
/** Serializes same-path mutations across the parent and its delegates. */
private writeLocks = new PathMutex();
+ /** Orders one parallel batch's calls by the resources they claim. */
- private batchPlanner = new BatchPlanner();
++ private batchPlanner: BatchPlanner;
/** Complete tool registry; only the active subset is sent to the provider. */
private toolCatalog = new Map<string, AgentTool>();
/** Tools intentionally omitted from the initial provider request. */
@@@ -2120,6 -2121,6 +2124,7 @@@
this.fastMode = opts.fastMode === true;
this.jevApiKey = opts.jevApiKey;
this.host = opts.host;
++ this.batchPlanner = new BatchPlanner(this.host, this.sessionId);
this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
this.hostCloseUnsubscribe = this.host.onClose?.(() => {
this.cleanupActiveToolProgress();
@@@ -2721,7 -2722,6 +2726,7 @@@ Do not invent objections or turn specul
const blocked = await this.extensionToolCall(context);
if (blocked?.block) return blocked;
await this.preparePathToolCall(context);
- this.registerBatchCall(context);
++ await this.registerBatchCall(context);
return undefined;
}
const enterKind = enterToolKind(context.toolCall.name);
@@@ -3675,6 -3675,6 +3680,7 @@@
toolCallId,
toolName,
args: params,
++ ...(this.batchPlanner.ticket(toolCallId) ? { fileBatchTicket: this.batchPlanner.ticket(toolCallId) } : {}),
mode: this.mode,
...(isBash
? {
@@@ -3978,13 -3978,13 +3984,13 @@@
// Direct/internal invocations retain preflight. pi invocations have
// already committed instructions in the ordered preparation phase.
if (!prepared) await this.loadPathInstructions(toolName, params, this.instructionExecution.getStore());
-- if (PATH_MUTATING_TOOLS.has(toolName)) {
++ if (!this.batchPlanner.supported && PATH_MUTATING_TOOLS.has(toolName)) {
return this.writeLocks.run(
this.pathLockKey(toolCallId, params),
() => run(toolCallId, params, signal, onUpdate),
);
}
-- if (toolName === "Read") {
++ if (!this.batchPlanner.supported && toolName === "Read") {
return this.writeLocks.read(
this.pathLockKey(toolCallId, params),
() => run(toolCallId, params, signal, onUpdate),
@@@ -4180,17 -4179,14 +4186,17 @@@
// every tool, so the session agent and a delegated `Task` run send the
// same declaration (#864).
const builtin = this.builtinTools.has(tool);
+ const guarded = withModeExecutionGuard(
+ withExplicitRequired({
+ ...tool,
- executionMode: builtin ? toolExecutionMode(tool.name) : "sequential",
++ executionMode: builtin ? toolExecutionMode(tool.name, this.batchPlanner.supported) : "sequential",
+ }),
+ () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),
+ );
+ // Batch ordering wraps the mode guard: a call the guard rejects must
+ // still release the calls ordered behind it in its batch.
const catalogTool = withDynamicTaskExecutionMode(
- builtin && TOOL_EXECUTION_SPECS[tool.name]?.claims ? withBatchTurn(guarded, this.batchPlanner) : guarded,
- withModeExecutionGuard(
- withExplicitRequired({
- ...tool,
- executionMode: builtin ? toolExecutionMode(tool.name) : "sequential",
- }),
- () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),
- ),
++ builtin && TOOL_EXECUTION_SPECS[tool.name]?.file ? withBatchTurn(guarded, this.batchPlanner) : guarded,
() => this.agent?.state.messages.at(-1),
);
if (builtin) this.builtinTools.add(catalogTool);
@@@ -5137,10 -5133,8 +5143,10 @@@
tools: scopedTools,
beforeToolCall: async (context) => {
await this.preparePathToolCall(context, applyInstructions, builtinToolNames);
- this.registerBatchCall(context, builtinToolNames);
++ await this.registerBatchCall(context, builtinToolNames, worktreeKey);
return undefined;
},
+ onTurnEnd: (message) => this.batchPlanner.settleBatch(message),
onEvent: (envelope) => {
this.noteDelegationActivity(record, envelope);
this.onEvent(envelope);
@@@ -6415,30 -6409,6 +6421,37 @@@
}
}
+ /**
+ * Records what a prepared builtin call will touch so the batch can order it
+ * (`withBatchTurn`). Runs after every check that can block the call. Tools
+ * without claims are sequential, or Task, whose mixed batches pi already
+ * runs sequentially.
+ */
- private registerBatchCall(
++ private async registerBatchCall(
+ context: BeforeToolCallContext,
+ builtinToolNames?: ReadonlySet<string>,
- ): void {
++ delegationId?: string,
++ ): Promise<void> {
+ const name = context.toolCall.name;
- const claims = TOOL_EXECUTION_SPECS[name]?.claims;
- if (!claims) return;
++ if (!this.batchPlanner.supported || !TOOL_EXECUTION_SPECS[name]?.file) return;
++ // pi prepares/executes sequential batches one call at a time. They must
++ // not seal a partial registration and later try to append to it.
++ const calls = context.assistantMessage.content.filter((block) => block.type === "toolCall");
++ if (resolveBatchExecutionMode(context.assistantMessage) === "sequential"
++ || calls.some((call) => context.context?.tools?.find((tool) => tool.name === call.name)?.executionMode !== "parallel")) return;
+ const selected = context.context?.tools?.find((tool) => tool.name === name);
+ const builtin = builtinToolNames ? builtinToolNames.has(name) : selected && this.builtinTools.has(selected);
+ const batch: unknown = context.assistantMessage;
+ if (!builtin || !isRecord(context.args) || !isRecord(batch)) return;
- this.batchPlanner.register(
++ await this.batchPlanner.register(
+ batch,
+ context.args,
- claims(normalizeToolParams(name, context.args), this.workspaceRoot ?? this.projectPath ?? ""),
++ { toolName: name, toolCallId: context.toolCall.id,
++ ordinal: context.assistantMessage.content.findIndex((block) => block.type === "toolCall" && block.id === context.toolCall.id),
++ args: normalizeToolParams(name, context.args), delegationId },
+ );
+ }
+
private async preparePathToolCall(
context: BeforeToolCallContext,
apply?: (instructions: ProjectInstructions | undefined) => void,
@@@ -9162,9 -9144,9 +9188,10 @@@
if (this.disposed) throw new Error("runtime disposed");
this.assertNotRunning();
const turnId = durableTurnId?.trim() || randomUUID();
-- return this.trackTurnOperation(turnId, () =>
-- this.promptTurn(input, userMessageId, turnId),
-- );
++ return this.trackTurnOperation(turnId, async () => {
++ try { return await this.promptTurn(input, userMessageId, turnId); }
++ finally { await this.batchPlanner.drain(); }
++ });
}
private async promptTurn(
@@@ -9172,6 -9154,6 +9199,9 @@@
userMessageId: string | undefined,
durableTurnId: string,
): Promise<{ turnId: string }> {
++ await this.batchPlanner.negotiate(Boolean(this.remoteWorkspace));
++ this.rebuildToolCatalog();
++ this.setAgentTools(this.activeTools());
const selectedTools = this.selectedMcpTools(input);
const modelInput = typeof input !== "string" && input.sessionMessage
? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }
diff --cc packages/agent-runtime/src/subagent.ts
index 19cbddf45,ea13c27ae..12a61c5af
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@@ -316,7 -314,7 +316,7 @@@ export class SubagentRun
...tool,
executionMode:
tool.executionMode === "parallel"
-- ? toolExecutionMode(tool.name)
++ ? toolExecutionMode(tool.name, true)
: "sequential",
},
() => this.agent?.state.messages.at(-1),
diff --cc packages/agent-runtime/src/system-transcript-runtime.test.ts
index 3e724fd13,3e724fd13..05d366211
--- a/packages/agent-runtime/src/system-transcript-runtime.test.ts
+++ b/packages/agent-runtime/src/system-transcript-runtime.test.ts
@@@ -27,6 -27,6 +27,7 @@@ function fixture(history: UiMessage[]
sessionId: "fixture", mode: "agent", provider, thinkingLevel: "off", history, pluginSkills: skills,
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
host: { call: async <T>(method: string, params?: unknown): Promise<T> => {
++ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
if (method === "session.appendMessage") {
if (persistenceFailure) throw persistenceFailure;
rows.push((params as { message: UiMessage }).message);
diff --cc packages/agent-runtime/src/tool-execution-policy.ts
index 62c9d6e3c,f04b16f0c..2fb1479b1
--- a/packages/agent-runtime/src/tool-execution-policy.ts
+++ b/packages/agent-runtime/src/tool-execution-policy.ts
@@@ -1,123 -1,58 +1,40 @@@
- /**
- * Batch policy only: this does not grant permissions or coordinate other agents.
- * Resource claims only order calls inside one assistant message; they are not a
- * cross-agent lock (`PathMutex` and host-core keep that role).
- */
-/** Batch policy only: this does not grant permissions or coordinate other agents. */
++/** Logical tool policy. Only Host can prove that file resources are independent. */
import type { AssistantMessage } from "@earendil-works/pi-ai";
- import { normalizeLockPath } from "./path-lock.js";
-
- export type ResourceAccess = "shared" | "exclusive";
- export type ResourceClaim =
- /** `key` is a {@link resourcePathKey}. */
- | { kind: "path"; key: string; access: ResourceAccess }
- /** The whole workspace. */
- | { kind: "tree"; access: ResourceAccess };
-
- export type ToolExecutionSpec = {
- /** pi batch mode; a tool missing from the table is sequential. */
- mode: "parallel" | "sequential";
- /** What one call touches, from its normalized params; parallel tools only. */
- claims?: (params: unknown, base: string) => ResourceClaim[];
- };
-export function toolExecutionMode(name: string): "parallel" | "sequential" {
- switch (name) {
- case "Read":
- case "Glob":
- case "Grep":
- case "Task":
- return "parallel";
- default:
- return "sequential";
- }
++export type ToolExecutionSpec = { mode: "parallel" | "sequential"; file?: true };
+export const TOOL_EXECUTION_SPECS: Readonly<Record<string, ToolExecutionSpec>> = {
- Read: { mode: "parallel", claims: (params, base) => pathClaim(params, base, "shared") },
- Glob: { mode: "parallel", claims: () => [{ kind: "tree", access: "shared" }] },
- Grep: { mode: "parallel", claims: () => [{ kind: "tree", access: "shared" }] },
- Write: { mode: "parallel", claims: (params, base) => pathClaim(params, base, "exclusive") },
- Edit: { mode: "parallel", claims: (params, base) => editClaims(params, base) },
- // No file claims; a Task mixed with file tools runs the whole batch
- // sequentially (`resolveBatchExecutionMode`).
++ Read: { mode: "parallel", file: true },
++ Glob: { mode: "parallel", file: true },
++ Grep: { mode: "parallel", file: true },
++ Write: { mode: "parallel", file: true },
++ Edit: { mode: "parallel", file: true },
+ Task: { mode: "parallel" },
+};
+
- export function toolExecutionMode(name: string): "parallel" | "sequential" {
++export function toolExecutionMode(name: string, hostFileBatches = false): "parallel" | "sequential" {
++ if (!hostFileBatches && (name === "Write" || name === "Edit")) return "sequential";
+ return TOOL_EXECUTION_SPECS[name]?.mode ?? "sequential";
}
- /**
- * Lexical, case-insensitive key for one path argument: relative paths join
- * `base`, absolute ones (`/x`, `C:/x`, `//server/x`) stay as they are, and
- * `.`/`..` collapse as in {@link normalizeLockPath}. No filesystem access: a
- * remote workspace has no local filesystem and preparation must not do I/O.
- * With an empty `base` a relative path stays unjoined (unlike
- * `mutationFailureKey`, which falls back to the scratch directory), so
- * relative/absolute aliases then rely on the basename fallback in `sameFile`.
- */
- export function resourcePathKey(raw: string, base: string): string {
- const path = raw.replaceAll("\\", "/");
- const absolute = path.startsWith("/") || /^[A-Za-z]:/.test(path);
- return normalizeLockPath(absolute || !base ? path : `${base}/${path}`);
- }
-
- function pathClaim(params: unknown, base: string, access: ResourceAccess): ResourceClaim[] {
- const path = typeof params === "object" && params !== null
- ? (params as { path?: unknown }).path
- : undefined;
- return typeof path === "string" && path.trim()
- ? [{ kind: "path", key: resourcePathKey(path.trim(), base), access }]
- : [{ kind: "tree", access }];
- }
-
- /**
- * Whole tree for `MV` and `REM`, which touch a second path or the directory
- * listing, and for a `CUT`/`PUT` header naming an `@register`: host-core keeps
- * named registers per session, so another file's Edit may read or overwrite it.
- * U+0085 joins `\s` because host-core splits headers with Rust whitespace.
- */
- function editClaims(params: unknown, base: string): ResourceClaim[] {
- const ops = typeof params === "object" && params !== null
- ? (params as { ops?: unknown }).ops
- : undefined;
- if (typeof ops === "string" && /^[\s\u0085]*(?:MV|REM)\b|^[\s\u0085]*(?:CUT|PUT)\b[^\n]*[\s\u0085]@/m.test(ops)) {
- return [{ kind: "tree", access: "exclusive" }];
- }
- return pathClaim(params, base, "exclusive");
- }
-
- const FILE_TOOL_NAMES = new Set(["Read", "Glob", "Grep", "Write", "Edit"]);
-
--/**
- * Keep Task fan-out and file batches parallel, but preserve the old safety
- * boundary for a batch that mixes a background delegate with file tools: the
- * whole batch runs sequentially. Delegate write/resource coordination belongs
- * to a later Host-owned phase.
- * Keep Task fan-out and read batches parallel, but preserve the old safety
- * boundary for a batch that mixes a background delegate with file reads.
- * Delegate write/resource coordination belongs to a later Host-owned phase.
-- */
--export function resolveBatchExecutionMode(
-- assistantMessage: AssistantMessage,
--): "parallel" | "sequential" | undefined {
-- const names = assistantMessage.content
-- .filter((block): block is Extract<AssistantMessage["content"][number], { type: "toolCall" }> => block.type === "toolCall")
-- .map((block) => block.name);
-- const hasTask = names.includes("Task");
- const hasFileTool = names.some((name) => FILE_TOOL_NAMES.has(name));
- return hasTask && hasFileTool ? "sequential" : undefined;
- const hasFileRead = names.some((name) => name === "Read" || name === "Glob" || name === "Grep");
- return hasTask && hasFileRead ? "sequential" : undefined;
++export function resolveBatchExecutionMode(message: AssistantMessage): "parallel" | "sequential" | undefined {
++ const names = message.content.filter((b) => b.type === "toolCall").map((b) => b.name);
++ return names.includes("Task") && names.some((name) => TOOL_EXECUTION_SPECS[name]?.file)
++ ? "sequential" : undefined;
}
--export function resolveTaskExecutionMode(
-- lastMessage: unknown,
--): "parallel" | "sequential" {
-- if (
-- typeof lastMessage === "object" &&
-- lastMessage !== null &&
-- (lastMessage as { role?: unknown }).role === "assistant" &&
-- Array.isArray((lastMessage as { content?: unknown }).content) &&
-- resolveBatchExecutionMode(lastMessage as AssistantMessage) === "sequential"
-- ) {
-- return "sequential";
-- }
++export function resolveTaskExecutionMode(lastMessage: unknown): "parallel" | "sequential" {
++ if (typeof lastMessage === "object" && lastMessage !== null
++ && (lastMessage as { role?: unknown }).role === "assistant"
++ && Array.isArray((lastMessage as { content?: unknown }).content)
++ && resolveBatchExecutionMode(lastMessage as AssistantMessage) === "sequential") return "sequential";
return "parallel";
}
--export function withDynamicTaskExecutionMode<
-- T extends { name: string; executionMode?: "parallel" | "sequential" },
-->(tool: T, getLastMessage: () => unknown): T {
-- if (tool.name !== "Task" || tool.executionMode !== "parallel") {
-- return tool;
-- }
++export function withDynamicTaskExecutionMode<T extends { name: string; executionMode?: "parallel" | "sequential" }>(
++ tool: T, getLastMessage: () => unknown,
++): T {
++ if (tool.name !== "Task" || tool.executionMode !== "parallel") return tool;
return Object.defineProperty(tool, "executionMode", {
-- enumerable: true,
-- configurable: true,
-- get: () => resolveTaskExecutionMode(getLastMessage()),
++ enumerable: true, configurable: true, get: () => resolveTaskExecutionMode(getLastMessage()),
});
}
diff --cc packages/host-runtime/src/agent-sidecar.ts
index f27168052,f27168052..c83d6f3e7
--- a/packages/host-runtime/src/agent-sidecar.ts
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@@ -50,6 -50,6 +50,11 @@@ export type VendorAuthResolver = (input
// session, so it cannot reach a credential the session was not launched with.
const HOST_PROXY_ALLOWED = new Set([
"tools.execute",
++ "tools.fileBatchCapabilities",
++ "tools.fileBatchRegister",
++ "tools.fileBatchSeal",
++ "tools.fileBatchAbandon",
++ "tools.fileBatchClose",
"tools.abort",
"tools.list",
"session.get",
diff --cc packages/host-runtime/src/file-batch-bridge.test.ts
index 000000000,000000000..cd57f3e29
new file mode 100644
--- /dev/null
+++ b/packages/host-runtime/src/file-batch-bridge.test.ts
@@@ -1,0 -1,0 +1,27 @@@
++import { afterEach, expect, it } from "vitest";
++import { AgentSidecar, type SidecarHostLink } from "./agent-sidecar.js";
++
++const source = `const rl=require('node:readline').createInterface({input:process.stdin});
++const pending=new Map();rl.on('line',line=>{const m=JSON.parse(line);
++if(m.method==='probe'){pending.set('r'+m.id,m.id);console.log(JSON.stringify({id:'r'+m.id,method:'host.proxy',params:m.params}));}
++else if(pending.has(m.id)){console.log(JSON.stringify({...m,id:pending.get(m.id)}));pending.delete(m.id);}});`;
++let sidecar: AgentSidecar | undefined;
++afterEach(async () => { await sidecar?.dispose(); });
++
++it("forwards only the explicit file batch methods through the production sidecar bridge", async () => {
++ sidecar = new AgentSidecar({ launch: { command: process.execPath, args: ["-e", source] }, onStderr: () => {} });
++ const calls: Array<{ method: string; params: unknown }> = [];
++ const host: SidecarHostLink = {
++ call: async <T>(method: string, params?: unknown) => { calls.push({ method, params }); return { ok: true } as T; },
++ onNotification: () => () => {}, onExit: () => () => {},
++ };
++ sidecar.setHost(host);
++ for (const method of ["tools.fileBatchCapabilities", "tools.fileBatchRegister", "tools.fileBatchSeal", "tools.fileBatchAbandon", "tools.fileBatchClose"]) {
++ const params = { sessionId: "session", batchId: "batch" };
++ await expect(sidecar.call("probe", { method, params })).resolves.toEqual({ ok: true });
++ expect(calls.at(-1)).toEqual({ method, params });
++ }
++ await expect(sidecar.call("probe", { method: "tools.fileBatchBypassPermissions", params: {} })).rejects.toMatchObject({ code: -32601 });
++ await expect(sidecar.call("probe", { method: "settings.set", params: {} })).rejects.toMatchObject({ code: -32601 });
++ expect(calls).toHaveLength(5);
++});
diff --cc packages/shared/src/file-batches.ts
index 000000000,000000000..0524713c4
new file mode 100644
--- /dev/null
+++ b/packages/shared/src/file-batches.ts
@@@ -1,0 -1,0 +1,16 @@@
++/** Internal runtime/Host protocol. These bindings never grant file permission. */
++export const FILE_BATCH_VERSION = 1;
++export interface FileBatchCapability {
++ version: number;
++ supported: boolean;
++}
++export interface FileBatchRegistration {
++ sessionId: string;
++ delegationId?: string;
++ batchId: string;
++ ordinal: number;
++ toolCallId: string;
++ toolName: string;
++ args: unknown;
++}
++export interface FileBatchTicket { ticket: string }
diff --cc packages/shared/src/index.ts
index 869c684f0,869c684f0..755903f8c
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@@ -1,5 -1,5 +1,6 @@@
export * from "./activation.js";
export * from "./protocol.js";
++export * from "./file-batches.js";
export * from "./errors.js";
export * from "./rpc-error.js";
export * from "./certificate-errors.js";
diff --cc scripts/e2e-parallel-read-batches.mjs
index ebdfa1e49,ccd50e1ac..2efb4f4d7
--- a/scripts/e2e-parallel-read-batches.mjs
+++ b/scripts/e2e-parallel-read-batches.mjs
@@@ -2,8 -2,7 +2,8 @@@
// A response barrier proves concurrent dispatch, not filesystem-body overlap.
import assert from "node:assert/strict";
import { createServer } from "node:http";
- import { mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises";
-import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
++import { link, symlink, mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises";
+import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";
@@@ -151,12 -110,7 +151,12 @@@ try
task: "Read and search the fixture files.", provider: runtime.provider,
thinkingLevel: "off", systemPrompt: "Read the fixture files.",
tools: runtime.scopeDelegateTools(tools, definition, "fixture-delegate", apply),
- beforeToolCall: context => runtime.preparePathToolCall(context, apply, names),
+ beforeToolCall: async context => {
+ await runtime.preparePathToolCall(context, apply, names);
- runtime.registerBatchCall(context, names);
++ await runtime.registerBatchCall(context, names);
+ return undefined;
+ },
+ onTurnEnd: message => runtime.batchPlanner.settleBatch(message),
onEvent: envelope => events.push(envelope.event),
});
const report = await child.run();
@@@ -167,103 -121,9 +167,157 @@@
assert.equal(runtime.agent.state.systemPrompt, parentPrompt);
await endTurn(host, turnId);
turnId = undefined;
- console.log("PASS parallel-read E2E: local HTTP provider, parent/delegate concurrent Read dispatch, real Read/Glob/Grep, source-order results, parent prompt isolation");
+ releaseReads();
+ clearTimeout(barrierTimeout);
+
+ // [Read a, Write b, Read c]: no claim conflicts, so all three reach Host
+ // before any response is released, and results keep source order.
+ const mixed = [
+ { id: "mixed-read-a", name: "Read", arguments: { path: "a.txt" } },
+ { id: "mixed-write-b", name: "Write", arguments: { path: "b.txt", content: "written-marker\n" } },
+ { id: "mixed-read-c", name: "Read", arguments: { path: "c.txt" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "mixed-read-a") ? undefined : mixed;
+ let stopGate = holdUntilAllEnter(mixed.map(call => call.id));
+ const mixedRequests = await runTurn(session, "Read a, write b, read c.");
+ stopGate();
+ assert.deepEqual([...gatedEntered].sort(), mixed.map(call => call.id).sort());
+ assert.equal(await readFile(join(workspace, "b.txt"), "utf8"), "written-marker\n");
+ const mixedResults = toolMessages(mixedRequests.at(-1)).filter(message => message.tool_call_id.startsWith("mixed-"));
+ assert.deepEqual(mixedResults.map(message => message.tool_call_id), mixed.map(call => call.id));
+ assert.match(JSON.stringify(mixedResults[0].content), /alpha-marker/);
+ assert.match(JSON.stringify(mixedResults[2].content), /gamma-marker/);
+ gated = new Set();
+
- // [Read a, Edit a]: the Edit claims the file the Read shares, so Host sees
- // read:start, read:end, edit:start. The Edit uses the tag of a real Read
- // from the previous model step and must succeed.
++ // Both RPCs may be submitted together; Host now owns the actual body order.
++ // The native RPC regression separately gates/reverses arrivals to prove it.
++ // Edit still uses a real previous-step tag and must succeed.
+ let tag;
+ respond = body => {
+ const results = toolMessages(body);
+ if (!results.some(m => m.tool_call_id === "tag-read")) {
+ return [{ id: "tag-read", name: "Read", arguments: { path: "a.txt" } }];
+ }
+ if (!results.some(m => m.tool_call_id === "order-edit")) {
+ tag = /\[a\.txt#([0-9A-Fa-f]{4})\]/.exec(JSON.stringify(results.find(m => m.tool_call_id === "tag-read").content))?.[1];
+ assert.ok(tag, "the fixture Read returned no hashline tag");
+ return [
+ { id: "order-read", name: "Read", arguments: { path: "a.txt" } },
+ { id: "order-edit", name: "Edit", arguments: { path: "a.txt", tag, ops: "PUT >$:\n+edited-marker" } },
+ ];
+ }
+ return undefined;
+ };
+ dispatch.length = 0;
+ await runTurn(session, "Read a, then edit it.");
- assert.deepEqual(
- dispatch.filter(entry => entry.startsWith("order-")),
- ["order-read:start", "order-read:end", "order-edit:start", "order-edit:end"],
- );
++ assert.ok(dispatch.includes("order-read:end") && dispatch.includes("order-edit:end"));
+ assert.equal(hostResults.get("order-edit")?.ok, true, `Edit failed: ${JSON.stringify(hostResults.get("order-edit"))}`);
+ assert.match(await readFile(join(workspace, "a.txt"), "utf8"), /alpha-marker\n[\s\S]*edited-marker/);
+
++ // Real differently named aliases through production parent Runtime/pi/Host.
++ // They are intentionally not represented by a basename or local realpath key.
++ await link(join(workspace,"a.txt"),join(workspace,"hard-alias.txt"));
++ const aliases = ["hard-alias.txt"];
++ try {
++ await symlink(join(workspace,"a.txt"),join(workspace,"symbolic-alias.txt"),"file");
++ aliases.push("symbolic-alias.txt");
++ } catch (error) {
++ if (error.code !== "EPERM" && error.code !== "EACCES") throw error;
++ console.log("SKIP file symlink E2E: OS does not grant symlink creation; hard-link cases still run");
++ }
++ for (const alias of aliases) for (const writeFirst of [false,true]) {
++ const before = await readFile(join(workspace,"a.txt"),"utf8");
++ const after = `alias-written-${alias}-${writeFirst}\n`;
++ const readId = `alias-read-${alias}-${writeFirst}`, writeId = `alias-write-${alias}-${writeFirst}`;
++ const pair = [
++ {id:readId,name:"Read",arguments:{path:alias}},
++ {id:writeId,name:"Write",arguments:{path:"a.txt",content:after}},
++ ];
++ if(writeFirst) pair.reverse();
++ respond = body => toolMessages(body).some(m=>m.tool_call_id===writeId) ? undefined : pair;
++ const round = await runTurn(session,"Run the alias file batch in source order.");
++ assert.equal(hostResults.get(writeId)?.ok,true,JSON.stringify(hostResults.get(writeId)));
++ const readResult = toolMessages(round.at(-1)).find(m=>m.tool_call_id===readId);
++ const readText = JSON.parse(readResult.content).content;
++ for (const line of (writeFirst ? after : before).trim().split(/\r?\n/)) {
++ assert.ok(readText.includes(line),JSON.stringify(readResult));
++ }
++ assert.equal(await readFile(join(workspace,alias),"utf8"),after);
++ assert.deepEqual(toolMessages(round.at(-1)).filter(m=>[readId,writeId].includes(m.tool_call_id)).map(m=>m.tool_call_id),pair.map(c=>c.id));
++ // Repeat through the real delegate loop and the runtime's scoped catalog.
++ const childAfter = `child-${after}`;
++ const childPair = pair.map(call => call.name === "Write"
++ ? { ...call, arguments: { ...call.arguments, content: childAfter } } : call);
++ respond = body => toolMessages(body).some(m=>m.tool_call_id===writeId) ? undefined : childPair;
++ const childStart = requests.length;
++ const writer = { name:"alias-writer",description:"Read and write aliases",tools:["Read","Write"],prompt:"Run the batch",source:"builtin" };
++ const writerNames = new Set(writer.tools);
++ const writerTools = [...runtime.toolCatalog.values()].filter(tool=>writerNames.has(tool.name));
++ let writerRun;
++ const childInstructions = instructions => writerRun.setSystemPrompt(`Child rules: ${JSON.stringify(instructions)}`);
++ writerRun = new SubagentRun({ definition:writer,sessionId:session.id,task:"Run the file batch.",
++ provider:runtime.provider,thinkingLevel:"off",systemPrompt:"Run the file batch.",
++ tools:runtime.scopeDelegateTools(writerTools,writer,"alias-child",childInstructions),
++ beforeToolCall:async context=>{
++ await runtime.preparePathToolCall(context,childInstructions,writerNames);
++ await runtime.registerBatchCall(context,writerNames);
++ },
++ onTurnEnd:message=>runtime.batchPlanner.settleBatch(message),onEvent:envelope=>events.push(envelope.event),
++ });
++ assert.equal((await writerRun.run()).status,"completed");
++ await runtime.batchPlanner.drain();
++ const childRead = toolMessages(requests.slice(childStart).at(-1)).find(m=>m.tool_call_id===readId);
++ assert.ok(JSON.parse(childRead.content).content.includes((writeFirst ? childAfter : after).trim()),JSON.stringify(childRead));
++ assert.equal(await readFile(join(workspace,alias),"utf8"),childAfter);
++ }
++
+ // Two same-batch Writes to different files each leave a review snapshot;
+ // rolling both back restores both files.
+ const writes = [
+ { id: "rollback-write-c", name: "Write", arguments: { path: "c.txt", content: "overwritten-c\n" } },
+ { id: "rollback-write-d", name: "Write", arguments: { path: "d.txt", content: "overwritten-d\n" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "rollback-write-c") ? undefined : writes;
+ await runTurn(session, "Overwrite c and d.");
+ assert.equal(await readFile(join(workspace, "c.txt"), "utf8"), "overwritten-c\n");
+ assert.equal(await readFile(join(workspace, "d.txt"), "utf8"), "overwritten-d\n");
+ for (const { id } of writes) {
+ const snapshotId = hostResults.get(id)?.content?.review?.snapshotId;
+ assert.ok(snapshotId, `${id} left no review snapshot`);
+ const outcome = await host.call("review.rollback", { sessionId: session.id, snapshotId });
+ assert.equal(outcome.status ?? outcome.outcome?.status, "rolledBack", JSON.stringify(outcome));
+ }
+ assert.equal(await readFile(join(workspace, "c.txt"), "utf8"), "gamma-marker\n");
+ assert.equal(await readFile(join(workspace, "d.txt"), "utf8"), "delta-marker\n");
+
+ // Ask mode: both same-batch Writes wait for approval at the same time;
+ // denying one does not affect the other.
+ await configureSession(host, session, "agent", "ask");
+ const asks = [
+ { id: "ask-write-e", name: "Write", arguments: { path: "e.txt", content: "denied\n" } },
+ { id: "ask-write-f", name: "Write", arguments: { path: "f.txt", content: "approved\n" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "ask-write-e") ? undefined : asks;
+ const asked = runTurn(session, "Write e and f.");
+ const permissionFor = id => host.notifications.find(n => n.method === "permissions.request" && n.params?.toolCallId === id);
+ for (let attempt = 0; attempt < 200 && !asks.every(({ id }) => permissionFor(id)); attempt += 1) {
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ assert.ok(asks.every(({ id }) => permissionFor(id)), "both Writes should await approval together");
+ await host.call("permissions.resolve", { requestId: permissionFor("ask-write-e").params.requestId, decision: "deny" });
+ await host.call("permissions.resolve", { requestId: permissionFor("ask-write-f").params.requestId, decision: "allow-once" });
+ const askRequests = await asked;
+ assert.equal(existsSync(join(workspace, "e.txt")), false);
+ assert.equal(await readFile(join(workspace, "f.txt"), "utf8"), "approved\n");
+ const askResults = toolMessages(askRequests.at(-1)).filter(message => message.tool_call_id.startsWith("ask-"));
+ assert.deepEqual(askResults.map(message => message.tool_call_id), asks.map(call => call.id));
+ assert.equal(hostResults.get("ask-write-e")?.ok, false);
+ assert.equal(hostResults.get("ask-write-f")?.ok, true);
+ assert.equal(events.some(event => event.type === "error"), false);
- console.log("PASS parallel-read E2E: local HTTP provider, parent/delegate concurrent Read dispatch, real Read/Glob/Grep, source-order results, parent prompt isolation; [Read, Write, Read] overlap, [Read a, Edit a] Host order with a real tag, two-Write rollback, concurrent ask-mode approvals");
++ console.log("PASS parallel-file E2E: parent/delegate Runtime/pi with real Host, concurrent dispatch, source-order results, alias Read/Write both orders, real-tag Edit, two-Write rollback, concurrent ask-mode approvals");
} finally {
releaseReads();
+ releaseGate();
clearTimeout(barrierTimeout);
await runtime?.dispose();
if (turnId) await endTurn(host, turnId, "error");