Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
perf(host-core): allow concurrent writes to independent files within a session
cauliflower3faa015329a2
diff --git a/crates/host-core/src/file_resources.rs b/crates/host-core/src/file_resources.rsindex 9182c8978..2ce3e6217 100644--- a/crates/host-core/src/file_resources.rs+++ b/crates/host-core/src/file_resources.rs@@ -29,6 +29,10 @@ pub fn is_write(name: &str) -> bool {}impl FileResources {+ pub(crate) fn is_identified_write(&self) -> bool {+ self.exclusive && self.identity.is_some() && self.address.is_some()+ }+pub fn fence(exclusive: bool) -> Arc<Self> {Arc::new(Self {exclusive,diff --git a/crates/host-core/src/tool_budget.rs b/crates/host-core/src/tool_budget.rsindex d4f8a4764..20ca87b4a 100644--- a/crates/host-core/src/tool_budget.rs+++ b/crates/host-core/src/tool_budget.rs@@ -11,6 +11,7 @@ pub const MAX_IN_FLIGHT_SHELL: usize = 4;pub const MAX_IN_FLIGHT_READS: usize = 8;pub const MAX_IN_FLIGHT_MUTATIONS: usize = 2;pub const MAX_IN_FLIGHT_MUTATIONS_PER_SESSION: usize = 1;+const MAX_IN_FLIGHT_COORDINATED_MUTATIONS_PER_SESSION: usize = 2;pub const MAX_IN_FLIGHT_PLUGINS: usize = 4;pub const MAX_IN_FLIGHT_PER_SESSION: usize = 4;pub const MAX_QUEUED_TOOLS: usize = 64;@@ -172,10 +173,24 @@ struct Request {ticket: Option<String>,}+impl Request {+ // Eligibility stays immutable through release, including after batches.finish.+ // Admission separately checks the ticket's validated, submitted source order.+ fn coordinated_mutation(&self) -> bool {+ self.class == ToolClass::Mutation+ && self.ticket.is_some()+ && self+ .resources+ .as_ref()+ .is_some_and(|r| r.is_identified_write())+ }+}+#[derive(Default)]struct SessionUsage {active: usize,mutations: usize,+ conservative_mutations: usize,/// Of `active`, calls rooted in a subagent's own worktree.own_worktree: usize,}@@ -263,7 +278,12 @@ impl BudgetState {self.sessions.get(&request.session_id).is_none_or(|usage| {usage.active < MAX_IN_FLIGHT_PER_SESSION&& (request.class != ToolClass::Mutation- || usage.mutations < MAX_IN_FLIGHT_MUTATIONS_PER_SESSION)+ || if request.coordinated_mutation() {+ usage.conservative_mutations == 0+ && usage.mutations < MAX_IN_FLIGHT_COORDINATED_MUTATIONS_PER_SESSION+ } else {+ usage.mutations < MAX_IN_FLIGHT_MUTATIONS_PER_SESSION+ })})}@@ -280,6 +300,9 @@ impl BudgetState {usage.active += 1;if request.class == ToolClass::Mutation {usage.mutations += 1;+ if !request.coordinated_mutation() {+ usage.conservative_mutations += 1;+ }}if request.own_worktree {usage.own_worktree += 1;@@ -308,6 +331,9 @@ impl BudgetState {usage.active -= 1;if request.class == ToolClass::Mutation {usage.mutations -= 1;+ if !request.coordinated_mutation() {+ usage.conservative_mutations -= 1;+ }}if request.own_worktree {usage.own_worktree -= 1;@@ -343,30 +369,35 @@ impl BudgetState {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,+ if entry.granted {+ return true;+ }+ let prior = &entry.request;+ // An unready successor must not fence another batch that could be+ // needed by its own predecessor. Preserve this before capacity fairness.+ if let (Some(ticket), Some(claims)) = (&prior.ticket, &prior.resources) {+ if !self.batches.can_run(ticket, claims) {+ return true;}+ }+ if let (Some(ours), Some(theirs)) = (&request.ticket, &prior.ticket) {+ if self.batches.precedes(ours, theirs) {+ return true;+ }+ }+ // Let an older conservative mutation drain its session. Otherwise+ // independent coordinated writes could keep refilling its second slot.+ if request.coordinated_mutation()+ && prior.session_id == request.session_id+ && prior.class == ToolClass::Mutation+ && !prior.coordinated_mutation()+ {+ return false;+ }+ prior+ .resources+ .as_ref()+ .is_none_or(|claims| !resources.conflicts(claims))})}}diff --git a/crates/host-core/src/tool_budget/file_tests.rs b/crates/host-core/src/tool_budget/file_tests.rsindex b8652aa91..b349f3b39 100644--- a/crates/host-core/src/tool_budget/file_tests.rs+++ b/crates/host-core/src/tool_budget/file_tests.rs@@ -6,6 +6,231 @@ use std::future::{poll_fn, Future};use std::pin::Pin;use std::task::Poll;+fn coordinated_write(+ budget: &ToolBudget,+ root: &std::path::Path,+ index: u32,+) -> (PendingFileCall, Arc<FileResources>, String) {+ let path = format!("file-{index}");+ std::fs::write(root.join(&path), "before").unwrap();+ let mut c = call(index, "Write", &path);+ c.batch_id = format!("batch-{index}");+ let ticket = budget.register_file_call(c.clone()).unwrap();+ budget.seal_file_batch(&c.batch_id, "s").unwrap();+ let pending = budget+ .begin_file_call(&ticket, "s", None, &c.tool_call_id, "Write", &c.args)+ .unwrap();+ let resources =+ FileResources::resolve(Some(root), &ContainedRoots::new(), "Write", &c.args, false);+ (pending, resources, ticket)+}++#[tokio::test]+async fn independent_coordinated_writes_share_session_capacity() {+ let dir = tempfile::tempdir().unwrap();+ let budget = ToolBudget::new();+ let (_a, ra, ta) = coordinated_write(&budget, dir.path(), 0);+ let (_b, rb, tb) = coordinated_write(&budget, dir.path(), 1);+ let first = budget+ .acquire_files("s", "Write", false, ra, Some(ta))+ .await+ .unwrap();+ let mut second = Box::pin(budget.acquire_files("s", "Write", false, rb, Some(tb)));+ let second = poll_fn(|cx| match second.as_mut().poll(cx) {+ Poll::Ready(result) => Poll::Ready(result.unwrap()),+ Poll::Pending => panic!("independent coordinated write blocked by session capacity"),+ })+ .await;+ assert_eq!(budget.snapshot().mutations, 2);+ drop((first, second));+ assert_eq!(budget.snapshot().active, 0);+}++async fn ready<T>(future: Pin<&mut impl Future<Output = T>>) -> T {+ let mut future = future;+ poll_fn(|cx| match future.as_mut().poll(cx) {+ Poll::Ready(value) => Poll::Ready(value),+ Poll::Pending => panic!("eligible request did not acquire available capacity"),+ })+ .await+}++#[tokio::test]+async fn conservative_waiter_drains_coordinated_writes_before_refilling() {+ for legacy in [true, false] {+ let dir = tempfile::tempdir().unwrap();+ let budget = ToolBudget::new();+ let (_a, ra, ta) = coordinated_write(&budget, dir.path(), 0);+ let (_b, rb, tb) = coordinated_write(&budget, dir.path(), 1);+ let (_c, rc, tc) = coordinated_write(&budget, dir.path(), 2);+ let (_l, rl, _) = coordinated_write(&budget, dir.path(), 3);+ let a = budget+ .acquire_files("s", "Write", false, ra, Some(ta))+ .await+ .unwrap();+ let b = ready(Box::pin(budget.acquire_files("s", "Write", false, rb, Some(tb))).as_mut())+ .await+ .unwrap();+ let mut conservative = Box::pin(async {+ if legacy {+ budget.acquire("s", "Write").await+ } else {+ budget.acquire_files("s", "Write", false, rl, None).await+ }+ });+ pending(conservative.as_mut()).await;+ drop(a);+ let mut later = Box::pin(budget.acquire_files("s", "Write", false, rc, Some(tc)));+ pending(later.as_mut()).await; // immediate admission must respect the waiter+ drop(b); // dispatch must grant L, not C+ let l = ready(conservative.as_mut()).await.unwrap();+ pending(later.as_mut()).await;+ drop(l);+ drop(ready(later.as_mut()).await.unwrap());+ assert_eq!(budget.snapshot().active, 0);+ assert_eq!(budget.snapshot().queued, 0);+ }+}++#[tokio::test]+async fn conservative_active_write_blocks_coordinated_write_and_cancel_cleans_up() {+ let dir = tempfile::tempdir().unwrap();+ let budget = ToolBudget::new();+ let (_a, ra, ta) = coordinated_write(&budget, dir.path(), 0);+ let legacy = budget.acquire("s", "Write").await.unwrap();+ let mut waiting = Box::pin(budget.acquire_files("s", "Write", false, ra, Some(ta)));+ pending(waiting.as_mut()).await;+ drop(legacy); // reserves the coordinated permit before its waiter claims it+ assert_eq!(budget.snapshot().mutations, 1);+ drop(waiting);+ assert_eq!(budget.snapshot().active, 0);+ drop(budget.acquire("s", "Write").await.unwrap());+}++#[tokio::test]+async fn cancelling_conservative_waiter_restores_second_slot_immediately() {+ let dir = tempfile::tempdir().unwrap();+ let budget = ToolBudget::new();+ let (_a, ra, ta) = coordinated_write(&budget, dir.path(), 0);+ let (_b, rb, tb) = coordinated_write(&budget, dir.path(), 1);+ let a = budget+ .acquire_files("s", "Write", false, ra, Some(ta))+ .await+ .unwrap();+ let mut legacy = Box::pin(budget.acquire("s", "Write"));+ pending(legacy.as_mut()).await;+ let mut b = Box::pin(budget.acquire_files("s", "Write", false, rb, Some(tb)));+ pending(b.as_mut()).await;+ drop(legacy);+ let b = ready(b.as_mut()).await.unwrap();+ assert_eq!(budget.snapshot().mutations, 2);+ drop((a, b));+ assert_eq!(budget.snapshot().active, 0);+}++#[tokio::test]+async fn coordinated_writes_preserve_global_limit_and_close_does_not_release_them() {+ let dir = tempfile::tempdir().unwrap();+ let budget = ToolBudget::new();+ let (_a, ra, ta) = coordinated_write(&budget, dir.path(), 0);+ let (_b, rb, tb) = coordinated_write(&budget, dir.path(), 1);+ let a = budget+ .acquire_files("s", "Write", false, ra, Some(ta))+ .await+ .unwrap();+ let b = ready(Box::pin(budget.acquire_files("s", "Write", false, rb, Some(tb))).as_mut())+ .await+ .unwrap();+ budget.close_file_batch("batch-0", "s").unwrap();+ budget.close_file_batch("batch-1", "s").unwrap();+ let mut other = Box::pin(budget.acquire("other", "Write"));+ pending(other.as_mut()).await;+ drop(a);+ drop(ready(other.as_mut()).await.unwrap());+ drop(b);+ assert_eq!(budget.snapshot().active, 0);+ drop(budget.acquire("s", "Write").await.unwrap());+}++#[tokio::test]+async fn unready_conservative_successor_does_not_block_its_predecessor() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("a"), "before").unwrap();+ let budget = ToolBudget::new();+ let a = call(0, "Write", "a");+ let b = call(1, "Write", "missing");+ 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 _pb = 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 _pa = budget+ .begin_file_call(&ta, "s", None, "0", "Write", &a.args)+ .unwrap();+ let ra = FileResources::resolve(+ Some(dir.path()),+ &ContainedRoots::new(),+ "Write",+ &a.args,+ false,+ );+ let a = ready(Box::pin(budget.acquire_files("s", "Write", false, ra, Some(ta))).as_mut())+ .await+ .unwrap();+ pending(later.as_mut()).await;+ drop(a);+ drop(ready(later.as_mut()).await.unwrap());+}++#[tokio::test]+async fn coordinated_alias_writes_preserve_source_order_in_reversed_arrival() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("a"), "before").unwrap();+ std::fs::hard_link(dir.path().join("a"), dir.path().join("alias")).unwrap();+ for names in [["Write", "Write"], ["Edit", "Write"], ["Write", "Edit"]] {+ let budget = ToolBudget::new();+ let a = call(0, names[0], "a");+ let b = call(1, names[1], "alias");+ 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 _pb = budget+ .begin_file_call(&tb, "s", None, "1", names[1], &b.args)+ .unwrap();+ let rb = FileResources::resolve(+ Some(dir.path()),+ &ContainedRoots::new(),+ names[1],+ &b.args,+ false,+ );+ let mut later = Box::pin(budget.acquire_files("s", names[1], false, rb, Some(tb)));+ pending(later.as_mut()).await;+ let _pa = budget+ .begin_file_call(&ta, "s", None, "0", names[0], &a.args)+ .unwrap();+ let ra = FileResources::resolve(+ Some(dir.path()),+ &ContainedRoots::new(),+ names[0],+ &a.args,+ false,+ );+ let first =+ ready(Box::pin(budget.acquire_files("s", names[0], false, ra, Some(ta))).as_mut())+ .await+ .unwrap();+ pending(later.as_mut()).await;+ drop(first);+ drop(ready(later.as_mut()).await.unwrap());+ assert_eq!(budget.snapshot().active, 0);+ }+}+#[tokio::test]async fn unready_successor_cannot_form_a_fairness_cycle_through_another_batch() {let budget = ToolBudget::new();diff --git a/crates/host-core/src/tools/file_lease_tests.rs b/crates/host-core/src/tools/file_lease_tests.rsindex aa6c4a3fa..df0aed224 100644--- a/crates/host-core/src/tools/file_lease_tests.rs+++ b/crates/host-core/src/tools/file_lease_tests.rs@@ -1,4 +1,4 @@-//! Deterministic gate at the real blocking-pool boundary, keyed by test workspace.+//! Deterministic gates at the real blocking-pool boundary, keyed by workspace/path.use super::*;use std::collections::HashMap;use std::future::{poll_fn, Future};@@ -9,14 +9,18 @@ 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();+type GateKey = (PathBuf, String);+static GATES: OnceLock<StdMutex<HashMap<GateKey, Arc<Gate>>>> = OnceLock::new();-pub(super) fn pause(root: Option<&Path>) {+pub(super) fn pause(root: Option<&Path>, path: Option<&str>) {let Some(gates) = GATES.get() else { return };let gate = gates.lock().unwrap()- .get(root.unwrap_or(Path::new("")))+ .get(&(+ root.unwrap_or(Path::new("")).to_owned(),+ path.unwrap_or("").to_owned(),+ )).cloned();if let Some(gate) = gate {if let Some(entered) = gate.entered.lock().unwrap().take() {@@ -35,7 +39,7 @@ async fn cancelling_transport_waiter_does_not_release_a_running_blocking_read_lelet (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(),+ (dir.path().to_owned(), "alias".into()),Arc::new(Gate {entered: StdMutex::new(Some(entered_tx)),leave: StdMutex::new(leave_rx),@@ -99,5 +103,145 @@ async fn cancelling_transport_waiter_does_not_release_a_running_blocking_read_leleave_tx.send(()).unwrap();drop(write.await.unwrap());assert_eq!(budget.snapshot().active, 0);- GATES.get().unwrap().lock().unwrap().remove(dir.path());+ GATES+ .get()+ .unwrap()+ .lock()+ .unwrap()+ .remove(&(dir.path().to_owned(), "alias".into()));+}++#[tokio::test]+async fn two_coordinated_blocking_writes_overlap_and_retain_cancelled_lease() {+ let dir = tempfile::tempdir().unwrap();+ let budget = crate::tool_budget::ToolBudget::new();+ let roots = ContainedRoots::new();+ let mut tickets = Vec::new();+ let mut pending = Vec::new();+ for (ordinal, path) in ["a", "b"].iter().enumerate() {+ std::fs::write(dir.path().join(path), "before").unwrap();+ let call = crate::file_batches::BatchCall {+ session_id: "s".into(),+ delegation_id: None,+ batch_id: "writes".into(),+ ordinal: ordinal as u32,+ tool_call_id: path.to_string(),+ tool_name: "Write".into(),+ args: json!({"path":path,"content":format!("after-{path}")}),+ };+ tickets.push((budget.register_file_call(call.clone()).unwrap(), call));+ }+ budget.seal_file_batch("writes", "s").unwrap();+ let mut executions = Vec::new();+ let mut entered = Vec::new();+ let mut releases = Vec::new();+ for (ticket, call) in &tickets {+ pending.push(+ budget+ .begin_file_call(ticket, "s", None, &call.tool_call_id, "Write", &call.args)+ .unwrap(),+ );+ let resources = crate::file_resources::FileResources::resolve(+ Some(dir.path()),+ &roots,+ "Write",+ &call.args,+ false,+ );+ let permit = tokio::time::timeout(+ std::time::Duration::from_secs(5),+ budget.acquire_files("s", "Write", false, resources.clone(), Some(ticket.clone())),+ )+ .await+ .unwrap()+ .unwrap();+ let (tx, rx) = tokio::sync::oneshot::channel();+ let (leave, wait) = std::sync::mpsc::channel();+ GATES.get_or_init(Default::default).lock().unwrap().insert(+ (dir.path().to_owned(), call.tool_call_id.clone()),+ Arc::new(Gate {+ entered: StdMutex::new(Some(tx)),+ leave: StdMutex::new(wait),+ }),+ );+ entered.push(rx);+ releases.push(leave);+ executions.push(Box::pin(execute_tool_with_file_lease(+ Some(dir.path()),+ None,+ "Write",+ &call.args,+ ToolExecutionOptions {+ timeout_ms: None,+ bash_options: None,+ allow_external_paths: false,+ hashline: None,+ visualization_root: None,+ },+ Some(Arc::new(permit)),+ Some(resources),+ )));+ }+ for execution in &mut executions {+ poll_fn(|cx| {+ assert!(execution.as_mut().poll(cx).is_pending());+ Poll::Ready(())+ })+ .await;+ }+ for signal in entered {+ tokio::time::timeout(std::time::Duration::from_secs(5), signal)+ .await+ .unwrap()+ .unwrap();+ }+ assert_eq!(budget.snapshot().mutations, 2);+ // Both bodies entered before either was released. Dropping an outer future+ // tests execution ownership, not the user-facing Write Stop protocol.+ drop(executions.remove(0));+ let conflict = crate::file_resources::FileResources::resolve(+ Some(dir.path()),+ &roots,+ "Read",+ &json!({"path":"a"}),+ false,+ );+ let mut reader = Box::pin(budget.acquire_files("other", "Read", false, conflict, None));+ poll_fn(|cx| {+ assert!(reader.as_mut().poll(cx).is_pending());+ Poll::Ready(())+ })+ .await;+ releases[1].send(()).unwrap();+ assert!(executions.remove(0).await.ok);+ assert_eq!(budget.snapshot().mutations, 1);+ poll_fn(|cx| {+ assert!(reader.as_mut().poll(cx).is_pending());+ Poll::Ready(())+ })+ .await;+ releases[0].send(()).unwrap();+ drop(+ tokio::time::timeout(std::time::Duration::from_secs(5), reader)+ .await+ .unwrap()+ .unwrap(),+ );+ assert_eq!(+ std::fs::read_to_string(dir.path().join("a")).unwrap(),+ "after-a"+ );+ assert_eq!(+ std::fs::read_to_string(dir.path().join("b")).unwrap(),+ "after-b"+ );+ assert_eq!(budget.snapshot().active, 0);+ for path in ["a", "b"] {+ GATES+ .get()+ .unwrap()+ .lock()+ .unwrap()+ .remove(&(dir.path().to_owned(), path.into()));+ }}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 271c7b0b3..fcd5c57f8 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1176,7 +1176,10 @@ async fn run_file_tool(// retain the lease until the actual filesystem body has returned.let _file_lease = lease;#[cfg(test)]- file_lease_tests::pause(workspace.as_deref());+ file_lease_tests::pause(+ workspace.as_deref(),+ args.get("path").and_then(Value::as_str),+ );if let Some((_, resources)) = &_file_lease {resources.validate(diff --git a/docs/adr/host-file-batch-admission.md b/docs/adr/host-file-batch-admission.mdindex 604a6007c..b5baec19f 100644--- a/docs/adr/host-file-batch-admission.md+++ b/docs/adr/host-file-batch-admission.md@@ -44,7 +44,7 @@ ToolBudget checks batch predecessors, active resources, conflicting waiters andcapacity in one synchronous reservation. No capacity is held while awaiting aresource. 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+do not bypass an exclusive waiter. Global capacity limits and 30-secondHOST_OVERLOADED behavior stay unchanged. Local diagnostics report totaladmission wait and the initial reason, not invented non-overlapping timings.@@ -64,7 +64,7 @@ Tickets travel in AsyncLocalStorage, not a shared provider-call-ID map.Remote workspaces do not yet expose this execution-end protocol. They and oldHosts retain sequential write batches; the desktop never stats a remote path-locally. Bash, Task's delegation lifecycle, plugin/MCP policy, write quotas and+locally. Bash, Task's delegation lifecycle, plugin/MCP policy andpersistence formats are unchanged. Coordination covers participating filetools and rollback in one Host process, not arbitrary external writers, shellprocesses or other Host instances. It is not OS-wide transaction isolation or a@@ -85,9 +85,16 @@ new defense against malicious external path replacement.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.+must be included in performance measurements. Identified local writes with+validated batch tickets can share two session mutation slots, still bounded by+two global mutations. Calls without that coordination remain single-write and+exclude coordinated writes symmetrically. Eligibility uses immutable request+facts so finishing batch metadata cannot change release accounting. An older+source-ready conservative waiter drains its session rather than allowing later+independent writes to refill it indefinitely; source-order bypass and unready+successor exceptions remain necessary to avoid queue/DAG cycles. This is not a+per-Agent fair scheduler. 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,diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex eb988f726..708eee919 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -66,7 +66,13 @@ ToolBudget grants all resources and execution capacity together. Waiting for apredecessor/resource does not occupy a capacity slot. Later conflicting callscannot bypass an exclusive resource waiter; an earlier source-order call canbypass 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.+limits remain: 16 total, 8 reads, 2 writes and 4 per session. Within a session,+up to two writes may overlap only when both have validated batch tickets and+trusted local file identities, subject to the existing conflict checks. All+other mutations retain single-write admission and exclude coordinated writes+in both arrival orders. An older source-ready conservative mutation waiter+prevents later coordinated writes from continuously refilling that session;+unready successors and source-predecessor bypass retain the DAG exceptions.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.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 8eb8b9859..0adfb9083 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -273,6 +273,13 @@future and proves a conflicting write cannot acquire until that body finishes.Closing/abandoning metadata must not release running work. Snapshot/finalizeand later rollback participate in the same Host file domain.+- Independent identified writes with validated tickets may use two session+ slots. Per-file native gates must observe both blocking bodies before either+ is released, and retain the cancelled body's lease. Budget regressions cover+ legacy/coordinated admission in both orders, conservative waiter draining,+ reversed source order, global limits and cancellation after reservation.+ Runtime E2E must preserve distinct snapshots and rollback for both writes;+ this is correctness evidence, not a wall-clock throughput claim.- Runtime/pi integration tests cover parent/delegate registration, preparationorder, validation/mode failures, Stop and model result order. Protocol adaptertests cover sealing, cleanup, remote/legacy fallback and equal provider IDs in@@ -7888,9 +7895,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.6. If the task uses a dedicated worktree outside the advertised workspace,verify its guarded Bash edit and resulting `git diff`.- **Expected**:- - Read/search calls may overlap, but only one `Write`/`Edit` executes for a- session at a time; queued mutations do not consume another global- mutation slot while waiting.+ - Read/search calls may overlap. A session may execute two independent+ identified local writes with validated batch tickets; conservative writes+ remain exclusive within the session. Queued mutations consume no global+ mutation capacity while waiting; total running writes stay bounded by two.- The stale-tag edit fails without changing the file and returns`EDIT_TAG_MISMATCH` carrying the live tag and current content at theanchors; the overlapping-range payload fails with `EDIT_RANGE_INVALID`diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex baf2442ff..acf69d1b9 100644--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@ -50,7 +50,11 @@ Unix 对支持的本地文件系统使用已打开文件的 dev/ino;WindowsToolBudget 一次授予全部资源和容量;等待前驱或资源不占槽位。后来的冲突调用不能越过等待中的独占者;同批较早源序调用可越过后到达的后继,避免队列与依赖图死锁。-额度仍为总 16、读 8、写 2、每会话 4、每会话写 1;准入等待 30 秒仍返回 HOST_OVERLOADED。+额度仍为总 16、读 8、写 2、每会话 4。同一会话最多两个写可以重叠,但两者都必须有+已验证的批次 ticket 和可信本地文件身份,且通过现有资源冲突检查。其他 mutation 保持+单写准入,并在两种到达顺序下都与协调写互斥。较早且源序已就绪的保守写等待者阻止+后来协调写持续补位;未就绪后继与源序前驱绕行仍保留依赖图例外。+准入等待 30 秒仍返回 HOST_OVERLOADED。本地 audit/debug 记录总准入等待与初始原因 source_order、resource、capacity;不将它们宣称为互不重叠的分段耗时。diff --git a/scripts/e2e-parallel-read-batches.mjs b/scripts/e2e-parallel-read-batches.mjsindex 2efb4f4d7..feab99fc4 100644--- a/scripts/e2e-parallel-read-batches.mjs+++ b/scripts/e2e-parallel-read-batches.mjs@@ -293,6 +293,9 @@ try {// 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");+ // Existing targets exercise identified admission; absent targets fence the domain.+ await writeFile(join(workspace, "e.txt"), "original-e\n");+ await writeFile(join(workspace, "f.txt"), "original-f\n");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" } },@@ -307,7 +310,7 @@ try {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, "e.txt"), "utf8"), "original-e\n");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));