Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): per-subagent git worktrees and read-only roots for read-only agents (#9498)
Akarshan Biswase3a75ab41ee9
diff --git a/adk/python/jan_adk/_generated.py b/adk/python/jan_adk/_generated.pyindex 101d2cc03..5966d2337 100644--- a/adk/python/jan_adk/_generated.py+++ b/adk/python/jan_adk/_generated.py@@ -344,6 +344,8 @@ class SubagentStartEvent(TypedDict):name: str# The task the child was dispatched with -- its sole user message. Carried on the event rather than left for consumers to correlate back to the `dispatch_subagent` call: two dispatches can share a `subagent_name`, so matching on name alone is ambiguous.task: NotRequired[Union[str, None]]+ # Where the child works: its own worktree and branch, or the checkout it was given, marked when read-only.+ workspace: NotRequired[Union[str, None]]type: Literal["subagent_start"]class SubagentQueuedEvent(TypedDict):diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 853dc6c63..7670f2acb 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -39,7 +39,7 @@ Either form loads the skill's full instructions into the conversation (no separa| `/resume [id]` | Resume a thread. Bare: pick interactively || `/fork` | Branch this session at a past message into a new thread, keeping this one || `/tree` | Saved threads as a fork tree. Enter resumes one |-| `/worktree` | The dedicated checkout this session works in, and what changed there |+| `/worktree` | The dedicated checkout this session works in, what changed there, and its subagents' worktrees || `/quit` | Exit |See [Sessions](/docs/agent/sessions).diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdxindex 1abdf4371..c1ab68e45 100644--- a/docs/src/pages/docs/agent/subagents.mdx+++ b/docs/src/pages/docs/agent/subagents.mdx@@ -161,6 +161,74 @@ itself. That keeps one curator for memory instead of several writers it never seThey *can* request permission for a write or a command. Those prompts surface in your console,labelled with which subagent asked.+## Where a subagent works++This applies to the `jan` CLI and TUI; in the desktop app a subagent works in its parent's+workspace as before.++Each subagent's working directory is decided when it is dispatched. There is no tool for it: the+dispatch result says where each one works, for example+`working in worktree ~/.jan/worktrees/jan-582afba2/general-3f2a (branch jan/agent/general-3f2a, from 587e06393); uncommitted changes in your checkout are not in it`+or `working read-only in /home/you/src/jan`.++- **Writers get their own checkout.** A subagent whose tools include `write` or `edit` gets a fresh+ checkout on a `jan/agent/<name>-<id>` branch, started from `HEAD`, under+ `~/.jan/worktrees/<project>/`. It is a repository of its own (a `git clone --shared`, not a linked+ worktree), so two writers dispatched together never edit the same checkout, none of them sees your+ uncommitted changes, and none of them can write your `.git`. When the writer finishes, its branch+ is fetched into your repository and its final answer names it; merging it is up to you or the main+ agent. If the branch could not be brought over (the checkout's `.git` or config was tampered with,+ or you have since moved a branch of that name), the answer and the session-end note say so and+ the branch stays in the checkout. When your session runs in a subdirectory of the repository, the subagent+ starts in the same subdirectory of its worktree; if that directory is not in the worktree+ (untracked or ignored in your checkout, or absent at the `ref`), it starts at the worktree's top+ level instead and the dispatch result says so.+- **Readers are read-only.** Any other subagent (`explore`, `review`, `research`, ...) works in+ your checkout with it read-only: `write` and `edit` refuse paths in it, and its shell always runs+ in the sandbox with the checkout (including `.git`) mounted read-only, even when your own session+ runs unsandboxed. If no sandbox can start on the machine, a reader gets no shell at all. The+ session scratch stays writable, and package caches (`YARN_CACHE_FOLDER`, `COREPACK_HOME`) point+ into it.+- Not a git repository, or no commits yet: every subagent works in your checkout (readers still+ read-only), and the dispatch result says so.++A dispatch entry can choose with its optional `workspace` field:++| `workspace` | Meaning |+| --- | --- |+| omitted | The default above |+| `"new"` | A fresh checkout |+| `"shared"` | Your checkout (read-only for a reader) |+| `"<earlier subagent name>"` | That subagent's workspace, for follow-ups or a reviewer of its work. Only one writer may be in a worktree at a time: a writer naming one that another writer is still in is refused, not queued, so dispatch it again once that one has finished |+| `{"ref": "<git ref>"}` | A fresh checkout at that ref, fetched from `origin` when it is not local (for example `pull/9486/head`). A fetch that has not finished within 60 seconds is stopped and the dispatch fails with that error |++Saved subagent definitions cannot set a workspace; it is chosen per dispatch.++Checkouts share one `CARGO_TARGET_DIR` per project, so a new one does not start with a cold Rust+build. A writer's sandbox can write its checkout (its own `.git` included) and that build+directory, and can read your repository's objects, which its checkout borrows (`objects/info/+alternates`); it cannot write any of your `.git`. Every git operation works there, `git branch -d`,+`git stash drop`, `git gc` and `git repack` included. Because the checkout is the child's to+change, Jan's own git never trusts it: before it reads a checkout (to list, sweep or fetch it) it+checks that its `.git` is still a plain directory without a `commondir`, that its object alternates+still name only your objects and that its config does not include another file; it then runs with+the checkout's other config emptied or overridden (`core.fsmonitor`, hooks, filters, transports),+ignoring `replace` refs and nested repositories. A checkout that fails the check is neither read+nor removed, and the session-end note says why.++Because a checkout borrows your objects instead of copying them, avoid `git gc --prune=now` in your+repository while a child is running or a checkout is kept: it can delete objects only a checkout+still uses (the base of a `{ "ref": ... }` workspace fetched for the run, for instance) and break+that checkout. A plain `git gc` keeps unreferenced objects for two weeks and is safe.++The main agent can read its subagents' checkouts with the file tools (`read`, `ls`,+`find`, `grep`), and from its shell only while that shell is sandboxed, where they are mounted+read-only (`git -C <checkout> diff` works; an escalated command naming them is refused).++When the session ends, checkouts with no commits beyond their base and no uncommitted changes are+deleted. The rest are kept and named (their branches already fetched into your repository), and so+is any checkout git cannot read; `/worktree` lists them while the session runs.+<Callout type="info">Because a subagent's context is separate, a long research task that would have crowded your sessioncosts you only its final answer.diff --git a/packages/adk/src/generated/rpc-types.d.ts b/packages/adk/src/generated/rpc-types.d.tsindex 6bf724d7f..6c1117d2c 100644--- a/packages/adk/src/generated/rpc-types.d.ts+++ b/packages/adk/src/generated/rpc-types.d.ts@@ -312,6 +312,8 @@ export interface SubagentStartEvent {"name": string/** The task the child was dispatched with -- its sole user message. Carried on the event rather than left for consumers to correlate back to the `dispatch_subagent` call: two dispatches can share a `subagent_name`, so matching on name alone is ambiguous. */"task"?: string | null+ /** Where the child works: its own worktree and branch, or the checkout it was given, marked when read-only. */+ "workspace"?: string | null"type": "subagent_start"}diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.jsonindex 73f704f9a..fdca92ec3 100644--- a/protocol/rpc-schema.json+++ b/protocol/rpc-schema.json@@ -675,6 +675,13 @@"null"]},+ "workspace": {+ "description": "Where the child works: its own worktree and branch, or the\ncheckout it was given, marked when read-only.",+ "type": [+ "string",+ "null"+ ]+ },"type": {"type": "string","const": "subagent_start"diff --git a/protocol/schema.json b/protocol/schema.jsonindex eeb853a7b..fc13618b3 100644--- a/protocol/schema.json+++ b/protocol/schema.json@@ -233,6 +233,13 @@"null"]},+ "workspace": {+ "description": "Where the child works: its own worktree and branch, or the\ncheckout it was given, marked when read-only.",+ "type": [+ "string",+ "null"+ ]+ },"type": {"type": "string","const": "subagent_start"diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex f635172f0..b0a6875ee 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -16,6 +16,7 @@ dependencies = ["comfy-table","console","dirs",+ "dunce","ed25519-dalek","env","env_logger",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex b2f0feb02..eff3bb196 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -110,6 +110,9 @@ serde_json = "1.0"[dependencies]dirs = "6.0.0"+# Canonical paths without Windows' `\\?\` prefix, which git reads as a URL+# or refuses (`worktree add`); a no-op elsewhere.+dunce = "1.0"# The protocol types derive JSON Schema from themselves: `jan cli agent schema`# is generated, never hand-written, so a consumer validates against the types# rather than against a copy of them.diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lockindex 0a62e8ea9..88c28e772 100644--- a/src-tauri/jan-cli/Cargo.lock+++ b/src-tauri/jan-cli/Cargo.lock@@ -16,6 +16,7 @@ dependencies = ["comfy-table","console","dirs",+ "dunce","ed25519-dalek","env","env_logger",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 3bcdf389e..d8e6cc624 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -619,6 +619,7 @@ pub async fn start_monitor(allow_network: allow_network.unwrap_or(false),home_readonly: false,sandbox: true,+ workspace_readonly: false,};let set = {let mut sets = session_monitors().lock().unwrap();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex c57d302a7..5ba941a5c 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};use crate::tools::sandbox::{- command_touches_hidden_root, escapes_read_roots, escapes_write_roots, in_hidden_root,+ escapes_read_roots, escapes_write_roots, hidden_tokens, in_attached_root, in_hidden_root,};use crate::tools::{BuiltinTool, Capability};@@ -186,16 +186,36 @@ pub fn resolve_decision(// nor a routine "allow writes" approval reaches keys, hooks or the agent's// own permissions.if let Some(hidden) = ctx.hidden_root {+ // An attached root inside the home (a parent's view of its subagents'+ // worktrees) is the one part of it a read may reach. The read tools+ // only read. The shell may name it only while it stays in the sandbox+ // (`hidden_root` is set only then, and `escalate` leaves it) and the+ // sandbox mounts that root read-only (it is not also a write root):+ // otherwise `rm -rf` on a child's worktree would be one prompt away.+ let shell_reads_only = tool.capability == Capability::Exec+ && !requests_escalation(tool, args);+ let carved = |p: &str| match tool.capability {+ Capability::Read => {+ in_attached_root(ctx.project_root, ctx.scratch, ctx.read_roots, p)+ }+ Capability::Exec if shell_reads_only => {+ in_attached_root(ctx.project_root, ctx.scratch, ctx.read_roots, p)+ && !in_attached_root(ctx.project_root, ctx.scratch, ctx.write_roots, p)+ }+ _ => false,+ };+ let hidden_hit = |p: &str| {+ in_hidden_root(ctx.project_root, ctx.scratch, hidden, p) && !carved(p)+ };let hits_path = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .is_some_and(|p| in_hidden_root(ctx.project_root, ctx.scratch, hidden, p))+ .is_some_and(hidden_hit)});let hits_command = tool.capability == Capability::Exec- && args- .get("command")- .and_then(|v| v.as_str())- .is_some_and(|c| command_touches_hidden_root(ctx.project_root, ctx.scratch, hidden, c));+ && args.get("command").and_then(|v| v.as_str()).is_some_and(|c| {+ hidden_tokens(hidden, c).into_iter().any(|t| hidden_hit(&t))+ });if hits_path || hits_command {return Decision::HardDeny(DenyReason::Hidden);}@@ -1083,6 +1103,91 @@ mod tests {let _ = std::fs::remove_dir_all(&repo);}+ /// The parent may read its subagents' worktrees under `~/.jan/worktrees`+ /// through a read root: by path with the read tools, and from the shell+ /// only while it runs sandboxed, where the root is mounted read-only. The+ /// rest of the Jan home stays hidden, a read root grants no write, and a+ /// shell call that leaves the sandbox (`escalate`) or a root the sandbox+ /// mounts writable gets no carve-out at all.+ #[test]+ fn a_read_root_inside_the_jan_home_is_readable_and_nothing_else_there_is() {+ let home = unique_root();+ let jan = home.join(".jan");+ let trees = jan.join("worktrees/proj-1");+ std::fs::create_dir_all(trees.join("general-ab12")).unwrap();+ std::fs::write(trees.join("general-ab12/a.txt"), b"a").unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let roots = vec![trees.canonicalize().unwrap()];+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &roots,+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();+ let file = trees.join("general-ab12/a.txt");+ let read = |args| resolve_decision(lookup("read").unwrap(), &args, &ctx, &perms, &grants);+ assert_eq!(read(json!({"path": file.to_string_lossy()})), Decision::Allow);+ assert_eq!(+ read(json!({"path": jan.join("config.toml").to_string_lossy()})),+ Decision::HardDeny(DenyReason::Hidden)+ );+ let shell = |cmd: String| {+ resolve_decision(+ lookup(crate::tools::SHELL_TOOL).unwrap(),+ &json!({"command": cmd}),+ &ctx,+ &perms,+ &grants,+ )+ };+ assert_eq!(+ shell(format!("git -C {} diff", file.parent().unwrap().display())),+ Decision::Prompt(PromptKind::Exec),+ "an ordinary exec, not a hidden-path refusal"+ );+ assert_eq!(+ shell(format!("cat {}", jan.join("config.toml").display())),+ Decision::HardDeny(DenyReason::Hidden)+ );+ let write = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": file.to_string_lossy(), "content": "x"}),+ &ctx,+ &perms,+ &grants,+ );+ assert_eq!(write, Decision::HardDeny(DenyReason::Hidden), "a read root is not writable");+ // Out of the sandbox nothing mounts the root read-only, so a command+ // naming it is refused like any other path in the Jan home.+ let rm = format!("rm -rf {}", file.parent().unwrap().display());+ let unsandboxed = resolve_decision(+ lookup(crate::tools::SHELL_TOOL).unwrap(),+ &json!({"command": rm, ESCALATE_ARG: true}),+ &ctx,+ &perms,+ &grants,+ );+ assert_eq!(unsandboxed, Decision::HardDeny(DenyReason::Hidden));+ // Inside it, the same command meets a read-only mount.+ assert_eq!(shell(rm.clone()), Decision::Prompt(PromptKind::Exec));+ // A root the sandbox mounts writable is no read-only view.+ let writable = GateContext { write_roots: &roots, ..ctx };+ let in_writable = resolve_decision(+ lookup(crate::tools::SHELL_TOOL).unwrap(),+ &json!({"command": rm}),+ &writable,+ &perms,+ &grants,+ );+ assert_eq!(in_writable, Decision::HardDeny(DenyReason::Hidden));+ let _ = std::fs::remove_dir_all(&home);+ }+/// The Cowork opt-in at the gate layer: an attached root also passed as a/// write root takes the ordinary in-project Write prompt, not WriteEscape,/// while a path outside both roots keeps the escape classification.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 0fc8d6031..347f2b0a7 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -15,7 +15,7 @@ use crate::tools::jail;use crate::tools::proc;use crate::tools::nofollow;use crate::tools::sandbox::{- escapes_write_roots, hidden_under, in_scratch, landing, lexical_normalize,+ escapes_write_roots, hidden_under, in_read_only_root, in_scratch, landing, lexical_normalize,refuse_windows_name, resolve_path, scratch_display_path, symlink_escapes_any_root, Landing,};use crate::screenshot_pages::PageScope;@@ -220,6 +220,11 @@ async fn execute_text(// readable and unwritable."read" => read(args, project_root, scratch, ctx.read_roots).await.0,"ls" => ls(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,+ "write" if ctx.workspace_readonly+ && in_read_only_root(project_root, scratch, arg_str(args, "path").unwrap_or("")) =>+ {+ read_only_refusal(args, project_root)+ }"write" => {write(args,@@ -230,6 +235,11 @@ async fn execute_text().await}+ "edit" if ctx.workspace_readonly+ && in_read_only_root(project_root, scratch, arg_str(args, "path").unwrap_or("")) =>+ {+ read_only_refusal(args, project_root)+ }"edit" => {edit(args,@@ -986,6 +996,17 @@ async fn edit(}}+/// The refusal a `write`/`edit` gets for a path in a read-only root. Refused+/// here rather than left to the prompt, which auto-approval would answer.+fn read_only_refusal(args: &serde_json::Value, root: &Path) -> String {+ let path = arg_str(args, "path").unwrap_or_default();+ format!(+ "ERROR: {path} is in a read-only checkout ({}): this agent cannot change the project. \+ Write temporary files to the scratch directory instead.",+ root.display()+ )+}+/// The shell a confined command launches with: the (possibly jail-wrapped)/// shell config, the path the sandbox exposes as its temp dir, and the policy/// itself (which `denial_hint` reads even when the shell runs unconfined).@@ -1018,7 +1039,11 @@ pub(crate) fn confined_shell(if !ctx.write_roots.is_empty() {policy = policy.with_write_roots(ctx.write_roots.to_vec());}- let shell = if ctx.sandbox {+ policy = policy.with_workspace_readonly(ctx.workspace_readonly);+ // A read-only root is only read-only inside the sandbox, so it is never+ // run without one, whatever the surface chose.+ let confined = ctx.sandbox || ctx.workspace_readonly;+ let shell = if confined {// No confinement available means no shell: running unsandboxed would give// the command the whole machine, which is never what the caller asked for.let Some(wrapped) = jail::wrap(proc::shell(), &policy) else {@@ -1032,7 +1057,7 @@ pub(crate) fn confined_shell(} else {proc::shell().clone()};- let sandbox_tmp = if ctx.sandbox {+ let sandbox_tmp = if confined {jail::scratch_env_path(jail::backend(), &policy)} else {None@@ -1090,7 +1115,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// Cloned into the detached task, which is what keeps a backgrounded command// collecting output after this call has already returned.let sink = ctx.on_output.clone();- let sandboxed = ctx.sandbox;+ // A read-only root is confined even in an unsandboxed session, so its+ // denials get the note too.+ let sandboxed = ctx.sandbox || ctx.workspace_readonly;let escalation = ctx.escalation;// Fed from the first byte, so a command the user opens in `/shells` after it// backgrounded still shows what it printed before the timeout.@@ -1464,7 +1491,9 @@ fn sandbox_denial_note(out: &str, policy: &jail::Policy, escalation: bool) -> Streturn String::new();}let mut note = jail::denial_hint(policy);- if escalation {+ // Escalating drops the sandbox but not a read-only root, so offering it to+ // a read-only run only buys a pointless prompt.+ if escalation && !policy.workspace_readonly {note.push_str(ESCALATION_HINT);}note@@ -2282,6 +2311,48 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A read-only root: `write`/`edit` refuse anything under it outright,+ /// while reads keep working and the scratch stays writable.+ #[tokio::test]+ async fn a_read_only_root_refuses_writes_and_edits_under_it() {+ let root = unique_root();+ std::fs::write(root.join("a.txt"), "one").unwrap();+ let scratch = unique_root();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[])+ .with_scratch_root(&scratch)+ .with_workspace_readonly(true);+ for (tool, args) in [+ ("write", json!({"path": "a.txt", "content": "two"})),+ ("write", json!({"path": "new/b.txt", "content": "x"})),+ ("write", json!({"path": ".git/HEAD", "content": "x"})),+ ("edit", json!({"path": "a.txt", "edits": [{"old_string": "one", "new_string": "two"}]})),+ ] {+ let (out, _) = super::execute_builtin(lookup(tool).unwrap(), &args, &ctx).await;+ assert!(out.starts_with("ERROR") && out.contains("read-only"), "{tool}: {out}");+ }+ assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one");+ assert!(!root.join("new").exists());+ let (read, _) =+ super::execute_builtin(lookup("read").unwrap(), &json!({"path": "a.txt"}), &ctx).await;+ assert_eq!(read, "one");+ // `/tmp/...` names the scratch on Linux; elsewhere its real path does.+ let in_scratch = if cfg!(target_os = "linux") {+ "/tmp/note.txt".to_string()+ } else {+ scratch.join("note.txt").to_string_lossy().into_owned()+ };+ let (out, _) = super::execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": in_scratch, "content": "ok"}),+ &ctx,+ )+ .await;+ assert!(!out.starts_with("ERROR"), "{out}");+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }+#[tokio::test]async fn write_then_read_roundtrips() {let root = unique_root();@@ -3830,6 +3901,24 @@ mod tests {assert!(sandbox_denial_note("Read-only file system\n[exit 0]", &policy, true).is_empty());}+ /// A read-only workspace is named as read-only, never as where writes go,+ /// and escalation is not offered: it would not lift the read-only root.+ #[test]+ fn a_read_only_workspace_denial_says_read_only_and_offers_no_escalation() {+ let policy = jail::Policy::new(Path::new("/w"), true)+ .with_scratch_root(Path::new("/var/scratch/jan-agent-s1"))+ .with_workspace_readonly(true);+ let denied = "touch: cannot touch '/w/x': Read-only file system\n[exit 1]";+ let note = sandbox_denial_note(denied, &policy, true);+ assert!(note.contains("the workspace (/w) is read-only"), "got: {note}");+ assert!(note.contains("writes are limited to the scratch dir"), "got: {note}");+ assert!(!note.contains("writes are limited to the workspace"), "got: {note}");+ assert!(!note.contains("escalate"), "got: {note}");+ let bare = jail::Policy::new(Path::new("/w"), true).with_workspace_readonly(true);+ let note = sandbox_denial_note(denied, &bare, false);+ assert!(note.contains("is read-only and nothing here is writable"), "got: {note}");+ }+#[test]fn bash_result_failed_detects_nonzero_and_signal_markers() {assert!(bash_result_failed("output\n[exit 1]"));diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex f983f8a6f..2784b76fd 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -99,6 +99,10 @@ pub struct Policy {/// read-only `$HOME`, inside the workspace (running in `$HOME`), or around/// it (a Jan worktree in `~/.jan/worktrees/`). See [`Policy::with_hide_root`].pub hide_root: Option<PathBuf>,+ /// Bind the workspace read-only: a read-only subagent works in the user's+ /// checkout and must not change it, `.git` included. The scratch and any+ /// `write_roots` stay writable. See [`Policy::with_workspace_readonly`].+ pub workspace_readonly: bool,}impl Policy {@@ -112,9 +116,18 @@ impl Policy {read_roots: Vec::new(),write_roots: Vec::new(),hide_root: None,+ workspace_readonly: false,}}+ /// Keep the workspace readable but not writable. AppContainer grants its+ /// workspace by a write ACE and has no read-only form, so [`wrap`] refuses+ /// such a policy there: no shell rather than a writable one.+ pub fn with_workspace_readonly(mut self, readonly: bool) -> Self {+ self.workspace_readonly = readonly;+ self+ }+/// Hide `hide_root` from the sandboxed shell. The gate's token scan of the/// command string is best-effort; this is what makes the directory/// unreachable to the spellings a scan cannot see (`cd ~; cat .jan/*`, a@@ -267,6 +280,7 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {// a re-exec of this binary that performs the confined spawn itself. If// the running binary cannot be located there is no wrapper to run, and// returning `cfg` unchanged would run the command with no confinement.+ Backend::AppContainer if policy.workspace_readonly => None,Backend::AppContainer => Some(ShellConfig {program: std::env::current_exe().ok()?,args: appcontainer::helper_args(@@ -529,7 +543,8 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {push(&mut args, &["--bind", &root, &root]);}- push(&mut args, &["--bind", &ws, &ws]);+ let bind = if policy.workspace_readonly { "--ro-bind" } else { "--bind" };+ push(&mut args, &[bind, &ws, &ws]);// And again after, when a bind contains it (running in `$HOME`): the// workspace bind would otherwise shadow the mask above and re-expose it.if let Some(hide) = policy.hide_root.as_deref().filter(|h| policy.hide_under_a_bind(h)) {@@ -573,11 +588,54 @@ fn seatbelt_program() -> &'static str {const HIDE_RULES: &str = "(deny file-read* (subpath (param \"HIDE_ROOT\")))\n\(deny file-write* (subpath (param \"HIDE_ROOT\")))\n";+/// The resolved form of `path` when it differs from `path` itself. Seatbelt+/// matches a `subpath` against the real path, so a rule naming a path through+/// a symlink (`/var/folders/...` and `/tmp` are links to `/private/...` on+/// macOS) never fires unless the resolved form is named too.+fn real_form(path: &Path) -> Option<PathBuf> {+ path.canonicalize().ok().filter(|real| real != path)+}++/// The paths a Seatbelt profile names beyond the policy's own fields, worked+/// out once so the profile and its `-D` arguments always agree: sandbox-exec+/// refuses a profile referencing a parameter no argument supplies.+struct SeatbeltPaths {+ scratch_real: Option<PathBuf>,+ /// The read-only checkout and read roots, each in every form it has.+ deny_write: Vec<PathBuf>,+}++impl SeatbeltPaths {+ fn of(policy: &Policy) -> Self {+ let readonly = policy+ .workspace_readonly+ .then_some(&policy.workspace)+ .into_iter()+ .chain(policy.read_roots.iter().filter(|r| !policy.write_roots.contains(r)));+ let mut deny_write: Vec<PathBuf> = Vec::new();+ for root in readonly {+ for form in std::iter::once(root.clone()).chain(real_form(root)) {+ if !deny_write.contains(&form) {+ deny_write.push(form);+ }+ }+ }+ Self {+ scratch_real: policy.scratch_root.as_deref().and_then(real_form),+ deny_write,+ }+ }+}+/// Seatbelt profile. `(deny default)` closes everything, then each section opens/// the narrowest thing that works. Later rules win, which is what lets the/// workspace be re-allowed after `$HOME` is denied (or, with `home_readonly`,/// lets the home stay readable while writes remain confined).pub fn seatbelt_policy(policy: &Policy) -> String {+ seatbelt_profile(policy, &SeatbeltPaths::of(policy))+}++fn seatbelt_profile(policy: &Policy, paths: &SeatbeltPaths) -> String {let mut p = String::from("(version 1)\n\(deny default)\n\@@ -620,13 +678,28 @@ pub fn seatbelt_policy(policy: &Policy) -> String {if policy.hide_root.is_some() && !hide_last {p.push_str(HIDE_RULES);}+ p.push_str("(allow file-read* (subpath (param \"WORKSPACE\")))\n");+ // Not the host temp dir (`$TMPDIR`, `/var/folders/...`): the shell's+ // `TMPDIR` is the session scratch, granted by name below, and the host+ // one holds other programs' files, which must not be writable here.p.push_str(- "(allow file-read* (subpath (param \"WORKSPACE\")))\n\- ; Writes: the workspace and the temp dir, nothing else.\n\- (allow file-write* (subpath (param \"WORKSPACE\")))\n\- (allow file-write* (subpath (param \"TMPDIR\")))\n\+ "; Writes: the workspace, the scratch and /private/tmp, nothing else.\n\(allow file-write* (subpath \"/private/tmp\"))\n",);+ // The `/private/tmp` grant above is broad, so a read-only checkout or read+ // root under it (a project in `/tmp`) would be writable through it. Denied+ // after them, and before the scratch and write-root allows below so those+ // stay writable even inside such a root.+ for i in 0..paths.deny_write.len() {+ p.push_str(&format!(+ "(deny file-write* (subpath (param \"DENY_WRITE_{i}\")))\n"+ ));+ }+ // After the denials, as bubblewrap binds the workspace after the read+ // roots: a writable workspace inside a read root stays writable.+ if !policy.workspace_readonly {+ p.push_str("(allow file-write* (subpath (param \"WORKSPACE\")))\n");+ }// The session scratch by name, rather than trusting it to sit under TMPDIR:// a relocated scratch must stay usable, and it is read back after the home// denial above, which would otherwise cover a scratch inside $HOME. Emitted@@ -638,6 +711,12 @@ pub fn seatbelt_policy(policy: &Policy) -> String {(allow file-write* (subpath (param \"SCRATCH\")))\n",);}+ if paths.scratch_real.is_some() {+ p.push_str(+ "(allow file-read* (subpath (param \"SCRATCH_REAL\")))\n\+ (allow file-write* (subpath (param \"SCRATCH_REAL\")))\n",+ );+ }// After the HOME/MASK denials, so an attached folder inside either is read// back: in Seatbelt the later rule wins. Read only — no matching// `file-write*`, so `(deny default)` keeps the folder unwritable. Emitted@@ -681,7 +760,8 @@ pub fn seatbelt_policy(policy: &Policy) -> String {/// interpolated into the profile so a path containing profile syntax cannot/// rewrite the policy.pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {- let mut args = vec!["-p".to_string(), seatbelt_policy(policy)];+ let paths = SeatbeltPaths::of(policy);+ let mut args = vec!["-p".to_string(), seatbelt_profile(policy, &paths)];args.push(format!("-DWORKSPACE={}",policy.workspace.to_string_lossy()@@ -698,13 +778,15 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {for (i, root) in policy.write_roots.iter().enumerate() {args.push(format!("-DWRITE_ROOT_{i}={}", root.to_string_lossy()));}- args.push(format!(- "-DTMPDIR={}",- std::env::temp_dir().to_string_lossy()- ));+ for (i, root) in paths.deny_write.iter().enumerate() {+ args.push(format!("-DDENY_WRITE_{i}={}", root.to_string_lossy()));+ }if let Some(scratch) = &policy.scratch_root {args.push(format!("-DSCRATCH={}", scratch.to_string_lossy()));}+ if let Some(real) = &paths.scratch_real {+ args.push(format!("-DSCRATCH_REAL={}", real.to_string_lossy()));+ }if let Some(home) = home_dir() {args.push(format!("-DHOME_ROOT={}", home.to_string_lossy()));}@@ -803,6 +885,20 @@ pub fn denial_hint(policy: &Policy) -> String {}s};+ // A read-only workspace is not a place writes may go: naming it as one sends+ // the model straight back to retry there.+ if policy.workspace_readonly {+ let scratch = scratch.strip_prefix(" and ").unwrap_or("");+ let writes = if scratch.is_empty() {+ " and nothing here is writable".to_string()+ } else {+ format!("; writes are limited to {scratch}")+ };+ return format!(+ "\n[sandbox: the workspace ({}) is read-only{writes}{home}.{net}{attached}]",+ policy.workspace.display()+ );+ }format!("\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}{attached}]",policy.workspace.display()@@ -1157,6 +1253,26 @@ mod tests {assert!(!seatbelt_policy(&policy()).contains("HIDE_ROOT"));}+ /// A read-only subagent's checkout is bound read-only, `.git` included+ /// (it is inside the bind), while the scratch stays the writable `/tmp`.+ #[test]+ fn bwrap_binds_a_read_only_workspace_read_only() {+ let ws = "/data/agent-workspace/threads/t1";+ let text = joined(&bwrap_args(&policy().with_workspace_readonly(true), &cfg()));+ assert!(text.contains(&format!("--ro-bind {ws} {ws}")), "{text}");+ assert!(!text.contains(&format!("--bind {ws} {ws}")), "{text}");+ assert!(text.contains(&format!("--chdir {ws}")), "{text}");+ }++ #[test]+ fn seatbelt_never_allows_writes_to_a_read_only_workspace() {+ let write = "(allow file-write* (subpath (param \"WORKSPACE\")))";+ assert!(seatbelt_policy(&policy()).contains(write));+ let p = seatbelt_policy(&policy().with_workspace_readonly(true));+ assert!(!p.contains(write), "{p}");+ assert!(p.contains("(allow file-read* (subpath (param \"WORKSPACE\")))"), "{p}");+ }+#[test]fn bwrap_mounts_root_read_only_before_layering_on_it() {let args = bwrap_args(&policy(), &cfg());@@ -1417,15 +1533,150 @@ mod tests {}}+ /// The `/private/tmp` grant is broad, and in Seatbelt the later rule wins:+ /// a read-only checkout under it must be denied writes after it, by every+ /// name it has, or it is writable after all.+ #[test]+ fn seatbelt_denies_writes_to_a_read_only_checkout_under_the_temp_grants() {+ let ws = Path::new("/private/tmp/checkout");+ let ro = Policy::new(ws, false)+ .with_workspace_readonly(true)+ .with_read_roots(vec![PathBuf::from("/private/tmp/worktrees")]);+ let p = seatbelt_policy(&ro);+ let deny = "(deny file-write* (subpath (param \"DENY_WRITE_0\")))";+ let at = p.find(deny).expect(&p);+ assert!(p.find("(allow file-write* (subpath \"/private/tmp\"))").unwrap() < at, "{p}");+ assert!(p.contains("(deny file-write* (subpath (param \"DENY_WRITE_1\")))"), "{p}");+ let args = seatbelt_args(&ro, &cfg());+ assert!(args.iter().any(|a| a == "-DDENY_WRITE_0=/private/tmp/checkout"), "{args:?}");+ assert!(args.iter().any(|a| a == "-DDENY_WRITE_1=/private/tmp/worktrees"), "{args:?}");+ // A writable workspace, and a read root also marked writable, get none.+ let rw = Policy::new(ws, false)+ .with_read_roots(vec![PathBuf::from("/r")])+ .with_write_roots(vec![PathBuf::from("/r")]);+ assert!(!seatbelt_policy(&rw).contains("DENY_WRITE"));+ assert!(!seatbelt_args(&rw, &cfg()).iter().any(|a| a.contains("DENY_WRITE")));+ }++ /// The scratch and the write roots stay writable even inside a read-only+ /// checkout: their allows come after its denial.+ #[test]+ fn seatbelt_keeps_the_scratch_and_write_roots_writable_past_the_denial() {+ let ro = Policy::new(Path::new("/Users/u"), false)+ .with_workspace_readonly(true)+ .with_scratch_root(Path::new("/Users/u/.jan/scratch/s1"))+ .with_write_roots(vec![PathBuf::from("/Users/u/.jan/worktrees/r/cargo-target")]);+ let p = seatbelt_policy(&ro);+ let deny = p.find("(param \"DENY_WRITE_0\")").expect(&p);+ assert!(deny < p.find("(allow file-write* (subpath (param \"SCRATCH\")))").unwrap(), "{p}");+ assert!(deny < p.find("(allow file-write* (subpath (param \"WRITE_ROOT_0\")))").unwrap());+ // A parent session in a Jan worktree reads its children's worktrees+ // beside it: that read root's denial must not cover its own checkout.+ let parent = Policy::new(Path::new("/Users/u/.jan/worktrees/r/feat"), false)+ .with_read_roots(vec![PathBuf::from("/Users/u/.jan/worktrees/r")]);+ let p = seatbelt_policy(&parent);+ let deny = p.find("(param \"DENY_WRITE_0\")").expect(&p);+ let ws = p.find("(allow file-write* (subpath (param \"WORKSPACE\")))").unwrap();+ assert!(deny < ws, "{p}");+ }++ /// Seatbelt matches a `subpath` against the resolved path, so a path that+ /// goes through a symlink (`/var` -> `/private/var` on macOS) is named in+ /// both forms, or the rule never fires.+ #[cfg(unix)]+ #[test]+ fn seatbelt_names_symlinked_paths_in_their_resolved_form_too() {+ let base = std::env::temp_dir().join(format!("jan-sb-forms-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ let real = base.join("real");+ std::fs::create_dir_all(real.join("ws")).unwrap();+ std::fs::create_dir_all(real.join("scratch")).unwrap();+ std::os::unix::fs::symlink(&real, base.join("link")).unwrap();+ let real = real.canonicalize().unwrap();+ let (ws, scratch) = (base.join("link/ws"), base.join("link/scratch"));+ let ro = Policy::new(&ws, false)+ .with_workspace_readonly(true)+ .with_scratch_root(&scratch);+ let p = seatbelt_policy(&ro);+ let args = seatbelt_args(&ro, &cfg());+ let has = |arg: String| args.contains(&arg);+ assert!(has(format!("-DDENY_WRITE_0={}", ws.display())), "{args:?}");+ assert!(has(format!("-DDENY_WRITE_1={}", real.join("ws").display())), "{args:?}");+ assert!(p.contains("(deny file-write* (subpath (param \"DENY_WRITE_1\")))"), "{p}");+ assert!(has(format!("-DSCRATCH_REAL={}", real.join("scratch").display())), "{args:?}");+ assert!(p.contains("(allow file-write* (subpath (param \"SCRATCH_REAL\")))"), "{p}");+ assert!(p.contains("(allow file-read* (subpath (param \"SCRATCH_REAL\")))"), "{p}");+ // Unresolvable or already resolved: one form, and no stray parameter.+ let plain = policy().with_scratch_root(Path::new("/var/scratch/jan-agent-s1"));+ assert!(!seatbelt_policy(&plain).contains("SCRATCH_REAL"));+ assert!(!seatbelt_args(&plain, &cfg()).iter().any(|a| a.contains("SCRATCH_REAL")));+ let _ = std::fs::remove_dir_all(&base);+ }++ /// bubblewrap layers in order, so a read-only checkout under `/tmp` is+ /// bound read-only after the scratch takes `/tmp`, never shadowed by it.+ #[test]+ fn bwrap_binds_a_read_only_checkout_under_tmp_after_the_scratch() {+ let ws = "/tmp/checkout";+ let ro = Policy::new(Path::new(ws), false)+ .with_workspace_readonly(true)+ .with_scratch_root(Path::new("/tmp/scratch-s1"))+ .with_read_roots(vec![PathBuf::from("/tmp/worktrees")]);+ let text = joined(&bwrap_args(&ro, &cfg()));+ let scratch = text.find("--bind /tmp/scratch-s1 /tmp").expect(&text);+ assert!(scratch < text.find(&format!("--ro-bind {ws} {ws}")).expect(&text), "{text}");+ assert!(scratch < text.find("--ro-bind /tmp/worktrees /tmp/worktrees").unwrap());+ assert!(!text.contains(&format!("--bind {ws} ")), "{text}");+ }+#[test]fn seatbelt_confines_writes_to_the_workspace_and_temp() {let p = seatbelt_policy(&policy());assert!(p.contains("(allow file-write* (subpath (param \"WORKSPACE\")))"));- assert!(p.contains("(allow file-write* (subpath (param \"TMPDIR\")))"));+ assert!(p.contains("(allow file-write* (subpath \"/private/tmp\"))"));// No blanket write rule anywhere.assert!(!p.contains("(allow file-write*)"));}+ /// The host temp dir is not the shell's: its `TMPDIR` is the session+ /// scratch, granted by name. No write allow may name the host temp dir,+ /// in its given or resolved form (`/var/folders/...` resolves to+ /// `/private/var/folders/...` on macOS), or anything above it.+ #[test]+ fn seatbelt_never_grants_writes_to_the_host_temp_dir() {+ let tmp = std::env::temp_dir();+ let forms: Vec<PathBuf> = std::iter::once(tmp.clone()).chain(real_form(&tmp)).collect();+ let scratch = tmp.join(format!("jan-agent-tmpgrant-{}", std::process::id()));+ std::fs::create_dir_all(&scratch).unwrap();+ let ws = Path::new("/data/agent-workspace/threads/t1");+ let policy = Policy::new(ws, false).with_scratch_root(&scratch);+ let p = seatbelt_policy(&policy);+ let args = seatbelt_args(&policy, &cfg());+ let _ = std::fs::remove_dir_all(&scratch);+ for line in p.lines().filter(|l| l.starts_with("(allow file-write*")) {+ let granted = match line.split_once("(param \"") {+ Some((_, rest)) => {+ let name = rest.split('"').next().unwrap();+ let value = args+ .iter()+ .find_map(|a| a.strip_prefix(&format!("-D{name}=")))+ .unwrap_or_else(|| panic!("{name} has no argument: {args:?}"));+ PathBuf::from(value)+ }+ None => match line.split_once("(subpath \"") {+ Some((_, rest)) => PathBuf::from(rest.split('"').next().unwrap()),+ None => continue,+ },+ };+ for form in &forms {+ assert!(!form.starts_with(&granted), "{line} grants {form:?}:\n{p}");+ }+ }+ // The scratch inside it stays writable, by its resolved name too.+ assert!(p.contains("(allow file-write* (subpath (param \"SCRATCH\")))"), "{p}");+ assert!(!args.iter().any(|a| a.starts_with("-DTMPDIR")), "{args:?}");+ }+/// The scratch is granted by name rather than relying on it happening to sit/// under the host temp dir, so a relocated scratch stays writable.#[test]@@ -1824,6 +2075,33 @@ mod enforcement_tests {assert!(!ok, "network must be denied by default");}+ /// A read-only subagent cannot change its checkout from the shell, not even+ /// its `.git`, while the scratch it was given stays writable.+ #[tokio::test]+ #[cfg(target_os = "linux")]+ async fn a_read_only_workspace_refuses_writes_but_the_scratch_does_not() {+ require_backend!();+ let ws = workspace();+ std::fs::create_dir_all(ws.join(".git")).unwrap();+ std::fs::write(ws.join("kept.txt"), b"original").unwrap();+ let scratch = workspace();+ let policy = Policy::new(&ws, false)+ .with_scratch_root(&scratch)+ .with_workspace_readonly(true);+ let (ok, out) = run_policy(policy.clone(), &ws, "echo changed > kept.txt").await;+ assert!(!ok, "{out}");+ let (ok, out) = run_policy(policy.clone(), &ws, "touch .git/index.lock").await;+ assert!(!ok, "{out}");+ let (ok, out) = run_policy(policy, &ws, "cat kept.txt && echo s > /tmp/s.txt").await;+ let kept = std::fs::read_to_string(ws.join("kept.txt")).unwrap();+ let scratched = scratch.join("s.txt").exists();+ let _ = std::fs::remove_dir_all(&ws);+ let _ = std::fs::remove_dir_all(&scratch);+ assert!(ok && out.contains("original"), "reads still work: {out}");+ assert_eq!(kept, "original");+ assert!(scratched, "the scratch stays writable");+ }+/// A relocated store root (e.g. `JAN_DATA_FOLDER` outside `$HOME`) must not/// be readable by the shell, even when it is not under the user's home.#[tokio::test]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 2bb180707..a4bd08571 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -223,6 +223,11 @@ pub struct ToolContext<'a> {/// it. `None` keeps the default: keyless Exa, upgraded by an `EXA_API_KEY`/// in the environment.pub web_search: Option<&'a tauri_plugin_websearch::provider::WebSearchConfig>,+ /// `project_root` is read-only: a read-only subagent working in the user's+ /// checkout. `write`/`edit` refuse any path under it (the scratch stays+ /// writable), and the shell runs only confined, with the root bound+ /// read-only; with no sandbox backend there is no shell at all.+ pub workspace_readonly: bool,}impl std::fmt::Debug for ToolContext<'_> {@@ -256,6 +261,7 @@ impl std::fmt::Debug for ToolContext<'_> {.field("screenshot_backend", &self.screenshot_backend.is_some()).field("hooks", &self.hooks.map(|h| h.len()).unwrap_or(0)).field("plan_mode", &self.plan_mode)+ .field("workspace_readonly", &self.workspace_readonly).field("hook_sink", &self.hook_sink.is_some()).field("shell_done_sink", &self.shell_done_sink.is_some()).field("detach_signal", &self.detach_signal.is_some())@@ -418,9 +424,16 @@ impl<'a> ToolContext<'a> {shell_done_sink: None,detach_signal: None,web_search: None,+ workspace_readonly: false,}}+ /// Make `project_root` read-only. See [`Self::workspace_readonly`].+ pub fn with_workspace_readonly(mut self, readonly: bool) -> Self {+ self.workspace_readonly = readonly;+ self+ }+/// Route the web tools to the host's chosen backend. See/// [`Self::web_search`].pub fn with_web_search(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rsindex 3d6da1ef2..93fb01f16 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs@@ -65,6 +65,7 @@ pub struct MonitorCtx {pub allow_network: bool,pub home_readonly: bool,pub sandbox: bool,+ pub workspace_readonly: bool,}impl MonitorCtx {@@ -79,6 +80,7 @@ impl MonitorCtx {allow_network: ctx.allow_network,home_readonly: ctx.home_readonly,sandbox: ctx.sandbox,+ workspace_readonly: ctx.workspace_readonly,}}@@ -92,7 +94,8 @@ impl MonitorCtx {.with_sandbox(self.sandbox).with_read_roots(&self.read_roots).with_write_roots(&self.write_roots)- .with_hidden_root(self.hidden_root.as_deref());+ .with_hidden_root(self.hidden_root.as_deref())+ .with_workspace_readonly(self.workspace_readonly);if let Some(mask) = &self.mask_root {ctx = ctx.with_mask_root(mask);}@@ -617,6 +620,7 @@ mod tests {home_readonly: false,// Bare shell: these tests exercise the monitor loop, not the jail.sandbox: false,+ workspace_readonly: false,}}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex 2756f13df..4e4c10304 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -296,6 +296,25 @@ fn tmp_relative(raw: &str) -> Option<String> {Some(raw.strip_prefix("/tmp/")?.to_string())}+/// True iff a write to `raw` would land in a read-only `project_root`: inside+/// it and not in the session scratch (which a read-only subagent still writes+/// to). Fails closed: a path that cannot be resolved counts as inside.+pub fn in_read_only_root(project_root: &Path, scratch: Option<&Path>, raw: &str) -> bool {+ let target = resolve_path(project_root, scratch, raw);+ let Ok(resolved) = canonicalize_lenient(&target) else {+ return true;+ };+ if let Some(scratch) = scratch.and_then(|s| s.canonicalize().ok()) {+ if resolved.starts_with(&scratch) {+ return false;+ }+ }+ match project_root.canonicalize() {+ Ok(root) => resolved.starts_with(root),+ Err(_) => true,+ }+}+/// True iff `raw` resolves inside `hidden` (the Jan home, `~/.jan`), which holds/// `config.toml` with provider keys and hooks plus every project's store. The/// memory/skill tools reach the store by name and never come through here.@@ -319,28 +338,41 @@ pub fn in_hidden_root(project_root: &Path, scratch: Option<&Path>, hidden: &Path}}-/// True iff a shell command names a path inside `hidden` (best-effort token-/// scan). `~` and `$HOME` are expanded, since `cat ~/.jan/config.toml` is the-/// obvious spelling. Best-effort is enough only because the OS sandbox masks-/// the directory too (see [`super::jail::Policy::hide_root`]); this turns a-/// plain attempt into a clear refusal instead of an empty directory.-pub fn command_touches_hidden_root(- project_root: &Path,- scratch: Option<&Path>,- hidden: &Path,- command: &str,-) -> bool {+/// The path-like tokens of a shell command (best-effort), `~` and `$HOME`+/// expanded against the home `hidden` sits in, since that is the obvious way+/// to spell a path under it. The gate refuses a command when one of them is+/// in the hidden root; best-effort is enough only because the OS sandbox+/// masks the directory too (see [`super::jail::Policy::hide_root`]).+pub fn hidden_tokens(hidden: &Path, command: &str) -> Vec<String> {let home = hidden.parent().map(|h| h.to_string_lossy().into_owned());command.split(|c: char| c.is_whitespace() || ";|&><()\"'`=".contains(c)).filter(|t| !t.is_empty())- .any(|t| {- let expanded = match &home {- Some(home) => expand_home(t, home),- None => t.to_string(),- };- in_hidden_root(project_root, scratch, hidden, &expanded)+ .map(|t| match &home {+ Some(home) => expand_home(t, home),+ None => t.to_string(),})+ .collect()+}++/// True iff `raw` resolves inside one of `roots` (canonicalized attached+/// folders). Relative paths belong to the project, never to a root.+pub fn in_attached_root(+ project_root: &Path,+ scratch: Option<&Path>,+ roots: &[PathBuf],+ raw: &str,+) -> bool {+ if roots.is_empty() || !Path::new(raw).is_absolute() {+ return false;+ }+ let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, scratch, raw)) else {+ return false;+ };+ roots+ .iter()+ .filter_map(|r| r.canonicalize().ok())+ .any(|r| resolved.starts_with(r))}fn expand_home(token: &str, home: &str) -> String {@@ -1039,6 +1071,17 @@ mod tests {let _ = std::fs::remove_dir_all(&home);}+ fn command_touches_hidden_root(+ project: &Path,+ scratch: Option<&Path>,+ hidden: &Path,+ cmd: &str,+ ) -> bool {+ hidden_tokens(hidden, cmd)+ .iter()+ .any(|t| in_hidden_root(project, scratch, hidden, t))+ }+#[test]fn command_scan_expands_home_spellings() {let home = unique_root();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex 079b880cf..31464ac63 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -109,14 +109,43 @@ pub fn path_slug(path: &Path) -> String {format!("{name}-{}", path_hash(path))}+/// The main checkout a Jan subagent checkout at `top` (a `git clone --shared`+/// at `<jan home>/worktrees/<slug>/<id>`) borrows its objects from: the+/// `<main>/.git/objects` its alternates name, canonicalized. `None` for any+/// other repository.+///+/// A writer can rewrite its own alternates, so they are trusted only when they+/// name the project whose slug the clone was created under; otherwise a kept+/// checkout could steer later sessions into another project's store.+fn shared_clone_origin(top: &Path) -> Option<PathBuf> {+ let worktrees = jan_home()?.join("worktrees");+ let worktrees = worktrees.canonicalize().unwrap_or(worktrees);+ let slug_dir = top.parent()?;+ if slug_dir.parent()? != worktrees {+ return None;+ }+ let raw = std::fs::read_to_string(top.join(".git/objects/info/alternates")).ok()?;+ let objects = Path::new(raw.lines().next()?.trim());+ let git = objects.parent()?;+ if objects.file_name()? != "objects" || git.file_name()? != ".git" {+ return None;+ }+ // The alternates spell `main` however git was handed it (forward slashes+ // on Windows, an unresolved symlink), and the slug hashes that text.+ let main = git.parent()?;+ let main = main.canonicalize().unwrap_or_else(|_| main.to_path_buf());+ (slug_dir.file_name()? == path_slug(&main).as_str()).then_some(main)+}+/// The path a project's store is keyed on: the project root, canonicalized,-/// with a linked git worktree mapped back onto its main checkout.+/// with a Jan subagent checkout or a linked git worktree mapped back onto its+/// main checkout.////// Without the mapping, a session running in `~/.jan/worktrees/<slug>/<id>`/// would get a fresh, empty store and lose the project's memory, skills and/// config. A subdirectory of a worktree maps to the same subdirectory of the-/// main checkout. Read straight from the `.git` file rather than by running-/// `git`, because this runs on every store lookup.+/// main checkout. Read straight from the `.git` file or the alternates rather+/// than by running `git`, because this runs on every store lookup.pub fn project_key(project_root: &Path) -> PathBuf {let root = project_root.canonicalize()@@ -124,7 +153,11 @@ pub fn project_key(project_root: &Path) -> PathBuf {for top in root.ancestors() {let dot_git = top.join(".git");if dot_git.is_dir() {- return root;+ return match (shared_clone_origin(top), root.strip_prefix(top)) {+ (Some(main), Ok(rel)) if rel.as_os_str().is_empty() => main,+ (Some(main), Ok(rel)) => main.join(rel),+ _ => root,+ };}if !dot_git.is_file() {continue;@@ -864,6 +897,49 @@ mod tests {let _ = std::fs::remove_dir_all(&base);}+ /// A Jan subagent checkout (`git clone --shared` under the Jan home's+ /// `worktrees/`) shares its main checkout's store too; the same clone made+ /// anywhere else is a project of its own.+ #[test]+ fn a_shared_clone_under_the_jan_worktrees_keys_on_its_main_checkout() {+ let main = unique_data_folder().join("main");+ std::fs::create_dir_all(main.join(".git/objects")).unwrap();+ let worktrees = jan_home().unwrap().join("worktrees");+ // Unique ids: the Jan home is shared by every test in this process.+ let id = unique_data_folder().file_name().unwrap().to_owned();+ let slug_dir = worktrees.join(path_slug(&main.canonicalize().unwrap()));+ let clone = slug_dir.join(&id);+ // A writer that rewrote its alternates to name a project other than+ // the one its slug directory belongs to.+ let forged = worktrees.join("other-0").join(&id);+ let elsewhere = unique_data_folder().join("clone");+ for dir in [&clone, &forged, &elsewhere] {+ std::fs::create_dir_all(dir.join(".git/objects/info")).unwrap();+ std::fs::write(+ dir.join(".git/objects/info/alternates"),+ format!("{}\n", main.join(".git/objects").display()),+ )+ .unwrap();+ std::fs::create_dir_all(dir.join("sub")).unwrap();+ }+ let main = main.canonicalize().unwrap();+ // The store slug hashes the path's text, which `Path` equality does not+ // compare: a trailing slash or another spelling of `main` would pass+ // `==` and still land in a different, empty store.+ assert_eq!(project_key(&clone).as_os_str(), main.as_os_str());+ assert_eq!(path_slug(&project_key(&clone)), path_slug(&main));+ assert_eq!(+ project_key(&clone.join("sub")).as_os_str(),+ main.join("sub").as_os_str()+ );+ assert_eq!(project_key(&elsewhere), elsewhere.canonicalize().unwrap());+ assert_eq!(project_key(&forged), forged.canonicalize().unwrap());+ let _ = std::fs::remove_dir_all(&slug_dir);+ let _ = std::fs::remove_dir_all(forged.parent().unwrap());+ let _ = std::fs::remove_dir_all(elsewhere.parent().unwrap());+ let _ = std::fs::remove_dir_all(main.parent().unwrap());+ }+/// The whole point of the split: a thread sandbox is a sibling of the store,/// so no relative path from inside it stays within the sandbox and reaches/// memory. `escapes_project` refuses the climb.diff --git a/src-tauri/src/core/agent/child_workspace.rs b/src-tauri/src/core/agent/child_workspace.rsnew file mode 100644index 000000000..d2b2660e8--- /dev/null+++ b/src-tauri/src/core/agent/child_workspace.rs@@ -0,0 +1,1797 @@+//! Where a dispatched subagent works: its own checkout, or the parent's+//! checkout, read-only unless it is a writer.+//!+//! Decided by the harness when the child is dispatched, never by a tool the+//! model calls. A child whose tool set can change files (`write`/`edit`) is a+//! *writer* and gets a fresh checkout on `jan/agent/<name>-<id>`, so parallel+//! writers never edit one checkout and none of them mixes its edits with the+//! user's uncommitted work. Every other child is a *reader*: it runs in the+//! checkout it was given with that checkout read-only, enforced by the file+//! tools and by a sandbox that is always on for it.+//!+//! A child's checkout (a "worktree" to the user) is a repository of its own,+//! made by `git clone --shared`: it borrows the user's objects read-only and+//! keeps its refs, index, config and hooks to itself, so a sandboxed child+//! never writes the user's `.git` (which git reads, unsandboxed, the next time+//! the user works). Its branch comes back as `jan/agent/<name>-<id>` in the+//! user's repository when the child finishes, by a fetch that runs none of+//! the child's config (see [`Checkout`](crate::core::agent::git::Checkout)).+//!+//! A dispatch item's optional `workspace` overrides the default: `"new"`, a+//! fresh checkout; `"shared"`, the parent's checkout; the name of an earlier+//! subagent, that subagent's workspace; `{"ref": "<git ref>"}`, a fresh+//! checkout at that ref (fetched from `origin` when it is not local).+//!+//! Checkouts live under `~/.jan/worktrees/<project-slug>/`, never under `/tmp`+//! (the sandbox binds the session scratch over `/tmp`). The ledger here+//! remembers every child's workspace for the session, so a later dispatch can+//! name it, and at the session's end removes the checkouts that hold nothing:+//! no commit past their base and no uncommitted change, `ref` ones included+//! (a writer may have committed there). One git cannot read is kept.+//!+//! Only the CLI build creates checkouts and holds readers to a read-only+//! checkout; on the desktop every child works in its parent's checkout as it+//! always has (see [`READ_ONLY_READERS`]).++use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};++/// The `workspace` a dispatch item asked for.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum WorkspaceRequest {+ /// A fresh worktree from the parent checkout's `HEAD`.+ New,+ /// The parent's own checkout.+ Shared,+ /// The workspace of an earlier subagent of this session, by name.+ Reuse(String),+ /// A fresh worktree at a git ref.+ Ref(String),+}++/// Parse a dispatch item's `workspace` value. `None` when it is absent (the+/// writer/reader default applies).+pub(crate) fn parse_request(+ value: Option<&serde_json::Value>,+) -> Result<Option<WorkspaceRequest>, String> {+ let bad = || {+ "invalid 'workspace': use \"new\", \"shared\", the name of an earlier subagent, or \+ {\"ref\": \"<git ref>\"}"+ .to_string()+ };+ match value {+ None | Some(serde_json::Value::Null) => Ok(None),+ Some(serde_json::Value::String(s)) => match s.trim() {+ "new" => Ok(Some(WorkspaceRequest::New)),+ "shared" => Ok(Some(WorkspaceRequest::Shared)),+ name if is_worker_name(name) => Ok(Some(WorkspaceRequest::Reuse(name.to_string()))),+ _ => Err(bad()),+ },+ Some(serde_json::Value::Object(map)) if map.len() == 1 => match map.get("ref") {+ Some(serde_json::Value::String(r))+ if crate::core::agent::git::is_plain_ref(r.trim()) =>+ {+ Ok(Some(WorkspaceRequest::Ref(r.trim().to_string())))+ }+ _ => Err(bad()),+ },+ Some(_) => Err(bad()),+ }+}++fn is_worker_name(name: &str) -> bool {+ !name.is_empty()+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+}++/// Whether a child with this final tool allowlist can change files. `None`+/// is the parent's whole toolset, which writes unless the parent denies both.+pub(crate) fn is_writer(+ allowed_tools: Option<&[String]>,+ permissions: &tauri_plugin_agent_tools::permissions::ToolPermissions,+) -> bool {+ ["write", "edit"].iter().any(|tool| {+ !permissions.is_denied(tool)+ && allowed_tools.is_none_or(|tools| tools.iter().any(|t| t == tool))+ })+}++/// A checkout the ledger created.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ChildWorktree {+ /// The checkout's top level.+ pub(crate) path: PathBuf,+ pub(crate) branch: String,+ /// The commit it was branched from.+ pub(crate) base: String,+ /// The `{"ref": ...}` it was made for, if any.+ pub(crate) from_ref: Option<String>,+ /// The main checkout's top level, which its branch is fetched back into.+ repo: PathBuf,+ /// The user's object directory it borrows, as recorded when it was made:+ /// its own alternates file is the child's to rewrite.+ objects: PathBuf,+}++/// Where one child works.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ChildWorkspace {+ /// The child's `project_root`.+ pub(crate) root: PathBuf,+ /// Whether the child may change `root` (a reader may not).+ pub(crate) read_only: bool,+ /// The worktree `root` is in, when it is not the parent's checkout.+ pub(crate) worktree: Option<ChildWorktree>,+ /// Why a worktree that was wanted could not be made.+ pub(crate) fallback: Option<String>,+ /// Whether the parent's checkout had uncommitted changes the new worktree+ /// does not carry.+ pub(crate) left_changes: bool,+ /// The parent's subdirectory of the repository when the worktree lacks+ /// it (untracked, ignored, or absent at the ref), so `root` is the+ /// worktree's top level instead.+ pub(crate) missing_subdir: Option<String>,+ /// Whether the `assign` that returned this made `worktree` for it, rather+ /// than handing out an earlier child's: only then may [`Ledger::undo`]+ /// remove it.+ fresh: bool,+}++impl ChildWorkspace {+ /// The parent's checkout, as is.+ fn shared(root: &Path, read_only: bool) -> Self {+ Self {+ root: root.to_path_buf(),+ read_only,+ worktree: None,+ fallback: None,+ left_changes: false,+ missing_subdir: None,+ fresh: false,+ }+ }++ /// The line the dispatch result carries for this child.+ pub(crate) fn note(&self) -> String {+ let fallback = self+ .fallback+ .as_deref()+ .map(|why| format!(" ({why}, so it uses your checkout)"))+ .unwrap_or_default();+ match (&self.worktree, self.read_only) {+ (Some(wt), read_only) => {+ let mode = if read_only { "read-only " } else { "" };+ let from = match &wt.from_ref {+ Some(r) => format!("{r} at {}", short(&wt.base)),+ None => short(&wt.base).to_string(),+ };+ let left = if self.left_changes {+ "; uncommitted changes in your checkout are not in it"+ } else {+ ""+ };+ let subdir = match &self.missing_subdir {+ Some(rel) => format!(+ "; your directory {rel} is not in this checkout, so it starts at the \+ top level"+ ),+ None => String::new(),+ };+ format!(+ "working in {mode}worktree {} (branch {}, from {from}){left}{subdir}",+ display(&self.root),+ wt.branch+ )+ }+ (None, true) => format!("working read-only in {}{fallback}", display(&self.root)),+ (None, false) => format!("working in your checkout {}{fallback}", display(&self.root)),+ }+ }++ /// The short form a `SubagentStart` event and the TUI show.+ pub(crate) fn label(&self) -> String {+ let mode = if self.read_only { "read-only " } else { "" };+ match &self.worktree {+ Some(wt) => format!("{mode}{} ({})", display(&self.root), wt.branch),+ None => format!("{mode}{}", display(&self.root)),+ }+ }++ /// Bring a writer's branch from its checkout into the user's repository,+ /// where the parent merges it. `Some(why)` when it could not be. Runs git.+ pub(crate) fn bring_back(&self) -> Option<String> {+ let wt = self.worktree.as_ref().filter(|_| !self.read_only)?;+ bring_back(wt).err()+ }++ /// The line appended to the child's answer, so the parent reading it later+ /// knows which branch to merge, or why that branch is not in the user's+ /// repository (`problem`, from [`Self::bring_back`]).+ pub(crate) fn answer_footer(&self, problem: Option<&str>) -> Option<String> {+ let wt = self.worktree.as_ref().filter(|_| !self.read_only)?;+ let path = display(&wt.path);+ Some(match problem {+ None => format!("[worked in {path} on branch {}]", wt.branch),+ Some(why) => format!(+ "[worked in {path} on branch {}, which is only there: it could not be brought \+ into your repository ({why})]",+ wt.branch+ ),+ })+ }+}++fn short(sha: &str) -> &str {+ &sha[..sha.len().min(9)]+}++fn display(path: &Path) -> String {+ let shown = match crate::core::agent::project::jan_home()+ .and_then(|home| home.parent().map(Path::to_path_buf))+ {+ Some(home) if !home.as_os_str().is_empty() => match path.strip_prefix(&home) {+ Ok(rest) => format!("~/{}", rest.display()),+ Err(_) => path.display().to_string(),+ },+ _ => path.display().to_string(),+ };+ shown.replace('\\', "/")+}++/// What a child's run is held to beyond its `project_root`: whether that root+/// is read-only, the extra directories its sandboxed shell may write, and the+/// environment its shell gets. `None` on a top-level run.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct ChildScope {+ pub(crate) read_only: bool,+ /// Directories its tools may read besides its workspace and write roots:+ /// the user's objects its checkout borrows.+ pub(crate) read_roots: Vec<PathBuf>,+ pub(crate) write_roots: Vec<PathBuf>,+ pub(crate) env_set: Vec<(String, String)>,+}++/// `~/.jan/worktrees/<slug>` for the repository `root` belongs to: its+/// subagents' worktrees and their shared build directory. Keyed on the main+/// checkout's top level, so a session running in a Jan worktree or in any+/// subdirectory finds the same one, and so the slug is the one `project_key`+/// checks a clone's alternates (which name that top level) against.+pub(crate) fn project_worktrees_dir(root: &Path) -> Option<PathBuf> {+ let key = tauri_plugin_agent_tools::workspace::project_key(root);+ let top = key.ancestors().find(|dir| dir.join(".git").exists()).unwrap_or(&key);+ Some(+ crate::core::agent::project::jan_home()?+ .join("worktrees")+ .join(tauri_plugin_agent_tools::workspace::path_slug(top)),+ )+}++/// The one `CARGO_TARGET_DIR` every child of the project builds into, so a+/// fresh worktree does not start with a cold Rust build.+const CARGO_TARGET: &str = "cargo-target";++/// The scope a child in `ws` runs under: the shared build directory for any+/// child outside the plain writable checkout, and package caches in the+/// session scratch for a reader. A writer is granted nothing of the user's+/// `.git`: its commits go to its own, inside its workspace. `scratch` is the+/// session scratch, when the session has one.+pub(crate) fn scope_for(+ ws: &ChildWorkspace,+ parent_root: &Path,+ scratch: Option<&Path>,+) -> ChildScope {+ let mut scope = ChildScope {+ read_only: ws.read_only,+ ..ChildScope::default()+ };+ if let Some(scratch) = scratch.filter(|_| ws.read_only) {+ let shown = tauri_plugin_agent_tools::tools::sandbox::scratch_display_path(+ Some(scratch),+ scratch,+ );+ scope.env_set.extend(reader_env(&shown));+ }+ if ws.worktree.is_some() || ws.read_only {+ if let Some(target) = project_worktrees_dir(parent_root).map(|d| d.join(CARGO_TARGET)) {+ if std::fs::create_dir_all(&target).is_ok() {+ scope.env_set.push((+ "CARGO_TARGET_DIR".to_string(),+ target.to_string_lossy().into_owned(),+ ));+ scope.write_roots.push(target);+ }+ }+ }+ if let Some(wt) = &ws.worktree {+ scope.read_roots.push(wt.objects.clone());+ }+ scope+}++/// What a child's args take from its workspace beyond `project_root`, read+/// from git by [`place`] when the child is dispatched.+#[derive(Debug, Clone)]+pub(crate) struct Placement {+ /// The child's own Session Start, when it is not in the parent's checkout.+ session_start: Option<crate::core::agent::context::SessionStart>,+ scope: ChildScope,+}++/// Resolve the [`Placement`] of a child in `ws`: its checkout's branch and the+/// scope its tools enforce. Runs git, so the dispatch calls it on+/// the blocking pool and [`apply`], on the async child task, runs none.+pub(crate) fn place(ws: &ChildWorkspace, parent_root: &Path, scratch: Option<&Path>) -> Placement {+ Placement {+ session_start: ws.worktree.as_ref().map(|wt| {+ crate::core::agent::context::SessionStart::with_branch(worktree_branch(wt))+ }),+ scope: scope_for(ws, parent_root, scratch),+ }+}++/// Point a child's run at its workspace: `project_root` (and so its prompt's+/// Working Directory and Runtime Environment blocks), its own Session Start+/// when it is not in the parent's checkout, and the scope its tools enforce.+pub(crate) fn apply(+ args: &mut crate::core::agent::r#loop::OrchestrationArgs,+ ws: &ChildWorkspace,+ placement: Placement,+) {+ if let Some(start) = placement.session_start {+ args.session_start = Some(start);+ }+ args.project_root = Some(ws.root.clone());+ args.child_scope = Some(placement.scope);+}++/// Package-manager caches a read-only child keeps in its scratch, since it+/// cannot write them into the project. `scratch_shell` is the scratch as the+/// shell names it.+fn reader_env(scratch_shell: &str) -> Vec<(String, String)> {+ let scratch = scratch_shell.trim_end_matches('/');+ vec![+ ("YARN_CACHE_FOLDER".to_string(), format!("{scratch}/yarn-cache")),+ ("COREPACK_HOME".to_string(), format!("{scratch}/corepack")),+ ]+}++/// The directory the parent's sandboxed tools may read its children's+/// worktrees through, created so the sandbox has something to bind. `None`+/// outside the CLI build or when there is no Jan home.+pub(crate) fn parent_read_root(root: &Path) -> Option<PathBuf> {+ if !cfg!(feature = "cli") {+ return None;+ }+ let dir = project_worktrees_dir(root)?;+ std::fs::create_dir_all(&dir).ok()?;+ dunce::canonicalize(&dir).ok()+}++/// Whether a reader's checkout is read-only. CLI-only: the desktop's Windows+/// sandbox (AppContainer) has no read-only workspace, so enforcing one there+/// would take the shell away from every reader child instead.+const READ_ONLY_READERS: bool = cfg!(feature = "cli");++#[derive(Debug, Default)]+struct LedgerState {+ /// Every child's workspace, by worker name, for `workspace: "<name>"`.+ by_name: HashMap<String, ChildWorkspace>,+ /// Worktrees with a writer in them right now.+ busy: HashSet<PathBuf>,+ /// Worktrees a sweep or undo is checking for removal right now, which no+ /// dispatch may be given: they may be gone before its child starts.+ removing: HashSet<PathBuf>,+ /// Worktrees this session created, in creation order.+ created: Vec<ChildWorktree>,+}++/// The session's record of its children's workspaces.+#[derive(Debug, Default)]+pub(crate) struct Ledger {+ state: Mutex<LedgerState>,+}++/// A writer's hold on its worktree, released when the child is done (it+/// finished, failed, was stopped or was torn down), before the child counts+/// as finished.+#[derive(Debug)]+pub(crate) struct WriterLease {+ ledger: Arc<Ledger>,+ path: PathBuf,+}++impl Drop for WriterLease {+ fn drop(&mut self) {+ self.ledger.state.lock().unwrap().busy.remove(&self.path);+ }+}++impl Ledger {+ /// Assign `name` its workspace and record it. A writer in a worktree gets+ /// the lease that keeps a second writer out until it is done: a second+ /// writer naming a busy worktree is refused, not queued.+ pub(crate) fn assign(+ self: &Arc<Self>,+ parent_root: &Path,+ name: &str,+ writer: bool,+ request: Option<&WorkspaceRequest>,+ ) -> Result<(ChildWorkspace, Option<WriterLease>), String> {+ let read_only = !writer && READ_ONLY_READERS;+ let ws = match request {+ Some(WorkspaceRequest::Shared) => ChildWorkspace::shared(parent_root, read_only),+ Some(WorkspaceRequest::Reuse(earlier)) => {+ let found = self.state.lock().unwrap().by_name.get(earlier).cloned();+ let mut ws = found.ok_or_else(|| {+ format!(+ "workspace '{earlier}' names no earlier subagent of this session; use \+ \"new\", \"shared\", or the name of a subagent that has already been \+ dispatched"+ )+ })?;+ ws.read_only = read_only;+ ws.left_changes = false;+ ws.fresh = false;+ ws+ }+ Some(WorkspaceRequest::New) => create(parent_root, name, None, read_only)?,+ Some(WorkspaceRequest::Ref(r)) => create(parent_root, name, Some(r), read_only)?,+ None if writer => create(parent_root, name, None, read_only)?,+ None => ChildWorkspace::shared(parent_root, read_only),+ };+ let mut state = self.state.lock().unwrap();+ // A reuse was looked up under an earlier hold of the lock: a sweep may+ // have removed that worktree since (dropping it from `created`). Only+ // a worktree the ledger still records, and that is still on disk, is+ // handed out; never a path git has already deleted.+ if let (Some(WorkspaceRequest::Reuse(earlier)), Some(wt)) = (request, ws.worktree.as_ref()) {+ let recorded = state.created.iter().any(|c| c.path == wt.path);+ if !recorded || !wt.path.is_dir() {+ return Err(format!(+ "refused: the worktree of '{earlier}' ({}) was removed, as it held no \+ work. This subagent was not started. Give it workspace \"new\" instead",+ display(&wt.path)+ ));+ }+ }+ if let Some(wt) = ws.worktree.as_ref().filter(|wt| state.removing.contains(&wt.path)) {+ return Err(format!(+ "refused: {} (branch {}) is being removed, as it held no work. This \+ subagent was not started. Give it workspace \"new\" instead",+ display(&wt.path),+ wt.branch+ ));+ }+ let lease = match ws.worktree.as_ref().filter(|_| writer) {+ Some(wt) => {+ if !state.busy.insert(wt.path.clone()) {+ return Err(format!(+ "refused: another subagent is still writing in {} (branch {}), and \+ only one writer may work in a worktree at a time. This subagent was \+ not started. Dispatch it again once that one has finished, or give \+ it workspace \"new\"",+ display(&wt.path),+ wt.branch+ ));+ }+ Some(WriterLease {+ ledger: self.clone(),+ path: wt.path.clone(),+ })+ }+ None => None,+ };+ if let Some(wt) = &ws.worktree {+ if !state.created.iter().any(|c| c.path == wt.path) {+ state.created.push(wt.clone());+ }+ }+ state.by_name.insert(name.to_string(), ws.clone());+ Ok((ws, lease))+ }++ /// Take back the assignment `ws` that `name`'s dispatch got and never+ /// used (the run was torn down before the child could start): forget the+ /// name, and remove the worktree only when that `assign` made it and it+ /// holds nothing. Everything else the session made stays, since a later+ /// dispatch may still name it. Call after the dispatch's lease is gone.+ pub(crate) fn undo(&self, name: &str, ws: &ChildWorkspace) {+ self.state.lock().unwrap().by_name.remove(name);+ if let Some(wt) = ws.worktree.as_ref().filter(|_| ws.fresh) {+ self.remove_unless_busy(wt);+ }+ }++ /// Mark `path` as being removed, unless a writer is in it or it already+ /// is. While marked, `assign` hands it to nobody, so the git that decides+ /// and does the removal runs without the ledger's lock: a lease dropping+ /// meanwhile never waits on it.+ fn claim(&self, path: &Path) -> bool {+ let mut state = self.state.lock().unwrap();+ !state.busy.contains(path) && state.removing.insert(path.to_path_buf())+ }++ /// Remove `wt` when no writer is in it and it holds nothing, forgetting it+ /// and every name that pointed at it. Returns whether it went.+ fn remove_unless_busy(&self, wt: &ChildWorktree) -> bool {+ if !self.claim(&wt.path) {+ return false;+ }+ let gone = remove_if_empty(wt);+ let mut state = self.state.lock().unwrap();+ state.removing.remove(&wt.path);+ if gone {+ state.created.retain(|c| c.path != wt.path);+ state+ .by_name+ .retain(|_, ws| ws.worktree.as_ref().is_none_or(|w| w.path != wt.path));+ }+ gone+ }+}++/// Remove the checkout `wt` when it holds nothing: no commit past its base on+/// any ref and no uncommitted change. One git cannot read counts as holding+/// work, since removal deletes it. Returns whether it went.+#[cfg(feature = "cli")]+fn remove_if_empty(wt: &ChildWorktree) -> bool {+ // A checkout that is no longer what Jan made is never removed: what it+ // holds cannot be read without trusting it.+ let Ok(checkout) = checkout(wt) else { return false };+ checkout.commits_anywhere(&wt.base) == Some(0)+ && checkout.try_changed_paths().is_ok_and(|c| c.is_empty())+ && std::fs::remove_dir_all(&wt.path).is_ok()+}++/// How long bringing a branch into the user's repository may take.+#[cfg(feature = "cli")]+const BRING_BACK_LIMIT: std::time::Duration = std::time::Duration::from_secs(60);++/// Fetch `wt`'s branch into the user's repository when it holds commits, so+/// the parent can merge it. Nothing is created for a branch with none.+#[cfg(feature = "cli")]+fn bring_back(wt: &ChildWorktree) -> Result<(), String> {+ let checkout = checkout(wt)?;+ match checkout.commits_on(&wt.base, &format!("refs/heads/{}", wt.branch)) {+ Some(0) => Ok(()),+ Some(_) => checkout.fetch_branch(&wt.repo, &wt.branch, BRING_BACK_LIMIT),+ None => Err(format!("git could not read its branch {}", wt.branch)),+ }+}++/// The desktop makes no checkouts, so there is never a branch to bring back.+#[cfg(not(feature = "cli"))]+fn bring_back(_wt: &ChildWorktree) -> Result<(), String> {+ Ok(())+}++/// The branch checked out in `wt`, read without trusting its `.git`.+#[cfg(feature = "cli")]+fn worktree_branch(wt: &ChildWorktree) -> Option<String> {+ checkout(wt).ok()?.current_branch()+}++/// The desktop makes no worktrees.+#[cfg(not(feature = "cli"))]+fn worktree_branch(_wt: &ChildWorktree) -> Option<String> {+ None+}++/// `wt` as Jan's git must be run in it: opened only while it is still the+/// repository Jan made. Every git call Jan makes in a child's checkout goes+/// through here, unsandboxed, so it never honors what the child rewrote. The+/// error says why not, for the user.+#[cfg(feature = "cli")]+fn checkout(wt: &ChildWorktree) -> Result<crate::core::agent::git::Checkout, String> {+ crate::core::agent::git::Checkout::open(&wt.path, &wt.objects)+}++/// The desktop makes no worktrees, so there is never one to remove.+#[cfg(not(feature = "cli"))]+fn remove_if_empty(_wt: &ChildWorktree) -> bool {+ false+}++/// How long a `{"ref": ...}` dispatch waits on `origin` before failing, so+/// an unreachable or hung remote cannot hold the dispatch forever.+#[cfg(feature = "cli")]+const REF_FETCH_LIMIT: std::time::Duration = std::time::Duration::from_secs(60);++/// A fresh checkout for `name`, or the parent's checkout when the project+/// cannot have one (the reason is kept for the dispatch note).+#[cfg(feature = "cli")]+fn create(+ parent_root: &Path,+ name: &str,+ git_ref: Option<&str>,+ read_only: bool,+) -> Result<ChildWorkspace, String> {+ use crate::core::agent::git;+ let fallback = |why: &str| ChildWorkspace {+ fallback: Some(why.to_string()),+ ..ChildWorkspace::shared(parent_root, read_only)+ };+ let Some(repo) = git::repo_root(parent_root) else {+ if git_ref.is_some() {+ return Err("workspace {\"ref\": ...} needs a git repository".to_string());+ }+ return Ok(fallback("not a git repository"));+ };+ let base = match git_ref {+ Some(r) => match git::resolve_commit(&repo, r) {+ Some(sha) => sha,+ None => git::fetch_commit(&repo, r, REF_FETCH_LIMIT)+ .map_err(|e| format!("could not find or fetch ref '{r}': {e}"))?,+ },+ None => match git::head_sha(&repo) {+ Some(sha) => sha,+ None => return Ok(fallback("the repository has no commits yet")),+ },+ };+ let dir = project_worktrees_dir(parent_root)+ .ok_or_else(|| "could not resolve the Jan home for worktrees".to_string())?;+ let mut last = String::new();+ for _ in 0..4 {+ let hex: String = uuid::Uuid::new_v4().simple().to_string()[..4].to_string();+ let id = format!("{name}-{hex}");+ let path = dir.join(&id);+ if path.exists() {+ continue;+ }+ let branch = format!("jan/agent/{id}");+ match git::clone_shared(&repo, &path, &branch, &base) {+ Ok(objects) => {+ // dunce, not std: Windows' `\\?\` form is what git refuses as a+ // clone URL, and every later git call is handed this path.+ let path = dunce::canonicalize(&path).unwrap_or(path);+ // A subdirectory of the checkout maps to the same one in the+ // worktree, so relative paths mean what they did.+ let rel = dunce::canonicalize(parent_root)+ .ok()+ .and_then(|r| {+ let top = dunce::canonicalize(&repo).ok()?;+ r.strip_prefix(top).ok().map(Path::to_path_buf)+ })+ .unwrap_or_default();+ // It may not exist there: untracked or ignored in the parent's+ // checkout, or absent at the ref. A child must never be given a+ // root that is not a directory, so it starts at the top level.+ let sub = Some(&rel)+ .filter(|rel| !rel.as_os_str().is_empty())+ .map(|rel| path.join(rel));+ let missing = sub.as_ref().is_some_and(|sub| !sub.is_dir());+ let root = sub.filter(|_| !missing).unwrap_or_else(|| path.clone());+ return Ok(ChildWorkspace {+ root,+ read_only,+ left_changes: git_ref.is_none() && !git::changed_paths(&repo).is_empty(),+ missing_subdir: missing+ .then(|| rel.to_string_lossy().replace('\\', "/")),+ worktree: Some(ChildWorktree {+ path,+ branch,+ base,+ from_ref: git_ref.map(str::to_string),+ repo: repo.clone(),+ objects,+ }),+ fallback: None,+ fresh: true,+ });+ }+ Err(e) => last = e,+ }+ }+ Err(format!("could not create a checkout: {last}"))+}++/// The desktop has no subagent worktrees: a child keeps its parent's+/// workspace, as before.+#[cfg(not(feature = "cli"))]+fn create(+ parent_root: &Path,+ _name: &str,+ _git_ref: Option<&str>,+ read_only: bool,+) -> Result<ChildWorkspace, String> {+ Ok(ChildWorkspace {+ fallback: Some("subagent worktrees are CLI-only".to_string()),+ ..ChildWorkspace::shared(parent_root, read_only)+ })+}++#[cfg(feature = "cli")]+impl Ledger {+ /// Whether a writer is in `path` right now.+ fn is_busy(&self, path: &Path) -> bool {+ self.state.lock().unwrap().busy.contains(path)+ }++ /// End of session: remove every checkout that holds nothing (no commit+ /// past its base, no uncommitted change), `ref` ones included, and return+ /// a line for each one kept, after bringing its branch into the user's+ /// repository. A checkout a writer is still in is kept, and so is one git+ /// cannot read: removal deletes it, so "unknown" must never count as+ /// "clean".+ ///+ /// The ledger's lock is held only to snapshot and to record each removal,+ /// never across git, so leases and dispatches carry on meanwhile.+ pub(crate) fn finish_session(&self) -> Vec<String> {+ let created = {+ let mut state = self.state.lock().unwrap();+ state.by_name.clear();+ state.created.clone()+ };+ let mut kept = Vec::new();+ for wt in created {+ if !wt.path.is_dir() {+ self.state.lock().unwrap().created.retain(|c| c.path != wt.path);+ continue;+ }+ if !self.remove_unless_busy(&wt) {+ // Whatever the child committed before it was stopped, so the+ // user has the branch to merge; not while a writer is in it.+ let brought = (!self.is_busy(&wt.path)).then(|| bring_back(&wt).err()).flatten();+ kept.push(kept_line(&wt, brought.as_deref()));+ }+ }+ kept+ }++ /// The session's subagent worktrees still on disk, for `/worktree`. Runs+ /// git per worktree, outside the ledger's lock.+ pub(crate) fn live(&self) -> Vec<String> {+ let created = self.state.lock().unwrap().created.clone();+ created+ .iter()+ .filter(|wt| wt.path.is_dir())+ .map(|wt| kept_line(wt, None))+ .collect()+ }+}++/// The session-end note naming the subagent worktrees left to merge.+#[cfg(feature = "cli")]+pub(crate) fn kept_notice(kept: &[String]) -> String {+ format!(+ "subagent worktrees kept (they hold work): {}",+ kept.join("; ")+ )+}++#[cfg(feature = "cli")]+fn kept_line(wt: &ChildWorktree, not_brought: Option<&str>) -> String {+ let held = match checkout(wt) {+ Err(why) => format!(+ "not read and not removed: {why}. Do not run git in it; inspect its .git, or \+ delete the directory"+ ),+ Ok(checkout) => {+ let mut held = match (checkout.commits_anywhere(&wt.base), checkout.try_changed_paths())+ {+ (Some(commits), Ok(changed)) => {+ format!("{commits} commit(s), {} uncommitted file(s)", changed.len())+ }+ _ => "status unknown: git could not read it".to_string(),+ };+ if let Some(why) = not_brought {+ held.push_str(&format!("; its branch is not in your repository: {why}"));+ }+ held+ }+ };+ format!("{} on {} ({held})", display(&wt.path), wt.branch)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn the_workspace_field_parses_every_documented_shape() {+ assert_eq!(parse_request(None), Ok(None));+ assert_eq!(parse_request(Some(&json!(null))), Ok(None));+ assert_eq!(parse_request(Some(&json!("new"))), Ok(Some(WorkspaceRequest::New)));+ assert_eq!(parse_request(Some(&json!("shared"))), Ok(Some(WorkspaceRequest::Shared)));+ assert_eq!(+ parse_request(Some(&json!("general-2"))),+ Ok(Some(WorkspaceRequest::Reuse("general-2".to_string())))+ );+ assert_eq!(+ parse_request(Some(&json!({"ref": "pull/9486/head"}))),+ Ok(Some(WorkspaceRequest::Ref("pull/9486/head".to_string())))+ );+ for bad in [+ json!(""),+ json!("../x"),+ json!(3),+ json!({"ref": "--upload-pack=x"}),+ json!({"ref": "+refs/heads/x:refs/heads/main"}),+ json!({"ref": "x:main"}),+ json!({"ref": "+x"}),+ json!({"ref": "a\u{1}b"}),+ json!({"ref": ""}),+ json!({"ref": "a", "extra": 1}),+ json!({"branch": "a"}),+ ] {+ assert!(parse_request(Some(&bad)).is_err(), "{bad}");+ }+ }++ /// The desktop has no read-only children: a reader there works in its+ /// parent's checkout with nothing added to its tools, exactly as before+ /// subagent workspaces (AppContainer has no read-only workspace, so+ /// enforcing one would take the shell away from every reader on Windows).+ #[cfg(not(feature = "cli"))]+ #[test]+ fn a_desktop_reader_child_is_held_to_nothing_new() {+ let root = std::env::temp_dir().join(format!("jan_child_ws_desk_{}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "explore", false, None).unwrap();+ assert!(lease.is_none());+ assert!(!ws.read_only, "{ws:?}");+ assert_eq!(scope_for(&ws, &root, Some(&root)), ChildScope::default());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_writer_is_a_child_that_can_write_or_edit() {+ use tauri_plugin_agent_tools::permissions::ToolPermissions;+ let all = ToolPermissions::allow_all();+ let names = |t: &[&str]| t.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ assert!(is_writer(None, &all));+ assert!(is_writer(Some(&names(&["read", "edit"])), &all));+ assert!(!is_writer(Some(&names(&["read", "ls", "shell"])), &all));+ let denied = ToolPermissions::new(+ tauri_plugin_agent_tools::permissions::PermissionDefault::Allow,+ &[],+ &names(&["write", "edit"]),+ &[],+ );+ assert!(!is_writer(None, &denied));+ }+}++#[cfg(all(test, feature = "cli"))]+mod git_tests {+ use super::*;+ use std::process::Command;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static N: AtomicUsize = AtomicUsize::new(0);++ fn git(dir: &Path, args: &[&str]) -> bool {+ Command::new("git")+ .arg("-C")+ .arg(dir)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }++ /// A repository with one commit, or `None` without git.+ fn repo(tag: &str) -> Option<PathBuf> {+ let dir = std::env::temp_dir().join(format!(+ "jan_child_ws_{tag}_{}_{}",+ std::process::id(),+ N.fetch_add(1, Ordering::SeqCst)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).ok()?;+ if !git(&dir, &["init", "-q", "-b", "main"]) {+ return None;+ }+ std::fs::write(dir.join("a.txt"), "a\n").ok()?;+ git(&dir, &["add", "a.txt"]);+ // Not `std::fs::canonicalize`: on Windows its `\\?\` form reaches git+ // as a clone URL ("hostname contains invalid characters").+ git(&dir, &["commit", "-q", "--no-gpg-sign", "-m", "a"])+ .then(|| dunce::canonicalize(&dir).ok())?+ }++ fn commit(dir: &Path, file: &str) {+ std::fs::write(dir.join(file), "x\n").unwrap();+ assert!(git(dir, &["add", file]));+ assert!(git(dir, &["commit", "-q", "--no-gpg-sign", "-m", file]));+ }++ #[test]+ fn a_writer_gets_its_own_worktree_and_a_reader_the_checkout_read_only() {+ let Some(root) = repo("default") else { return };+ let ledger = Arc::new(Ledger::default());+ let (writer, lease) = ledger.assign(&root, "general", true, None).unwrap();+ let wt = writer.worktree.clone().expect("a writer gets a worktree");+ assert!(lease.is_some());+ assert!(!writer.read_only);+ assert_eq!(writer.root, wt.path);+ assert!(wt.branch.starts_with("jan/agent/general-"), "{}", wt.branch);+ assert!(wt.path.starts_with(dunce::canonicalize(project_worktrees_dir(&root).unwrap()).unwrap()));+ assert_eq!(+ crate::core::agent::git::current_branch(&wt.path).as_deref(),+ Some(wt.branch.as_str())+ );+ let note = writer.note();+ assert!(note.contains(&wt.branch) && note.contains("worktree"), "{note}");+ assert_eq!(writer.answer_footer(None).map(|f| f.contains(&wt.branch)), Some(true));++ let (reader, lease) = ledger.assign(&root, "explore", false, None).unwrap();+ assert!(lease.is_none());+ assert_eq!(reader, ChildWorkspace::shared(&root, true));+ assert!(reader.note().starts_with("working read-only in "), "{}", reader.note());+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn two_concurrent_writers_never_share_and_reuse_of_a_busy_worktree_is_refused() {+ let Some(root) = repo("lease") else { return };+ let ledger = Arc::new(Ledger::default());+ let (a, lease_a) = ledger.assign(&root, "general", true, None).unwrap();+ let (b, _lease_b) = ledger.assign(&root, "general-2", true, None).unwrap();+ assert_ne!(a.root, b.root, "two writers, two checkouts");++ let reuse = WorkspaceRequest::Reuse("general".to_string());+ let err = ledger.assign(&root, "general-3", true, Some(&reuse)).unwrap_err();+ assert!(err.contains("still writing") && err.contains("not started"), "{err}");+ // A reader may look at it meanwhile, read-only.+ let (look, _) = ledger.assign(&root, "review", false, Some(&reuse)).unwrap();+ assert_eq!(look.root, a.root);+ assert!(look.read_only);++ drop(lease_a);+ let (again, lease) = ledger.assign(&root, "general-3", true, Some(&reuse)).unwrap();+ assert_eq!(again.root, a.root, "sequential reuse gets the same checkout");+ assert!(!again.read_only && lease.is_some());+ drop(lease);+ assert!(ledger+ .assign(&root, "x", true, Some(&WorkspaceRequest::Reuse("nobody".into())))+ .unwrap_err()+ .contains("no earlier subagent"));+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_ref_worktree_is_checked_out_at_the_ref_fetching_it_when_needed() {+ let Some(upstream) = repo("upstream") else { return };+ assert!(git(&upstream, &["checkout", "-q", "-b", "feature"]));+ commit(&upstream, "feature.txt");+ let feature = crate::core::agent::git::head_sha(&upstream).unwrap();+ assert!(git(&upstream, &["checkout", "-q", "main"]));++ let clone = upstream.with_extension("clone");+ let _ = std::fs::remove_dir_all(&clone);+ assert!(git(+ upstream.parent().unwrap(),+ &["clone", "-q", "--single-branch", "-b", "main", &upstream.to_string_lossy(), &clone.to_string_lossy()]+ ));+ let clone = dunce::canonicalize(&clone).unwrap();+ assert_eq!(crate::core::agent::git::resolve_commit(&clone, "feature"), None);++ let ledger = Arc::new(Ledger::default());+ let req = WorkspaceRequest::Ref("feature".to_string());+ let (ws, lease) = ledger.assign(&clone, "review", false, Some(&req)).unwrap();+ let wt = ws.worktree.clone().expect("a ref gets a worktree");+ assert!(ws.read_only && lease.is_none(), "a reader there is still read-only");+ assert_eq!(wt.base, feature);+ assert!(ws.root.join("feature.txt").is_file());+ assert!(ws.note().contains("feature at"), "{}", ws.note());++ assert!(ledger.finish_session().is_empty(), "an untouched ref worktree goes");+ assert!(!wt.path.exists());+ let _ = std::fs::remove_dir_all(&clone);+ let _ = std::fs::remove_dir_all(&upstream);+ }++ /// A writer working in a `ref` worktree commits on its `jan/agent/...`+ /// branch; session end must not delete that branch and lose the commits,+ /// nor drop uncommitted edits made there.+ #[test]+ fn a_ref_worktree_that_holds_work_is_kept_at_session_end() {+ let Some(root) = repo("refwork") else { return };+ assert!(git(&root, &["branch", "feature"]));+ let ledger = Arc::new(Ledger::default());+ let req = WorkspaceRequest::Ref("feature".to_string());+ let (committed, l1) = ledger.assign(&root, "general", true, Some(&req)).unwrap();+ let (dirty, l2) = ledger.assign(&root, "general-2", true, Some(&req)).unwrap();+ let (idle, l3) = ledger.assign(&root, "general-3", true, Some(&req)).unwrap();+ drop((l1, l2, l3));+ commit(&committed.root, "b.txt");+ let tip = crate::core::agent::git::head_sha(&committed.root).unwrap();+ std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();++ let kept = ledger.finish_session();+ assert_eq!(kept.len(), 2, "{kept:?}");+ assert!(committed.root.is_dir() && dirty.root.is_dir());+ assert!(!idle.root.exists(), "an untouched ref worktree still goes");+ let branch = &committed.worktree.as_ref().unwrap().branch;+ assert_eq!(+ crate::core::agent::git::resolve_commit(&root, branch).as_deref(),+ Some(tip.as_str()),+ "the writer's commit is still on its branch"+ );+ let _ = std::fs::remove_dir_all(&committed.root);+ let _ = std::fs::remove_dir_all(&dirty.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// `git status` failing says nothing about whether the checkout is clean,+ /// so the worktree is kept and the kept line says why.+ #[test]+ fn a_worktree_whose_status_cannot_be_read_is_kept() {+ let Some(root) = repo("badstatus") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ std::fs::write(ws.root.join("a.txt"), "edited\n").unwrap();+ let out = Command::new("git")+ .arg("-C")+ .arg(&ws.root)+ .args(["rev-parse", "--git-path", "index"])+ .output()+ .unwrap();+ let index = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());+ let index = if index.is_absolute() { index } else { ws.root.join(index) };+ std::fs::write(&index, "not an index").unwrap();++ let kept = ledger.finish_session();+ assert!(ws.root.join("a.txt").is_file(), "the edit survives");+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(kept[0].contains("status unknown"), "{kept:?}");+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn session_end_removes_only_clean_commitless_worktrees() {+ let Some(root) = repo("cleanup") else { return };+ let ledger = Arc::new(Ledger::default());+ let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();+ let (committed, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (dirty, l3) = ledger.assign(&root, "general-3", true, None).unwrap();+ drop((l1, l2, l3));+ commit(&committed.root, "b.txt");+ std::fs::write(dirty.root.join("a.txt"), "edited\n").unwrap();++ let kept = ledger.finish_session();+ assert_eq!(kept.len(), 2, "{kept:?}");+ assert!(!idle.root.exists());+ let idle_branch = &idle.worktree.as_ref().unwrap().branch;+ assert_eq!(crate::core::agent::git::resolve_commit(&root, idle_branch), None);+ assert!(committed.root.is_dir() && dirty.root.is_dir());+ assert!(kept.iter().any(|k| k.contains("1 commit(s)")), "{kept:?}");+ assert_eq!(ledger.live().len(), 2);+ let _ = std::fs::remove_dir_all(&committed.root);+ let _ = std::fs::remove_dir_all(&dirty.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A user who hides untracked files from `git status` must not lose a+ /// writer's new, never-added files: they are its deliverables.+ #[test]+ fn an_untracked_only_worktree_is_kept_when_status_hides_untracked_files() {+ let Some(root) = repo("untracked") else { return };+ assert!(git(&root, &["config", "status.showUntrackedFiles", "no"]));+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ std::fs::create_dir_all(ws.root.join("out")).unwrap();+ std::fs::write(ws.root.join("out/report.md"), "deliverable\n").unwrap();++ let kept = ledger.finish_session();+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(ws.root.join("out/report.md").is_file());+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A writer that committed on its branch and then moved HEAD away (back to+ /// the base, detached) still holds that work on the branch: the sweep+ /// must not force-delete it.+ #[test]+ fn a_branch_holding_commits_is_kept_even_when_head_moved_away() {+ let Some(root) = repo("head-moved") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.as_ref().unwrap();+ commit(&ws.root, "b.txt");+ assert!(git(&ws.root, &["switch", "-q", "--detach", &wt.base]));++ let kept = ledger.finish_session();+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(kept[0].contains("1 commit(s)"), "{kept:?}");+ assert!(ws.root.is_dir());+ assert!(crate::core::agent::git::resolve_commit(&root, &wt.branch).is_some());+ let _ = std::fs::remove_dir_all(&ws.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Undoing a dispatch the run never started takes back only what that+ /// dispatch got: its name, and the worktree its own `assign` made. An+ /// earlier reader's fresh worktree (which holds no lease) and an earlier+ /// writer's stay, and so do their names, for a later `workspace` to reuse.+ #[test]+ fn undo_removes_only_the_worktree_that_assignment_made() {+ let Some(root) = repo("undo") else { return };+ let ledger = Arc::new(Ledger::default());+ let new = WorkspaceRequest::New;+ let (reader, _) = ledger.assign(&root, "explore", false, Some(&new)).unwrap();+ let (writer, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);++ let (late, lease) = ledger.assign(&root, "late", true, None).unwrap();+ drop(lease);+ ledger.undo("late", &late);+ let late_wt = late.worktree.as_ref().unwrap();+ assert!(!late_wt.path.exists(), "the undone dispatch's worktree is removed");+ assert_eq!(crate::core::agent::git::resolve_commit(&root, &late_wt.branch), None);+ assert!(reader.root.is_dir() && writer.root.is_dir());+ assert_eq!(ledger.live().len(), 2, "{:?}", ledger.live());++ // An undone reuse hands nothing back: the worktree was not its own.+ let reuse = WorkspaceRequest::Reuse("general".to_string());+ let (borrowed, lease) = ledger.assign(&root, "late-2", true, Some(&reuse)).unwrap();+ drop(lease);+ ledger.undo("late-2", &borrowed);+ assert!(writer.root.is_dir(), "an earlier child's worktree survives");++ for earlier in ["explore", "general"] {+ let reuse = WorkspaceRequest::Reuse(earlier.to_string());+ assert!(ledger.assign(&root, "next", false, Some(&reuse)).is_ok(), "{earlier}");+ }+ for gone in ["late", "late-2"] {+ let reuse = WorkspaceRequest::Reuse(gone.to_string());+ assert!(ledger.assign(&root, "next", false, Some(&reuse)).is_err(), "{gone}");+ }+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Make `git status` in the checkout at `path` block for two seconds, so a+ /// sweep is slow without any test seam: `info/exclude`, which status reads,+ /// is a FIFO nobody opens until then. `false` where there is no `mkfifo`.+ #[cfg(unix)]+ fn slow_status(path: &Path) -> bool {+ let exclude = path.join(".git/info/exclude");+ let _ = std::fs::remove_file(&exclude);+ if !Command::new("mkfifo").arg(&exclude).status().is_ok_and(|s| s.success()) {+ return false;+ }+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_secs(2));+ // Opening it for writing is what lets status's read through; a+ // plain empty file after that serves any later read.+ let held = std::fs::OpenOptions::new().write(true).open(&exclude);+ let _ = std::fs::remove_file(&exclude);+ let _ = std::fs::write(&exclude, "");+ drop(held);+ });+ true+ }++ /// The sweep runs git per checkout; a writer finishing meanwhile (its+ /// lease dropping, from an async task) must not wait for that git.+ #[cfg(unix)]+ #[test]+ fn a_lease_drop_does_not_wait_on_a_slow_sweep() {+ use std::time::{Duration, Instant};+ let Some(root) = repo("slow") else { return };+ let ledger = Arc::new(Ledger::default());+ let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();+ let (busy, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ drop(l1);+ commit(&busy.root, "b.txt");+ if !slow_status(&idle.root) {+ return;+ }+ let sweep = {+ let ledger = ledger.clone();+ std::thread::spawn(move || ledger.finish_session())+ };+ std::thread::sleep(Duration::from_millis(500));+ let started = Instant::now();+ drop(l2);+ let waited = started.elapsed();+ let kept = sweep.join().unwrap();+ assert!(waited < Duration::from_secs(1), "the lease drop waited {waited:?}");+ assert!(!idle.root.exists(), "the idle worktree still goes");+ assert_eq!(kept.len(), 1, "the one holding a commit is kept: {kept:?}");+ let _ = std::fs::remove_dir_all(&busy.root);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A worktree the sweep has claimed for removal is not handed to a later+ /// dispatch, writer or reader: it may be gone by the time the child starts.+ #[test]+ fn a_worktree_being_removed_is_not_reused() {+ let Some(root) = repo("removing") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let path = ws.worktree.as_ref().unwrap().path.clone();+ assert!(ledger.claim(&path));+ assert!(!ledger.claim(&path), "one removal at a time");+ let reuse = WorkspaceRequest::Reuse("general".to_string());+ for writer in [true, false] {+ let err = ledger.assign(&root, "next", writer, Some(&reuse)).unwrap_err();+ assert!(err.contains("being removed"), "{err}");+ }+ ledger.state.lock().unwrap().removing.remove(&path);+ let (again, lease) = ledger.assign(&root, "next", true, Some(&reuse)).unwrap();+ assert_eq!(again.root, ws.root);+ assert!(!ledger.claim(&path), "a busy worktree is never claimed");+ drop(lease);+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A reuse looked up just before a sweep removed that worktree (the name+ /// still maps to it, but git deleted it and the ledger dropped it) is+ /// refused, never re-recorded or handed out as a missing directory.+ #[test]+ fn a_reuse_of_a_worktree_swept_meanwhile_is_refused() {+ let Some(root) = repo("swept") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.clone().unwrap();+ // The sweep's effect, landing between the lookup and the record.+ assert!(remove_if_empty(&wt));+ ledger.state.lock().unwrap().created.retain(|c| c.path != wt.path);++ let reuse = WorkspaceRequest::Reuse("general".to_string());+ for writer in [true, false] {+ let err = ledger.assign(&root, "next", writer, Some(&reuse)).unwrap_err();+ assert!(err.contains("was removed"), "{err}");+ }+ assert!(ledger.live().is_empty(), "{:?}", ledger.live());+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A session in a subdirectory the new checkout lacks (untracked there, or+ /// absent at the ref) starts its child at the worktree's top level and says+ /// so, rather than handing it a `project_root` that does not exist.+ #[test]+ fn a_subdirectory_missing_from_the_worktree_falls_back_to_its_top_level() {+ let Some(root) = repo("subdir") else { return };+ assert!(git(&root, &["branch", "old"]));+ std::fs::create_dir_all(root.join("tracked")).unwrap();+ commit(&root.join("tracked"), "t.txt");+ std::fs::create_dir_all(root.join("scratch")).unwrap();+ std::fs::write(root.join("scratch/u.txt"), "u\n").unwrap();+ let ledger = Arc::new(Ledger::default());++ let (here, _l) = ledger.assign(&root.join("tracked"), "a", true, None).unwrap();+ let wt = here.worktree.clone().unwrap();+ assert_eq!(here.root, wt.path.join("tracked"), "a tracked subdirectory maps across");+ // Filed under the repository's slug, the one its alternates name, or+ // `project_key` would not trust them and the child would get an+ // empty store.+ assert_eq!(project_worktrees_dir(&root.join("tracked")), project_worktrees_dir(&root));+ assert!(!here.note().contains("not in this checkout"), "{}", here.note());++ let (untracked, _l) = ledger.assign(&root.join("scratch"), "b", true, None).unwrap();+ let wt = untracked.worktree.clone().unwrap();+ assert_eq!(untracked.root, wt.path);+ assert!(untracked.note().contains("scratch is not in this checkout"), "{}", untracked.note());++ let old = WorkspaceRequest::Ref("old".to_string());+ let (at_ref, _) = ledger.assign(&root.join("tracked"), "c", false, Some(&old)).unwrap();+ let wt = at_ref.worktree.clone().unwrap();+ assert_eq!(at_ref.root, wt.path);+ assert!(at_ref.note().contains("tracked is not in this checkout"), "{}", at_ref.note());+ drop(_l);+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn outside_git_every_child_shares_the_checkout_and_readers_stay_read_only() {+ let dir = std::env::temp_dir().join(format!("jan_child_ws_nogit_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ if crate::core::agent::git::repo_root(&dir).is_some() {+ return;+ }+ let ledger = Arc::new(Ledger::default());+ let (w, lease) = ledger.assign(&dir, "general", true, None).unwrap();+ assert!(w.worktree.is_none() && !w.read_only && lease.is_none());+ assert!(w.note().contains("not a git repository"), "{}", w.note());+ let (r, _) = ledger.assign(&dir, "explore", false, Some(&WorkspaceRequest::New)).unwrap();+ assert!(r.read_only);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A writer child's `project_root`, and through it its Working Directory+ /// and Runtime Environment blocks, and its Session Start branch are its+ /// worktree's, not the parent's.+ #[test]+ fn a_writer_childs_args_point_at_its_worktree() {+ let Some(root) = repo("apply") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let wt = ws.worktree.clone().unwrap();+ let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ args.session_start = Some(crate::core::agent::context::SessionStart::capture(Some(&root)));+ apply(&mut args, &ws, place(&ws, &root, None));+ assert_eq!(args.project_root.as_deref(), Some(wt.path.as_path()));+ let start = args.session_start.as_ref().unwrap().block();+ assert!(start.contains(&wt.branch), "{start}");+ assert!(!args.child_scope.as_ref().unwrap().read_only);+ let prompt = crate::core::agent::context::compose_system_prompt(+ None,+ args.project_root.as_deref().unwrap(),+ None,+ false,+ &Default::default(),+ args.session_start.as_ref(),+ false,+ )+ .unwrap()+ .prefix;+ let shown = wt.path.to_string_lossy().replace('\\', "/");+ assert!(prompt.contains(&format!("Work directory: `{shown}`")), "{prompt}");+ assert!(prompt.contains(&format!("Current project directory: `{}`", wt.path.display())));++ let (reader, _) = ledger.assign(&root, "explore", false, None).unwrap();+ let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ let parent_start = args.session_start.clone();+ apply(&mut args, &reader, place(&reader, &root, None));+ assert_eq!(args.project_root.as_deref(), Some(root.as_path()));+ assert_eq!(args.session_start, parent_start, "a reader keeps the parent's start");+ assert!(args.child_scope.as_ref().unwrap().read_only);+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A writer can swap its checkout's `.git` for a file `gitdir: <a dir it+ /// made>` whose config runs a program (`core.fsmonitor`). Jan's own git in+ /// that checkout runs unsandboxed, so it must neither follow the redirect+ /// nor remove the checkout, and the session-end line must say why it was+ /// kept.+ #[test]+ fn a_checkout_whose_git_dir_was_swapped_for_a_pointer_is_never_followed() {+ let Some(root) = repo("redirect") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.clone().unwrap();+ let marker = root.with_extension("pwned");+ let _ = std::fs::remove_file(&marker);+ let evil = wt.path.with_extension("evil.git");+ assert!(git(&wt.path, &["init", "-q", "--bare", &evil.to_string_lossy()]));+ let hook = wt.path.with_extension("fsmonitor.sh");+ std::fs::write(&hook, format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()))+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let wt_dir = wt.path.to_string_lossy().into_owned();+ let hook_cmd = hook.to_string_lossy().into_owned();+ for (k, v) in [("core.bare", "false"), ("core.worktree", wt_dir.as_str()),+ ("core.fsmonitor", hook_cmd.as_str())]+ {+ assert!(git(&evil, &["config", k, v]));+ }+ std::fs::rename(wt.path.join(".git"), wt.path.with_extension("orig.git")).unwrap();+ std::fs::write(wt.path.join(".git"), format!("gitdir: {}\n", evil.display())).unwrap();++ let live = ledger.live();+ let kept = ledger.finish_session();+ let ran = marker.exists();+ let still_there = wt.path.is_dir();+ let _ = std::fs::remove_file(&marker);+ let _ = std::fs::remove_file(&hook);+ let _ = std::fs::remove_dir_all(&evil);+ let _ = std::fs::remove_dir_all(wt.path.with_extension("orig.git"));+ let _ = std::fs::remove_dir_all(&wt.path);+ let _ = std::fs::remove_dir_all(&root);+ assert!(!ran, "Jan's git ran the redirected repository's fsmonitor");+ assert!(still_there, "a tampered checkout is never removed");+ assert_eq!(kept.len(), 1, "{kept:?}");+ for line in live.iter().chain(&kept) {+ assert!(line.contains(".git was replaced"), "{line}");+ }+ }++ /// A project root that went through `std::fs::canonicalize` (on Windows+ /// the `\\?\C:\...` form) still gets a worktree, and the path the ledger+ /// keeps and hands to git carries no such prefix. Only Windows has the+ /// prefix; elsewhere this checks the same flow with a plain path.+ #[test]+ fn a_verbatim_project_root_still_gets_a_plain_worktree_path() {+ let Some(root) = repo("verbatim") else { return };+ let verbatim = std::fs::canonicalize(&root).unwrap();+ let ledger = Arc::new(Ledger::default());+ let (ws, _lease) = ledger.assign(&verbatim, "general", true, None).unwrap();+ let wt = ws.worktree.clone().expect("a writer gets a worktree");+ assert!(!wt.path.to_string_lossy().starts_with(r"\\?\"), "{wt:?}");+ assert!(wt.path.join(".git").is_dir(), "{wt:?}");+ let scope = scope_for(&ws, &verbatim, None);+ assert!(scope.read_roots.contains(&root.join(".git/objects")), "{scope:?}");+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_writer_is_granted_the_build_dir_and_read_access_to_the_borrowed_objects_only() {+ let Some(root) = repo("scope") else { return };+ let ledger = Arc::new(Ledger::default());+ let (w, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let scope = scope_for(&w, &root, None);+ assert!(!scope.read_only);+ // Its commits go to the repository it is, inside its workspace: none+ // of the user's `.git` is writable, only its objects readable.+ let target = project_worktrees_dir(&root).unwrap().join(CARGO_TARGET);+ assert_eq!(scope.write_roots, vec![target.clone()], "{scope:?}");+ assert_eq!(scope.read_roots, vec![root.join(".git/objects")], "{scope:?}");+ assert!(scope.env_set.iter().any(|(k, v)| k == "CARGO_TARGET_DIR" && Path::new(v) == target));++ let (r, _) = ledger.assign(&root, "explore", false, None).unwrap();+ let scratch = std::env::temp_dir().join(format!("jan_child_scratch_{}", std::process::id()));+ let scope = scope_for(&r, &root, Some(&scratch));+ assert!(scope.read_only);+ assert_eq!(scope.write_roots, vec![target], "a reader never gets the git dir");+ assert!(scope.read_roots.is_empty(), "{scope:?}");+ let yarn = scope.env_set.iter().find(|(k, _)| k == "YARN_CACHE_FOLDER");+ assert!(yarn.is_some_and(|(_, v)| v.ends_with("/yarn-cache")), "{scope:?}");+ assert!(scope.env_set.iter().any(|(k, _)| k == "COREPACK_HOME"), "{scope:?}");+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Run `command` in `ws` the way its child's shell runs: sandboxed, under+ /// the scope [`scope_for`] gives it. `None` when no sandbox can start here.+ fn child_shell(ws: &ChildWorkspace, parent_root: &Path, command: &str) -> Option<String> {+ child_shell_seeing(ws, parent_root, &[], command)+ }++ /// [`child_shell`] with `visible` also mounted read-only, as the user's+ /// home is for a run with `home_readonly`.+ fn child_shell_seeing(+ ws: &ChildWorkspace,+ parent_root: &Path,+ visible: &[PathBuf],+ command: &str,+ ) -> Option<String> {+ use tauri_plugin_agent_tools::tools::{handlers::execute_builtin, jail, lookup, ToolContext};+ if !jail::backend().enforces() {+ eprintln!("skipping: no sandbox backend on this host");+ return None;+ }+ let scope = scope_for(ws, parent_root, None);+ let reads: Vec<PathBuf> = scope+ .write_roots+ .iter()+ .chain(&scope.read_roots)+ .chain(visible)+ .cloned()+ .collect();+ let store = std::env::temp_dir().join(format!("jan_child_store_{}", std::process::id()));+ let ctx = ToolContext::new(&ws.root, &store, &[])+ .with_sandbox(true)+ .with_read_roots(&reads)+ .with_write_roots(&scope.write_roots)+ .with_env_set(&scope.env_set);+ let args = serde_json::json!({"command": command, "timeout": 120});+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ Some(rt.block_on(execute_builtin(lookup("shell").unwrap(), &args, &ctx)).0)+ }++ /// Every entry under `dir` but those `skip` names: a file's contents, a+ /// symlink's target, a directory as itself.+ fn tree(dir: &Path, skip: &dyn Fn(&str) -> bool) -> std::collections::BTreeMap<String, String> {+ fn walk(+ top: &Path,+ dir: &Path,+ skip: &dyn Fn(&str) -> bool,+ out: &mut std::collections::BTreeMap<String, String>,+ ) {+ for entry in std::fs::read_dir(dir).unwrap().map(Result::unwrap) {+ let path = entry.path();+ let rel = path.strip_prefix(top).unwrap().to_string_lossy().replace('\\', "/");+ if skip(&rel) {+ continue;+ }+ let meta = std::fs::symlink_metadata(&path).unwrap();+ if meta.file_type().is_symlink() {+ let to = std::fs::read_link(&path).unwrap();+ out.insert(rel, format!("-> {}", to.display()));+ } else if meta.is_dir() {+ out.insert(rel, "dir".to_string());+ walk(top, &path, skip, out);+ } else {+ let bytes = std::fs::read(&path).unwrap();+ out.insert(rel, String::from_utf8_lossy(&bytes).into_owned());+ }+ }+ }+ let mut out = std::collections::BTreeMap::new();+ walk(dir, dir, skip, &mut out);+ out+ }++ /// A writer's checkout is a repository of its own, so every git operation+ /// works there under the sandbox, the ones that rewrite `packed-refs` or+ /// repack included.+ #[cfg(target_os = "linux")]+ #[test]+ fn a_sandboxed_writer_can_run_any_git_operation_in_its_checkout() {+ let Some(root) = repo("anyop") else { return };+ assert!(git(&root, &["tag", "v1"]));+ let ledger = Arc::new(Ledger::default());+ let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let id = "-c user.name=t -c user.email=t@t -c commit.gpgSign=false -c tag.gpgSign=false";+ let steps = [+ format!("echo b > b.txt && git add b.txt && git {id} commit -q -m b"),+ "git branch side && git branch -d side".to_string(),+ format!("git {id} tag -a -m t t1 && git tag -d t1"),+ "echo s >> b.txt && git stash -q && git stash pop -q && \+ ! git rev-parse -q --verify refs/stash && grep -q s b.txt"+ .to_string(),+ "git gc -q && git pack-refs --all && git repack -q -a -d".to_string(),+ ];+ let mut failed = Vec::new();+ for step in &steps {+ let Some(out) = child_shell(&ws, &root, step) else { return };+ if !out.contains("[exit 0]") {+ failed.push(format!("{step}: {out}"));+ }+ }+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&ws.worktree.as_ref().unwrap().path);+ let _ = std::fs::remove_dir_all(&root);+ assert!(failed.is_empty(), "{failed:#?}");+ }++ /// Nothing a sandboxed writer does reaches the user's `.git`: not a+ /// pointer file, not a symlink planted where the user's git appends a+ /// reflog or writes packs, not a replace ref, config or hook.+ #[cfg(target_os = "linux")]+ #[test]+ fn a_sandboxed_writer_cannot_write_the_users_git_dir() {+ let Some(root) = repo("nouser") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, _lease) = ledger.assign(&root, "general", true, None).unwrap();+ let dot = root.join(".git");+ let outside = root.with_extension("outside");+ let _ = std::fs::remove_dir_all(&outside);+ std::fs::create_dir_all(&outside).unwrap();+ let head = crate::core::agent::git::head_sha(&root).unwrap();+ let g = dot.display();+ let o = outside.display();+ let attempts = [+ format!("echo /tmp/evil > {g}/commondir"),+ format!("mkdir -p {g}/logs && ln -sf {o}/bashrc {g}/logs/HEAD"),+ format!("ln -sf {o}/bashrc {g}/logs/refs/heads/main"),+ format!("mv {g}/objects/pack {g}/objects/pack.old"),+ format!("ln -s {o} {g}/objects/pack/evil"),+ format!("mkdir -p {g}/refs/replace && echo {head} > {g}/refs/replace/{head}"),+ format!("git --git-dir={g} update-ref refs/heads/evil {head}"),+ format!("echo '[core] fsmonitor = touch {o}/pwned' >> {g}/config"),+ format!("mkdir -p {g}/hooks && echo 'touch {o}/pwned' > {g}/hooks/post-commit"),+ format!("echo {o} > {g}/objects/info/alternates"),+ ];+ let before = tree(&dot, &|_| false);+ let mut wrote = Vec::new();+ for cmd in &attempts {+ // The user's repository visible to it, read-only: the most a+ // child is ever shown of it.+ let Some(out) = child_shell_seeing(&ws, &root, std::slice::from_ref(&root), cmd) else { return };+ if out.contains("[exit 0]") {+ wrote.push(format!("{cmd}: {out}"));+ }+ }+ let after = tree(&dot, &|_| false);+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&ws.worktree.as_ref().unwrap().path);+ let _ = std::fs::remove_dir_all(&outside);+ let _ = std::fs::remove_dir_all(&root);+ assert!(wrote.is_empty(), "these wrote the user's .git: {wrote:#?}");+ assert_eq!(after, before, "the user's .git changed");+ }++ /// Make `path` an executable script that touches `marker` when run.+ fn trap(path: &Path, marker: &Path) {+ std::fs::write(path, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ }++ /// Whatever a writer leaves in its own checkout's config, attributes,+ /// hooks or a repository nested in it, Jan's own git (the listing, the+ /// session-end sweep, bringing the branch back) runs none of it, and the+ /// user's repository gains the branch and nothing else.+ #[cfg(unix)]+ #[test]+ fn a_tampered_checkout_runs_nothing_when_jan_inspects_and_fetches_it() {+ let Some(root) = repo("tamper") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.clone().unwrap();+ let c = wt.path.clone();+ let marker = root.with_extension("ran");+ let _ = std::fs::remove_file(&marker);+ let hook = root.with_extension("trap.sh");+ trap(&hook, &marker);+ let h = hook.display().to_string();+ // The child's own work, and a repository nested in it, committed.+ commit(&c, "b.txt");+ let sub = c.join("sub");+ std::fs::create_dir_all(&sub).unwrap();+ assert!(git(&sub, &["init", "-q"]));+ commit(&sub, "s.txt");+ assert!(git(&sub, &["config", "core.fsmonitor", &h]));+ assert!(git(&c, &["add", "sub"]));+ assert!(git(&c, &["commit", "-q", "--no-gpg-sign", "-m", "sub"]));+ std::fs::write(sub.join("s.txt"), "dirty\n").unwrap();+ let tip = crate::core::agent::git::head_sha(&c).unwrap();+ // Then config that runs a program the next time git looks.+ for (k, v) in [+ ("core.fsmonitor", h.as_str()),+ ("filter.jan.process", h.as_str()),+ ("filter.jan.clean", h.as_str()),+ ("filter.jan.required", "true"),+ ("core.hooksPath", root.parent().unwrap().to_str().unwrap()),+ ("remote.evil.url", root.to_str().unwrap()),+ ("remote.evil.uploadpack", h.as_str()),+ ("uploadpack.packObjectsHook", h.as_str()),+ ("core.alternateRefsCommand", h.as_str()),+ ] {+ let config = c.join(".git/config");+ let out = Command::new("git")+ .args(["config", "--file", &config.to_string_lossy(), k, v])+ .status()+ .unwrap();+ assert!(out.success(), "{k}");+ }+ std::fs::write(c.join(".gitattributes"), "* filter=jan\n").unwrap();+ std::fs::write(c.join("a.txt"), "edited\n").unwrap();+ // The branch's own ref, its reflog and the directories they sit in.+ let skip = |rel: &str| {+ rel.starts_with("objects/") || rel.ends_with("heads/jan") || rel.contains("jan/agent")+ || rel == "index"+ };+ let before = tree(&root.join(".git"), &skip);++ let live = ledger.live();+ let kept = ledger.finish_session();+ let after = tree(&root.join(".git"), &skip);+ let ran = marker.exists();+ let branch = crate::core::agent::git::resolve_commit(&root, &wt.branch);+ let main_ok = git(&root, &["status", "--short"])+ && git(&root, &["log", "-1", "--oneline", &wt.branch])+ && git(&root, &["commit", "-q", "--allow-empty", "--no-gpg-sign", "-m", "m"]);+ let _ = std::fs::remove_dir_all(&c);+ let _ = std::fs::remove_file(&hook);+ let _ = std::fs::remove_file(&marker);+ let _ = std::fs::remove_dir_all(&root);+ assert!(!ran, "Jan's git ran a program the child configured");+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(live[0].contains("2 commit(s)"), "{live:?}");+ assert_eq!(branch.as_deref(), Some(tip.as_str()), "the branch is in the user's repo");+ assert_eq!(after, before, "the user's .git changed beyond the branch");+ assert!(main_ok, "the user's checkout still works");+ }++ /// A finished writer's branch is in the user's repository, and its answer+ /// names it. A branch with no commits is not created there, and one the+ /// user has since moved is never overwritten: the footer says so instead.+ #[test]+ fn a_writers_branch_is_brought_back_and_never_overwrites_the_users() {+ let Some(root) = repo("bring") else { return };+ let ledger = Arc::new(Ledger::default());+ let (idle, l1) = ledger.assign(&root, "general", true, None).unwrap();+ let (done, l2) = ledger.assign(&root, "general-2", true, None).unwrap();+ let (clash, l3) = ledger.assign(&root, "general-3", true, None).unwrap();+ drop((l1, l2, l3));+ commit(&done.root, "b.txt");+ commit(&clash.root, "c.txt");+ let branch = |ws: &ChildWorkspace| ws.worktree.as_ref().unwrap().branch.clone();+ // The user got there first, on a branch of the same name.+ assert!(git(&root, &["branch", &branch(&clash)]));+ commit(&root, "u.txt");+ assert!(git(&root, &["branch", "-f", &branch(&clash), "HEAD"]));+ let user_tip = crate::core::agent::git::resolve_commit(&root, &branch(&clash));++ let none = idle.bring_back();+ let brought = done.bring_back();+ let refused = clash.bring_back();+ let git_head = |ws: &ChildWorkspace| crate::core::agent::git::head_sha(&ws.root);+ let in_repo = crate::core::agent::git::resolve_commit(&root, &branch(&done));+ let footer = done.answer_footer(brought.as_deref()).unwrap();+ let clash_footer = clash.answer_footer(refused.as_deref()).unwrap();+ let clash_now = crate::core::agent::git::resolve_commit(&root, &branch(&clash));+ let idle_branch = crate::core::agent::git::resolve_commit(&root, &branch(&idle));+ let reader = ChildWorkspace::shared(&root, true);+ let _ = ledger.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(none, None);+ assert_eq!(idle_branch, None, "a branch with no commits is not created");+ assert_eq!(brought, None);+ assert_eq!(in_repo, git_head(&done));+ assert!(footer.contains(&branch(&done)) && !footer.contains("could not"), "{footer}");+ assert!(refused.is_some(), "a branch the user moved is not overwritten");+ assert_eq!(clash_now, user_tip);+ assert!(clash_footer.contains("could not be brought"), "{clash_footer}");+ assert_eq!(reader.answer_footer(None), None);+ assert_eq!(reader.bring_back(), None);+ }++ /// Config git reads beyond the repository's own file (an `include`, the+ /// `extensions` a format version 1 turns on) cannot be emptied by an+ /// override, so such a checkout is neither read nor removed.+ #[test]+ fn a_checkout_whose_config_reaches_other_files_is_not_read() {+ for (key, value) in [+ ("include.path", "/etc/hostname"),+ ("includeIf.gitdir:/.path", "/etc/hostname"),+ ("extensions.partialClone", "evil"),+ ("core.repositoryformatversion", "1"),+ ] {+ let Some(root) = repo("config") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.clone().unwrap();+ commit(&wt.path, "b.txt");+ let config = wt.path.join(".git/config");+ let set = Command::new("git")+ .args(["config", "--file", &config.to_string_lossy(), key, value])+ .status()+ .unwrap();+ assert!(set.success(), "{key}");++ let kept = ledger.finish_session();+ let fetched = crate::core::agent::git::resolve_commit(&root, &wt.branch);+ let still_there = wt.path.is_dir();+ let _ = std::fs::remove_dir_all(&wt.path);+ let _ = std::fs::remove_dir_all(&root);+ assert!(still_there && fetched.is_none(), "{key}");+ assert_eq!(kept.len(), 1, "{key}: {kept:?}");+ assert!(kept[0].contains("not read and not removed"), "{key}: {kept:?}");+ }+ }++ /// A checkout whose alternates no longer name only the user's objects is+ /// neither fetched from nor removed, and the kept line says why.+ #[test]+ fn a_checkout_with_rewritten_alternates_is_not_fetched_from() {+ let Some(root) = repo("alternates") else { return };+ let ledger = Arc::new(Ledger::default());+ let (ws, lease) = ledger.assign(&root, "general", true, None).unwrap();+ drop(lease);+ let wt = ws.worktree.clone().unwrap();+ commit(&wt.path, "b.txt");+ let alternates = wt.path.join(".git/objects/info/alternates");+ let mut text = std::fs::read_to_string(&alternates).unwrap_or_default();+ text.push_str("/etc\n");+ std::fs::write(&alternates, text).unwrap();++ let kept = ledger.finish_session();+ let fetched = crate::core::agent::git::resolve_commit(&root, &wt.branch);+ let still_there = wt.path.is_dir();+ let _ = std::fs::remove_dir_all(&wt.path);+ let _ = std::fs::remove_dir_all(&root);+ assert!(still_there);+ assert_eq!(fetched, None, "nothing fetched from it");+ assert_eq!(kept.len(), 1, "{kept:?}");+ assert!(kept[0].contains("alternates"), "{kept:?}");+ }+}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 9a613e9a2..778d308b3 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -251,6 +251,21 @@ yourself for small, targeted tasks where delegating would cost more than it savememory: no memory tool and no memory index. Put any fact from your memory that a subagent needs into its \task, and record anything worth keeping from its answer yourself.";+/// Where a dispatched child works, appended to [`SUBAGENT_GUIDE`] only in the+/// CLI build: the desktop makes no checkouts and keeps readers writable (see+/// `child_workspace`), so there it would describe branches that never exist.+/// A constant per build, so the prefix stays byte-stable.+const SUBAGENT_WORKSPACE_GUIDE: &str = if cfg!(feature = "cli") {+ "\n\nEach subagent's workspace is set when you dispatch it. One that can write or edit files works in its own \+checkout (a clone) on its own branch, started from HEAD, so parallel writers never share a checkout and \+your uncommitted changes are not in it; its branch is in your repository when it is done, to merge. \+Any other subagent works in your checkout read-only. The dispatch result says where each one works. Override with `workspace`: \"new\", \+\"shared\", the name of an earlier subagent to continue in its worktree, or `workspace: {\"ref\": \"<git \+ref>\"}` to review or test a branch or pull request in a checkout of its own."+} else {+ ""+};+/// The `# Subagents` block: the guide, then the predefined agents the/// `dispatch_subagent` `agent` enum accepts, each with its model and purpose./// Read from the registry when the prompt is composed, so it is fixed for the@@ -259,8 +274,10 @@ task, and record anything worth keeping from its answer yourself.";fn subagent_guide(project_root: &Path) -> String {let registry = crate::core::agent::subagent::SubagentRegistry::load(project_root);match crate::core::agent::subagent::agent_catalog(®istry) {- Some(catalog) => format!("{SUBAGENT_GUIDE}\n\nPredefined agents (`agent` field):\n{catalog}"),- None => SUBAGENT_GUIDE.to_string(),+ Some(catalog) => format!(+ "{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}\n\nPredefined agents (`agent` field):\n{catalog}"+ ),+ None => format!("{SUBAGENT_GUIDE}{SUBAGENT_WORKSPACE_GUIDE}"),}}@@ -513,6 +530,17 @@ impl SessionStart {}}+ /// Read the clock now, with a `branch` the caller already read. Takes no+ /// memory snapshot: its caller places a worktree subagent, and subagents+ /// have no memory.+ pub(crate) fn with_branch(branch: Option<String>) -> Self {+ Self {+ date: chrono::Local::now().format("%Y-%m-%d").to_string(),+ branch,+ memory: None,+ }+ }+#[cfg(test)]pub(crate) fn fixed(date: &str, branch: Option<&str>) -> Self {Self {@@ -1195,6 +1223,36 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // Where a child works is decided at dispatch, and the CLI guide says so,+ // ahead of the agent catalog.+ #[cfg(feature = "cli")]+ #[test]+ fn the_cli_subagent_guide_explains_child_worktrees() {+ let root = scratch_project("subagent-worktrees");+ let with = default_prompt(None, &root, None, true).expect("prompt");+ assert!(with.contains("own checkout"), "{with}");+ assert!(with.contains("is in your repository"), "{with}");+ assert!(with.contains("read-only"), "{with}");+ assert!(with.contains("workspace: {\"ref\""), "{with}");+ let guide = with.find("Each subagent's workspace").expect("workspace paragraph");+ assert!(guide < with.find("Predefined agents").unwrap(), "{with}");+ let _ = std::fs::remove_dir_all(&root);+ }++ // The desktop makes no worktrees and keeps readers writable, so its agent+ // is told nothing about either.+ #[cfg(not(feature = "cli"))]+ #[test]+ fn the_desktop_subagent_guide_says_nothing_of_worktrees() {+ let root = scratch_project("subagent-desktop");+ let with = default_prompt(None, &root, None, true).expect("prompt");+ assert!(with.contains("belongs to that subagent"), "{with}");+ assert!(!with.contains("own checkout"), "{with}");+ assert!(!with.contains("is in your repository"), "{with}");+ assert!(!with.contains("`workspace`"), "{with}");+ let _ = std::fs::remove_dir_all(&root);+ }+// ── Runtime environment block ────────────────────────────────────────#[test]diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 75a3f4b8b..439539f73 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -116,6 +116,10 @@ pub enum StreamEvent {/// `subagent_name`, so matching on name alone is ambiguous.#[serde(default, skip_serializing_if = "Option::is_none")]task: Option<String>,+ /// Where the child works: its own worktree and branch, or the+ /// checkout it was given, marked when read-only.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ workspace: Option<String>,},/// A backgrounded subagent dispatch found the parent run's concurrency cap/// (`max_parallel_subagents`) exhausted and queued the child in FIFO order.@@ -615,6 +619,7 @@ pub(crate) mod tests {run_id: "r1".into(),name: "scout".into(),task: Some("look".into()),+ workspace: None,},),(@@ -1119,6 +1124,7 @@ pub(crate) mod tests {run_id: "sub-1".into(),name: "rust-reviewer".into(),task: None,+ workspace: None,}).unwrap();assert_eq!(diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex 4bd36d6be..643942a4f 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -79,16 +79,97 @@ fn git(args: &[&str]) -> Result<String, String> {/// never triggers commit signing.#[cfg(feature = "cli")]fn run(repo: &Path, index: Option<&Path>, args: &[&str]) -> Result<String, String> {+ let mut cmd = repo_command(repo, args)?;+ if let Some(idx) = index {+ cmd.env("GIT_INDEX_FILE", idx);+ }+ let out = cmd.output().map_err(|e| format!("failed to launch git: {e}"))?;+ outcome(&out, args)+}++/// `git -C <repo> <args>` with the fixed agent identity [`run`] describes.+#[cfg(feature = "cli")]+fn repo_command(repo: &Path, args: &[&str]) -> Result<Command, String> {let mut cmd = git_command()?;cmd.arg("-C").arg(repo).args(args);cmd.env("GIT_AUTHOR_NAME", "Jan Agent").env("GIT_AUTHOR_EMAIL", "[email protected]").env("GIT_COMMITTER_NAME", "Jan Agent").env("GIT_COMMITTER_EMAIL", "[email protected]");- if let Some(idx) = index {- cmd.env("GIT_INDEX_FILE", idx);- }- let out = cmd.output().map_err(|e| format!("failed to launch git: {e}"))?;+ Ok(cmd)+}++/// [`run`] for a command that talks to a remote, which may never answer:+/// past `limit` the command and every helper it started (a remote helper, an+/// `ext::` transport's shell) are killed and this errors. It never prompts,+/// since nobody is at a terminal to answer.+#[cfg(feature = "cli")]+fn run_limited(repo: &Path, args: &[&str], limit: std::time::Duration) -> Result<String, String> {+ use std::io::Read;+ use std::process::Stdio;+ // `git_command` already gives git no stdin, no prompt and (unix) a session+ // of its own, whose group a timeout kills so the helpers die with it+ // instead of holding its pipes open. Adding `process_group(0)` here would+ // make that `setsid` fail and the spawn with it.+ let mut cmd = repo_command(repo, args)?;+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut child = cmd.spawn().map_err(|e| format!("failed to launch git: {e}"))?;+ // Drained while it runs, or a chatty command fills a pipe and never exits.+ let drain = |pipe: Option<Box<dyn Read + Send>>| {+ std::thread::spawn(move || {+ let mut buf = Vec::new();+ if let Some(mut pipe) = pipe {+ let _ = pipe.read_to_end(&mut buf);+ }+ buf+ })+ };+ let stdout = drain(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let stderr = drain(child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let deadline = std::time::Instant::now() + limit;+ let status = loop {+ match child.try_wait() {+ Ok(Some(status)) => break status,+ Ok(None) if std::time::Instant::now() < deadline => {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ waited => {+ kill_tree(&mut child);+ // The drain threads are left to finish on their own: a helper+ // outside the group could still hold a pipe open.+ return Err(match waited {+ Err(e) => format!("failed to wait for git: {e}"),+ _ => format!(+ "git {} timed out after {}s",+ args.first().copied().unwrap_or(""),+ limit.as_secs()+ ),+ });+ }+ }+ };+ let out = std::process::Output {+ status,+ stdout: stdout.join().unwrap_or_default(),+ stderr: stderr.join().unwrap_or_default(),+ };+ outcome(&out, args)+}++/// Kill `child` and every helper it spawned (its process group on Unix, its+/// process tree on Windows, where `git-remote-https` would otherwise outlive a+/// timed-out fetch), then reap it.+#[cfg(feature = "cli")]+fn kill_tree(child: &mut std::process::Child) {+ tauri_plugin_agent_tools::tools::proc::kill_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+}++/// Trimmed stdout of a git that succeeded, else its trimmed stderr (or a+/// generic message naming the subcommand).+#[cfg(feature = "cli")]+fn outcome(out: &std::process::Output, args: &[&str]) -> Result<String, String> {if out.status.success() {Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())} else {@@ -383,15 +464,85 @@ pub(crate) fn worktree_paths(repo: &Path) -> Vec<PathBuf> {/// copy came from a config file or a thread record.#[cfg(feature = "cli")]pub(crate) fn worktree_registered(repo: &Path, path: &Path) -> bool {- let Ok(want) = path.canonicalize() else {+ let Ok(want) = dunce::canonicalize(path) else {return false;};worktree_paths(repo).iter()- .filter_map(|p| p.canonicalize().ok())+ .filter_map(|p| dunce::canonicalize(p).ok()).any(|p| p == want)}+/// Whether a model-supplied ref (a dispatch's `{"ref": ...}`) is a plain+/// name git can neither read as an option nor as a refspec: no leading `-`+/// or `+`, no `:` (a `src:dst` refspec would let a fetch move any local+/// branch), no whitespace or control characters.+pub(crate) fn is_plain_ref(r: &str) -> bool {+ !r.is_empty()+ && !r.starts_with(['-', '+'])+ && !r.chars().any(|c| c == ':' || c.is_whitespace() || c.is_control())+}++/// The commit `rev` names in `repo`, or `None` when it names none or is not a+/// [plain ref](is_plain_ref).+#[cfg(feature = "cli")]+pub(crate) fn resolve_commit(repo: &Path, rev: &str) -> Option<String> {+ if !is_plain_ref(rev) {+ return None;+ }+ let spec = format!("{rev}^{{commit}}");+ run(repo, None, &["rev-parse", "--verify", "--quiet", "--end-of-options", &spec])+ .ok()+ .filter(|sha| is_object_id(sha))+}++/// Fetch `rev` from `origin` and return the commit it named, for a ref the+/// local repository does not have (`pull/9486/head`).+///+/// `rev` must be a [plain ref](is_plain_ref) that `git check-ref-format`+/// accepts, so it is never a refspec with a destination of its own. The+/// destination is a ref private to this call, read and deleted again:+/// `FETCH_HEAD` is shared by every fetch in the repository, so a concurrent+/// one could replace it between this fetch and its resolution, and+/// `--no-write-fetch-head` leaves it to them. `--refmap=` turns off the+/// remote-tracking update a configured `remote.origin.fetch` would make.+#[cfg(feature = "cli")]+pub(crate) fn fetch_commit(+ repo: &Path,+ rev: &str,+ limit: std::time::Duration,+) -> Result<String, String> {+ if !is_plain_ref(rev) {+ return Err(format!("not a git ref: {rev:?}"));+ }+ run(repo, None, &["check-ref-format", "--allow-onelevel", rev])+ .map_err(|_| format!("not a git ref: {rev:?}"))?;+ static FETCH_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let seq = FETCH_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let dest = format!("refs/jan/fetch/{}-{seq}", std::process::id());+ let spec = format!("{rev}:{dest}");+ let fetched = run_limited(+ repo,+ &[+ "fetch",+ "--quiet",+ "--no-tags",+ "--no-write-fetch-head",+ "--refmap=",+ "origin",+ "--",+ &spec,+ ],+ limit,+ )+ .and_then(|_| {+ resolve_commit(repo, &dest).ok_or_else(|| format!("fetching {rev} named no commit"))+ });+ // Also after a failure: a fetch cut off at its limit may have written it.+ let _ = run(repo, None, &["update-ref", "-d", &dest]);+ fetched+}+/// Forget worktree registrations whose directory the user has deleted. Without/// this, `worktree add` refuses a path that a stale registration still claims.#[cfg(feature = "cli")]@@ -399,6 +550,296 @@ pub(crate) fn worktree_prune(repo: &Path) {let _ = run(repo, None, &["worktree", "prune"]);}+/// Make `path` a repository of its own on a new `branch` at `base` (a full+/// commit id) and return the object directory it borrows from `repo` (`git+/// clone --shared`: its `objects/info/alternates` names it). Unlike a linked+/// worktree it shares no git dir with `repo`, so whoever works in it never+/// writes the user's `.git`; the branch reaches `repo` only through+/// [`Checkout::fetch_branch`]. The parent directory is created first; `path`+/// must not exist.+#[cfg(feature = "cli")]+pub(crate) fn clone_shared(+ repo: &Path,+ path: &Path,+ branch: &str,+ base: &str,+) -> Result<PathBuf, String> {+ require_object_id(base)?;+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let made = run(+ repo,+ None,+ &[+ "clone",+ "--shared",+ "--no-checkout",+ "--no-tags",+ "--quiet",+ "--",+ &repo.to_string_lossy(),+ &path.to_string_lossy(),+ ],+ )+ .and_then(|_| run(path, None, &["checkout", "-q", "-b", branch, base, "--"]))+ .and_then(|_| only_branch(path, branch))+ .and_then(|_| match alternates(path)?.as_slice() {+ [objects] => Ok(objects.clone()),+ other => Err(format!("the clone borrows {} object directories, not one", other.len())),+ });+ if made.is_err() {+ let _ = std::fs::remove_dir_all(path);+ }+ made+}++/// Leave a fresh clone with `branch` and nothing else: the clone's copy of the+/// user's current branch and its remote-tracking refs would read as work it+/// holds once the user's repository moves on, and the remote would point the+/// child back at the repository it must not write.+#[cfg(feature = "cli")]+fn only_branch(path: &Path, branch: &str) -> Result<(), String> {+ let heads = run(path, None, &["for-each-ref", "--format=%(refname:short)", "refs/heads"])?;+ for other in heads.lines().filter(|b| *b != branch) {+ run(path, None, &["branch", "-D", "--", other])?;+ }+ run(path, None, &["remote", "remove", "origin"]).map(|_| ())+}++/// The object directories the repository at `checkout` borrows, as its+/// `objects/info/alternates` names them (canonicalized when they exist).+#[cfg(feature = "cli")]+fn alternates(checkout: &Path) -> Result<Vec<PathBuf>, String> {+ let file = checkout.join(".git/objects/info/alternates");+ match std::fs::read_to_string(&file) {+ Ok(raw) => Ok(raw+ .lines()+ .map(str::trim)+ .filter(|l| !l.is_empty())+ .map(|l| dunce::canonicalize(l).unwrap_or_else(|_| PathBuf::from(l)))+ .collect()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),+ Err(e) => Err(format!("could not read {}: {e}", file.display())),+ }+}++/// Whether `key` (as `git config --list` spells it) is one a clone and+/// everyday work in it leave behind and that cannot name a program. Every+/// other key of a child's config is emptied for Jan's own git: whatever it is+/// (`filter.*`, `diff.*`, `merge.*`, `credential.*`, `remote.*.uploadpack`,+/// `core.sshCommand`, ...), it may be a command git would run.+#[cfg(feature = "cli")]+fn inert_config(key: &str) -> bool {+ let Some((section, rest)) = key.split_once('.') else { return false };+ let name = rest.rsplit_once('.').map_or(rest, |(_, name)| name);+ match section {+ "core" => matches!(+ name,+ "repositoryformatversion" | "filemode" | "bare" | "logallrefupdates" | "symlinks"+ | "ignorecase" | "precomposeunicode" | "autocrlf" | "eol" | "safecrlf"+ ),+ "user" | "branch" => true,+ "remote" => matches!(name, "url" | "pushurl" | "fetch" | "push" | "tagopt"),+ _ => false,+ }+}++/// A repository made by [`clone_shared`] that its child has worked in, opened+/// only while it is still what Jan made. Jan's git runs unsandboxed where the+/// child's was confined to this checkout, and the child controls everything+/// in its `.git`: its config can name programs git then runs, its `.git` can+/// be a file, or hold a `commondir`, pointing at another repository, and its+/// alternates can pull in any directory's objects. [`Checkout::open`] refuses+/// a checkout whose `.git` or alternates changed, or whose config reaches+/// beyond itself, and every command of a checkout empties the rest of that+/// config, names its git dir and work tree itself, honors no `replace` ref,+/// starts only the `file` transport and never looks inside a nested+/// repository.+#[cfg(feature = "cli")]+#[derive(Debug, Clone)]+pub(crate) struct Checkout {+ path: PathBuf,+ /// The `key=` overrides that empty every setting of the child's config+ /// that could name a program, read once by [`Checkout::open`].+ overrides: Vec<String>,+}++#[cfg(feature = "cli")]+impl Checkout {+ /// The clone at `path` (its top level) that borrows exactly `objects`, or+ /// an error naming what changed, for the user.+ pub(crate) fn open(path: &Path, objects: &Path) -> Result<Self, String> {+ let dot = path.join(".git");+ let plain = |p: &Path, dir: bool| {+ std::fs::symlink_metadata(p).is_ok_and(|m| if dir { m.is_dir() } else { m.is_file() })+ };+ if !plain(&dot, true) || !plain(&dot.join("objects"), true) || !plain(&dot.join("config"), false)+ {+ return Err("its .git was replaced: it is no longer a plain directory".to_string());+ }+ // Each of these makes git read another repository's config or objects.+ for pointer in ["commondir", "objects/info/http-alternates"] {+ if dot.join(pointer).exists() {+ return Err(format!("its .git has a {pointer} file, which redirects git"));+ }+ }+ if alternates(path)? != [objects.to_path_buf()] {+ return Err(format!(+ "its object alternates were rewritten: it must borrow only {}",+ objects.display()+ ));+ }+ // `--file` reads that one file, follows no `include` and starts nothing.+ let listed = git_command()?+ .args(["config", "--file"])+ .arg(dot.join("config"))+ .args(["--list", "-z"])+ .output()+ .map_err(|e| format!("failed to launch git: {e}"))?;+ if !listed.status.success() {+ return Err("its git config cannot be read".to_string());+ }+ let mut overrides = Vec::new();+ for entry in String::from_utf8_lossy(&listed.stdout).split('\0').filter(|e| !e.is_empty()) {+ let (key, value) = entry.split_once('\n').unwrap_or((entry, ""));+ // These read more files (another config, `config.worktree`) than+ // were looked at here.+ if key.starts_with("include.")+ || key.starts_with("includeif.")+ || key.starts_with("extensions.")+ {+ return Err(format!("its git config sets {key}, which makes git read more"));+ }+ if key == "core.repositoryformatversion" && value != "0" {+ return Err("its repository format is not the one Jan made".to_string());+ }+ if inert_config(key) {+ continue;+ }+ // `-c key=value` splits at the first `=`, so such a key cannot be+ // emptied.+ if key.contains('=') {+ return Err(format!("its git config sets {key}, which git cannot be told to ignore"));+ }+ let pair = format!("{key}=");+ if !overrides.contains(&pair) {+ overrides.push(pair);+ }+ }+ Ok(Self { path: path.to_path_buf(), overrides })+ }++ /// The options every git of Jan's in the checkout takes, ahead of the+ /// subcommand: the child's config emptied of anything that could run,+ /// then what no config may turn back on.+ fn hardened(&self) -> Vec<String> {+ let null = if cfg!(windows) { "NUL" } else { "/dev/null" };+ let mut opts = vec!["--no-replace-objects".to_string(), "--no-optional-locks".to_string()];+ for pair in &self.overrides {+ opts.extend(["-c".to_string(), pair.clone()]);+ }+ opts.extend([+ "-c".to_string(),+ "core.fsmonitor=false".to_string(),+ "-c".to_string(),+ format!("core.hooksPath={null}"),+ ]);+ opts+ }++ /// `git <args>` in the checkout, its git dir and work tree named+ /// explicitly.+ fn run(&self, args: &[&str]) -> Result<String, String> {+ let opts = self.hardened();+ let mut full: Vec<&str> = opts.iter().map(String::as_str).collect();+ full.extend_from_slice(args);+ let mut cmd = repo_command(&self.path, &full)?;+ cmd.env("GIT_DIR", self.path.join(".git"))+ .env("GIT_WORK_TREE", &self.path);+ let out = cmd.output().map_err(|e| format!("failed to launch git: {e}"))?;+ outcome(&out, args)+ }++ /// The branch checked out there, `None` when detached or unreadable.+ pub(crate) fn current_branch(&self) -> Option<String> {+ self.run(&["rev-parse", "--abbrev-ref", "HEAD"])+ .ok()+ .filter(|s| !s.is_empty() && s != "HEAD")+ }++ /// Commits reachable from `tip` (a branch or `HEAD`) but not from+ /// `base`. `None` when git cannot say, which callers must never read as+ /// zero.+ pub(crate) fn commits_on(&self, base: &str, tip: &str) -> Option<u64> {+ require_object_id(base).ok()?;+ if tip.starts_with('-') {+ return None;+ }+ self.run(&["rev-list", "--count", &format!("{base}..{tip}"), "--"])+ .ok()?+ .parse()+ .ok()+ }++ /// Commits any ref of the checkout (or `HEAD`) reaches that `base` does+ /// not: everything the child committed, on whatever branch, stash or tag.+ /// `None` when git cannot say.+ pub(crate) fn commits_anywhere(&self, base: &str) -> Option<u64> {+ require_object_id(base).ok()?;+ self.run(&["rev-list", "--count", "--all", "--not", base, "--"]).ok()?.parse().ok()+ }++ /// [`try_changed_paths`] for this checkout. A nested repository (or a+ /// recorded submodule) is never opened: its own config can name a program+ /// (`core.fsmonitor`) that its status would run.+ pub(crate) fn try_changed_paths(&self) -> Result<Vec<String>, String> {+ changed_paths_with(|args| {+ let mut full = args.to_vec();+ full.push("--ignore-submodules=all");+ self.run(&full)+ })+ }++ /// Fetch `branch` into `repo` under the same name: the child's commits+ /// become a branch of the user's repository. Not forced, so a branch the+ /// user has since built on is never overwritten (the fetch fails instead),+ /// and only that one ref comes. Objects are checked as they arrive.+ /// Bounded by `limit`, like any fetch.+ pub(crate) fn fetch_branch(+ &self,+ repo: &Path,+ branch: &str,+ limit: std::time::Duration,+ ) -> Result<(), String> {+ let spec = format!("refs/heads/{branch}:refs/heads/{branch}");+ let dot = self.path.join(".git").to_string_lossy().into_owned();+ let opts = self.hardened();+ let mut args: Vec<&str> = opts.iter().map(String::as_str).collect();+ // Only the `file` transport, so no helper (`ext::`, a remote helper)+ // is ever started; the `-c`s reach the `upload-pack` git runs in the+ // checkout through the environment.+ args.extend([+ "-c",+ "protocol.allow=never",+ "-c",+ "protocol.file.allow=always",+ "-c",+ "transfer.fsckObjects=true",+ "fetch",+ "--quiet",+ "--no-tags",+ "--no-write-fetch-head",+ "--refmap=",+ "--no-recurse-submodules",+ "--",+ &dot,+ &spec,+ ]);+ run_limited(repo, &args, limit).map(|_| ())+ }+}+/// Paths changed in a worktree relative to its own `HEAD`, staged, unstaged and/// untracked alike (`status --porcelain`, whose status letters are stripped)./// This is the "what has the agent done in there" summary, not a diff.@@ -409,8 +850,26 @@ pub(crate) fn worktree_prune(repo: &Path) {/// eat the first character of that one path.#[cfg(feature = "cli")]pub(crate) fn changed_paths(worktree: &Path) -> Vec<String> {- run(worktree, None, &["status", "--porcelain"])- .unwrap_or_default()+ try_changed_paths(worktree).unwrap_or_default()+}++/// [`changed_paths`], but a `git status` that fails is an error rather than+/// an empty list: a caller deciding whether a checkout may be deleted must not+/// read "git could not tell" as "clean".+///+/// `--untracked-files=all` overrides a user's `status.showUntrackedFiles=no`,+/// under which a checkout holding only new files would read as clean and be+/// force-deleted with them.+#[cfg(feature = "cli")]+pub(crate) fn try_changed_paths(worktree: &Path) -> Result<Vec<String>, String> {+ changed_paths_with(|args| run(worktree, None, args))+}++#[cfg(feature = "cli")]+fn changed_paths_with(+ git: impl Fn(&[&str]) -> Result<String, String>,+) -> Result<Vec<String>, String> {+ Ok(git(&["status", "--porcelain", "--untracked-files=all"])?.lines().filter_map(|l| l.trim_start().split_once(' '))// A rename reads `R old -> new`; the new name is the path on disk, and@@ -420,7 +879,7 @@ pub(crate) fn changed_paths(worktree: &Path) -> Vec<String> {None => path.trim().to_string(),}).filter(|s| !s.is_empty())- .collect()+ .collect())}#[cfg(all(test, feature = "cli"))]@@ -448,6 +907,8 @@ mod tests {assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "prompt=0\ndenied");}+ const LIMIT: std::time::Duration = std::time::Duration::from_secs(60);+/// Init a throwaway repo with one commit, or `None` if git is unavailable so/// the suite skips instead of failing on a box without git.fn init_repo() -> Option<PathBuf> {@@ -748,6 +1209,174 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// A fetch ref comes from the model, so a refspec (`src:dst`, a leading+ /// `+`) is refused before git sees it, and a plain ref lands in+ /// `FETCH_HEAD` only: no local branch or remote-tracking ref moves.+ #[test]+ fn fetch_commit_refuses_refspecs_and_moves_no_local_ref() {+ let Some(upstream) = init_repo() else { return };+ let trunk = current_branch(&upstream).unwrap();+ run(&upstream, None, &["checkout", "-q", "-b", "x"]).unwrap();+ std::fs::write(upstream.join("x.txt"), "x\n").unwrap();+ run(&upstream, None, &["add", "x.txt"]).unwrap();+ run(&upstream, None, &["commit", "-q", "-m", "x", "--no-gpg-sign"]).unwrap();+ let x = head_sha(&upstream).unwrap();+ run(&upstream, None, &["checkout", "-q", &trunk]).unwrap();+ let clone = upstream.with_extension("clone");+ let _ = std::fs::remove_dir_all(&clone);+ let (from, to) = (upstream.to_string_lossy(), clone.to_string_lossy());+ git(&["clone", "-q", "--single-branch", "-b", &trunk, &from, &to]).unwrap();+ // The usual wildcard refspec, under which a plain `git fetch origin x`+ // would also move `refs/remotes/origin/x`.+ let wide = "+refs/heads/*:refs/remotes/origin/*";+ run(&clone, None, &["config", "remote.origin.fetch", wide]).unwrap();+ run(&clone, None, &["branch", "victim"]).unwrap();+ let before = head_sha(&clone).unwrap();++ for bad in [+ "+refs/heads/x:refs/heads/victim",+ "x:victim",+ "refs/heads/x:refs/heads/victim",+ "+x",+ "x:",+ "x\u{7}",+ ] {+ assert!(fetch_commit(&clone, bad, LIMIT).is_err(), "{bad:?} must be refused");+ assert_eq!(+ resolve_commit(&clone, "refs/heads/victim").as_deref(),+ Some(before.as_str()),+ "{bad:?} moved a local branch"+ );+ }+ assert_eq!(fetch_commit(&clone, "x", LIMIT).as_deref(), Ok(x.as_str()));+ assert_eq!(resolve_commit(&clone, "refs/heads/x"), None, "no local branch made");+ assert_eq!(resolve_commit(&clone, "refs/remotes/origin/x"), None);+ assert_eq!(resolve_commit(&clone, "refs/heads/victim").as_deref(), Some(before.as_str()));+ let _ = std::fs::remove_dir_all(&clone);+ let _ = std::fs::remove_dir_all(&upstream);+ }++ /// Concurrent fetches in one repository would share `FETCH_HEAD`, so one+ /// could resolve the commit another fetched. A fetch therefore resolves+ /// from a ref of its own and leaves `FETCH_HEAD`, and no ref, behind.+ #[test]+ fn fetch_commit_neither_reads_nor_writes_the_shared_fetch_head() {+ let Some(upstream) = init_repo() else { return };+ let trunk = current_branch(&upstream).unwrap();+ let base = head_sha(&upstream).unwrap();+ run(&upstream, None, &["checkout", "-q", "-b", "x"]).unwrap();+ std::fs::write(upstream.join("x.txt"), "x\n").unwrap();+ run(&upstream, None, &["add", "x.txt"]).unwrap();+ run(&upstream, None, &["commit", "-q", "-m", "x", "--no-gpg-sign"]).unwrap();+ let x = head_sha(&upstream).unwrap();+ run(&upstream, None, &["checkout", "-q", &trunk]).unwrap();+ let clone = upstream.with_extension("fetchhead");+ let _ = std::fs::remove_dir_all(&clone);+ let (from, to) = (upstream.to_string_lossy(), clone.to_string_lossy());+ git(&["clone", "-q", "--single-branch", "-b", &trunk, &from, &to]).unwrap();+ // What another fetch running alongside left there.+ let other = format!("{base}\t\tbranch 'other' of elsewhere\n");+ let fetch_head = clone.join(".git/FETCH_HEAD");+ std::fs::write(&fetch_head, &other).unwrap();++ assert_eq!(fetch_commit(&clone, "x", LIMIT).as_deref(), Ok(x.as_str()));+ assert_eq!(std::fs::read_to_string(&fetch_head).unwrap(), other);+ let left = run(&clone, None, &["for-each-ref", "refs/jan/"]).unwrap();+ assert!(left.is_empty(), "{left}");+ let _ = std::fs::remove_dir_all(&clone);+ let _ = std::fs::remove_dir_all(&upstream);+ }++ /// A fetch from a remote that never answers gives up at its limit with an+ /// error saying so, rather than holding the dispatch that asked for it.+ #[test]+ fn a_fetch_from_a_remote_that_never_answers_times_out() {+ let Some(root) = init_repo() else { return };+ run(&root, None, &["config", "protocol.ext.allow", "always"]).unwrap();+ run(&root, None, &["remote", "add", "origin", "ext::sh -c sleep% 600"]).unwrap();+ let started = std::time::Instant::now();+ let err = fetch_commit(&root, "pull/1/head", std::time::Duration::from_secs(2))+ .unwrap_err();+ assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());+ assert!(err.contains("timed out after 2s"), "{err}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The primitives a subagent checkout's life is built from: resolve a ref+ /// to the commit it names, make a clone of its own that borrows only the+ /// user's objects, count what was committed in it, and bring its branch+ /// back into the user's repository.+ #[test]+ fn a_child_checkout_can_be_made_counted_and_brought_back() {+ let Some(root) = init_repo() else { return };+ let head = head_sha(&root).unwrap();+ assert_eq!(resolve_commit(&root, "HEAD").as_deref(), Some(head.as_str()));+ assert_eq!(resolve_commit(&root, "no-such-ref"), None);+ // A ref is never read as an option, whatever it is spelled as.+ assert_eq!(resolve_commit(&root, "--output=x"), None);++ let wt = root.parent().unwrap().join(format!(+ "{}-child",+ root.file_name().unwrap().to_string_lossy()+ ));+ let _ = std::fs::remove_dir_all(&wt);+ let objects = clone_shared(&root, &wt, "jan/agent/child-1", &head).unwrap();+ assert_eq!(objects, dunce::canonicalize(root.join(".git/objects")).unwrap());+ let wt = dunce::canonicalize(&wt).unwrap();+ assert!(wt.join(".git").is_dir(), "a repository of its own, not a linked worktree");+ assert!(!wt.join(".git/commondir").exists());+ let heads = run(&wt, None, &["for-each-ref", "--format=%(refname)"]).unwrap();+ assert_eq!(heads, "refs/heads/jan/agent/child-1", "no other branch, no remote refs");+ assert!(run(&wt, None, &["remote"]).unwrap().is_empty());++ let child = Checkout::open(&wt, &objects).unwrap();+ assert_eq!(child.current_branch().as_deref(), Some("jan/agent/child-1"));+ assert_eq!(child.commits_on(&head, "HEAD"), Some(0));+ std::fs::write(wt.join("b.txt"), "b\n").unwrap();+ run(&wt, None, &["add", "b.txt"]).unwrap();+ run(&wt, None, &["commit", "-q", "-m", "b", "--no-gpg-sign"]).unwrap();+ assert_eq!(child.commits_on(&head, "HEAD"), Some(1));+ assert_eq!(child.commits_on(&head, "refs/heads/jan/agent/child-1"), Some(1));+ assert_eq!(child.commits_on(&head, "--all"), None, "never an option");+ assert_eq!(child.commits_anywhere(&head), Some(1));+ std::fs::write(wt.join("c.txt"), "c\n").unwrap();+ assert_eq!(child.try_changed_paths(), Ok(vec!["c.txt".to_string()]));++ assert_eq!(resolve_commit(&root, "jan/agent/child-1"), None, "not there yet");+ child.fetch_branch(&root, "jan/agent/child-1", LIMIT).unwrap();+ let tip = head_sha(&wt).unwrap();+ assert_eq!(resolve_commit(&root, "jan/agent/child-1").as_deref(), Some(tip.as_str()));+ assert!(run(&root, None, &["for-each-ref", "refs/jan/"]).unwrap().is_empty());++ // A `.git` swapped for a file, a `commondir`, rewritten alternates and+ // a config that includes another file are each refused before any git+ // runs in it.+ let dot = wt.join(".git");+ let elsewhere = wt.join("elsewhere");+ std::fs::create_dir_all(&elsewhere).unwrap();+ let alternates = dot.join("objects/info/alternates");+ let good = std::fs::read_to_string(&alternates).unwrap();+ std::fs::write(&alternates, format!("{good}{}\n", elsewhere.display())).unwrap();+ let err = Checkout::open(&wt, &objects).unwrap_err();+ assert!(err.contains("alternates"), "{err}");+ std::fs::write(&alternates, &good).unwrap();+ std::fs::write(dot.join("commondir"), "/elsewhere\n").unwrap();+ assert!(Checkout::open(&wt, &objects).unwrap_err().contains("commondir"));+ std::fs::remove_file(dot.join("commondir")).unwrap();+ run(&wt, None, &["config", "include.path", "/elsewhere"]).unwrap();+ assert!(Checkout::open(&wt, &objects).unwrap_err().contains("include"));+ run(&wt, None, &["config", "--unset", "include.path"]).unwrap();+ assert!(Checkout::open(&wt, &objects).is_ok());+ let moved = wt.with_extension("moved");+ std::fs::rename(&dot, &moved).unwrap();+ std::fs::write(&dot, "gitdir: /elsewhere\n").unwrap();+ let err = Checkout::open(&wt, &objects).unwrap_err();+ assert!(err.contains(".git was replaced"), "{err}");+ let _ = std::fs::remove_dir_all(&moved);+ let _ = std::fs::remove_dir_all(&wt);+ let _ = std::fs::remove_dir_all(&root);+ }+/// `current_branch` re-reads `HEAD` live rather than caching it, so a/// checkout made after the first call (e.g. by another process while the/// TUI is open) is picked up on the next call.diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex eaa5df34a..3eb6a3cd3 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -220,6 +220,10 @@ pub(crate) struct OrchestrationArgs {/// subagent (`subagent::spawn_memory_tidy`), which shares it with the TUI/// so a hit cap is reported; `None` everywhere else.pub memory_change_budget: Option<Arc<tauri_plugin_agent_tools::memory::ChangeBudget>>,+ /// Set only on a dispatched child: whether its `project_root` is+ /// read-only, the extra paths its sandboxed shell may write and the+ /// environment it gets (see [`crate::core::agent::child_workspace`]).+ pub child_scope: Option<crate::core::agent::child_workspace::ChildScope>,}#[async_trait]@@ -873,6 +877,46 @@ struct CompositeToolInvoker {memory_changes: Option<MemoryChangesTracker>,/// See [`OrchestrationArgs::memory_change_budget`].memory_change_budget: Option<Arc<tauri_plugin_agent_tools::memory::ChangeBudget>>,+ /// The bucket this run's shells register under (`proc::kill_thread`): a+ /// child's own `run_id`, so stopping it can end the shells it left running+ /// before its worktree goes to another writer. `None` on a top-level run.+ shell_owner: Option<String>,+ /// What a child's workspace adds to its tools: a read-only root, the paths+ /// its shell may also write, and its shell env. A top-level run gets the+ /// default plus, on the CLI, read access to its subagents' worktrees.+ workspace: RunWorkspace,+}++/// The per-run additions to [`CompositeToolInvoker`]'s tool context that come+/// from where the run works (see [`crate::core::agent::child_workspace`]).+#[derive(Debug, Clone, Default)]+struct RunWorkspace {+ read_only: bool,+ read_roots: Vec<std::path::PathBuf>,+ write_roots: Vec<std::path::PathBuf>,+}++impl RunWorkspace {+ /// A child runs under its scope; a parent may read its children's+ /// worktrees. Write roots are also read roots: the tools require it.+ fn resolve(+ scope: Option<&crate::core::agent::child_workspace::ChildScope>,+ root: &std::path::Path,+ ) -> Self {+ match scope {+ Some(scope) => Self {+ read_only: scope.read_only,+ read_roots: scope.write_roots.iter().chain(&scope.read_roots).cloned().collect(),+ write_roots: scope.write_roots.clone(),+ },+ None => Self {+ read_roots: crate::core::agent::child_workspace::parent_read_root(root)+ .into_iter()+ .collect(),+ ..Self::default()+ },+ }+ }}/// Default for the sandboxed shell's network namespace, used when@@ -1161,8 +1205,11 @@ fn format_dispatched_plan(d: &crate::core::agent::subagent::DispatchedPlan) -> S.first_phase.iter().map(|c| match &d.blackboard_dir {- Some(dir) => format!(" - {} (run_id: {}) -> {dir}/{}.md", c.name, c.run_id, c.name),- None => format!(" - {} (run_id: {})", c.name, c.run_id),+ Some(dir) => format!(+ " - {} (run_id: {}) -> {dir}/{}.md; {}",+ c.name, c.run_id, c.name, c.workspace+ ),+ None => format!(" - {} (run_id: {}); {}", c.name, c.run_id, c.workspace),}).collect::<Vec<_>>().join("\n");@@ -1263,6 +1310,9 @@ impl CompositeToolInvoker {let ctx = ctx.with_network(self.allow_network).with_home_readonly(self.allow_home_read).with_sandbox(self.sandbox)+ .with_workspace_readonly(self.workspace.read_only)+ .with_read_roots(&self.workspace.read_roots)+ .with_write_roots(&self.workspace.write_roots).with_escalation(self.escalation.offered()).with_hidden_root(self.hidden_root.as_deref()).with_scratch_root(&self.scratch_root)@@ -1274,7 +1324,8 @@ impl CompositeToolInvoker {self.run_mode == crate::core::agent::plan::RunMode::Plan,Some(self.hook_sink()),)- .with_shell_done_sink(self.shell_done_sink());+ .with_shell_done_sink(self.shell_done_sink())+ .with_thread_id(self.shell_owner.as_deref());match &self.shell_detach {Some(signal) => ctx.with_detach_signal(signal.clone()),None => ctx,@@ -1742,7 +1793,9 @@ impl CompositeToolInvoker {// Unconfined means no scratch: the tools see the real// `/tmp`, so there is nowhere sanctioned to spill.self.subagent_scratch(),- ) {+ )+ .await+ {Ok(d) => format_dispatched_plan(&d),Err(e) => {ctx.bg.release_names(&reserved);@@ -2694,10 +2747,11 @@ impl ToolInvoker for CompositeToolInvoker {&tauri_plugin_agent_tools::tools::gate::GateContext {project_root: &self.project_root,scratch: Some(self.scratch_root.as_path()),- // The CLI works *in* the project, so it has no separate- // read-only or writable root to attach.- read_roots: &[],- write_roots: &[],+ // The CLI works *in* the project; what is attached is+ // its subagents' worktrees (a parent) or the borrowed+ // objects and build dir (a child).+ read_roots: &self.workspace.read_roots,+ write_roots: &self.workspace.write_roots,hidden_root: self.hidden_root.as_deref(),},&self.permissions,@@ -2735,6 +2789,7 @@ impl ToolInvoker for CompositeToolInvoker {let hidden = self.hidden_root.clone();let scratch = self.scratch_root.clone();let web_search = self.web_search.clone();+ let read_roots = self.workspace.read_roots.clone();// Hooks come along: a read is still a tool call, and a// PreToolUse policy that stopped applying to whatever happened// to be batched concurrently would be no policy at all.@@ -2759,6 +2814,7 @@ impl ToolInvoker for CompositeToolInvoker {.with_sandbox(sandbox).with_hidden_root(hidden.as_deref()).with_scratch_root(&scratch)+ .with_read_roots(&read_roots).with_web_search(web_search.as_ref()).with_hooks(&hooks, planning, Some(hook_sink));let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;@@ -2991,6 +3047,7 @@ pub(crate) async fn run_server_side_openai_orchestration(// Each proxy request is a session of one run: it snapshots its own.session_start: None,memory_change_budget: None,+ child_scope: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -3674,6 +3731,7 @@ async fn orchestrate_inner(session_start,// Read through `args` where the invoker is built.memory_change_budget: _,+ child_scope,} = args;// Per-turn override: the TUI toggles plan mode live via the request body@@ -4012,8 +4070,8 @@ async fn orchestrate_inner(if let Some(root) = project_root {// Background subagents are scoped to this run unless the session owns- // them: `_bg_guard` aborts any still-running child when- // `orchestrate_inner` returns or is cancelled. The cap+ // them: `bg_guard` aborts any still-running child and sweeps their+ // worktrees when the run ends or is cancelled. The cap// (`max_parallel_subagents`) is snapshotted here, at run start.let bg = session_subagent_bg.clone().unwrap_or_else(|| {std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(@@ -4025,9 +4083,9 @@ async fn orchestrate_inner(// TUI aborts them on cancel and on session reset). Arming it here would// kill on the first turn's return exactly the children this change// exists to keep running.- let _bg_guard = session_subagent_bg+ let bg_guard = session_subagent_bg.is_none()- .then(|| crate::core::agent::subagent::AbortOnDrop(bg.clone()));+ .then(|| crate::core::agent::subagent::AbortOnDrop::new(bg.clone(), events));let subagents = args.subagents_enabled.then(|| SubagentContext {parent_args: args.clone(),model_id: model_id.clone(),@@ -4087,7 +4145,11 @@ async fn orchestrate_inner(hidden_root: crate::core::agent::project::hidden_root(settings.sandbox),scratch_root: scratch_root.clone(),env_passthrough: settings.env_passthrough,- env_set: settings.env_set,+ // A child's workspace adds its build and cache dirs on top.+ env_set: merge_env_set(+ settings.env_set,+ child_scope.as_ref().map(|c| c.env_set.clone()).unwrap_or_default(),+ ),web_search: resolve_web_search(),project_root: root.clone(),allowed_names: allowed_names.clone(),@@ -4122,12 +4184,15 @@ async fn orchestrate_inner(hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),bg_shells: session_bg_shells.clone().unwrap_or_default(),parent_link: args.parent_link.clone(),+ // Only a child run has an id of its own.+ shell_owner: run_id.clone(),// Without a session registry nothing would deliver the detached// command's end except a park, which holds the message just the// same; so the signal only applies where the session owns shells.shell_detach: args.shell_detach.clone().filter(|_| session_bg_shells.is_some()),memory_changes,memory_change_budget: args.memory_change_budget.clone(),+ workspace: RunWorkspace::resolve(child_scope.as_ref(), root),};// Entries dropped while loading the hook files are reported once here,// before anything fires: a user whose matcher is a bad glob otherwise@@ -4233,13 +4298,21 @@ async fn orchestrate_inner(.await;// On a clean exit, wait for any subagents the model dispatched but never// explicitly awaited, so their in-flight work isn't aborted and lost by- // `_bg_guard`. On an error, teardown still aborts them. A session-owned+ // `bg_guard`. On an error, teardown still aborts them. A session-owned// set is skipped: nothing is about to abort those children, and waiting// here would hold the run open for precisely the work the session set// exists to outlive it.if result.is_ok() && session_subagent_bg.is_none() {bg.join_all().await;}+ // A run-owned registry's children are done with this run, so its end+ // is their session's end: stop any still running, then sweep their+ // worktrees, here rather than when the function returns so the kept+ // notice precedes `SessionEnd`. A session-owned registry has no guard;+ // its owner sweeps it.+ if let Some(guard) = bg_guard {+ guard.finish().await;+ }// Fired on failure too: a SessionEnd hook that only ran on the happy// path could not be used for the cleanup or audit it exists for. Its// answers cannot reach the model (the run is over) and are logged by@@ -8947,6 +9020,8 @@ mod tests {shell_detach: None,memory_changes: None,memory_change_budget: None,+ shell_owner: None,+ workspace: RunWorkspace::default(),}}@@ -12286,10 +12361,12 @@ mod tests {DispatchedChild {name: "explorer-a".to_string(),run_id: "sub-explorer-a-1".to_string(),+ workspace: "working read-only in /p".to_string(),},DispatchedChild {name: "explorer-b".to_string(),run_id: "sub-explorer-b-2".to_string(),+ workspace: "working read-only in /p".to_string(),},],blackboard_dir: Some("blackboard".to_string()),@@ -12312,6 +12389,7 @@ mod tests {first_phase: vec![DispatchedChild {name: "researcher".to_string(),run_id: "sub-researcher-1".to_string(),+ workspace: "working read-only in /p".to_string(),}],blackboard_dir: None,names: vec!["researcher".to_string(), "writer".to_string()],@@ -12603,6 +12681,7 @@ mod tests {first_phase: vec![DispatchedChild {name: "w".to_string(),run_id: "sub-w-1".to_string(),+ workspace: "working read-only in /p".to_string(),}],blackboard_dir: None,names: vec!["w".to_string()],@@ -13023,4 +13102,224 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// How the stub provider answers the parent's second request.+ #[cfg(feature = "cli")]+ #[derive(Clone, Copy)]+ enum SecondTurn {+ /// A 400, which fails the run.+ Fails,+ /// Never, so the test can cancel the run while it waits.+ Hangs,+ }++ /// A git project whose run dispatches one `writer` child into a fresh+ /// worktree, against a stub provider on which the child's request never+ /// returns: the writer is still in its worktree, holding its lease, when+ /// the parent's run ends. Returns the project, the run's args, and a+ /// receiver signalled once the parent's second request has arrived (the+ /// dispatch is done by then). `None` without git.+ #[cfg(feature = "cli")]+ fn run_with_a_stuck_writer(+ second: SecondTurn,+ ) -> Option<(+ std::path::PathBuf,+ OrchestrationArgs,+ std::sync::mpsc::Receiver<()>,+ )> {+ use std::io::{BufRead, BufReader, Read, Write};++ let root = unique_project_root();+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ };+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"])+ && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))+ {+ return None;+ }+ let defs = crate::core::agent::subagent::project_subagents_dir(&root);+ std::fs::create_dir_all(&defs).unwrap();+ std::fs::write(+ defs.join("writer.toml"),+ "name = \"writer\"\ndescription = \"edits\"\nsystem_prompt = \"You are writer.\"\n",+ )+ .unwrap();++ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let (second_tx, second_rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let parent_turns = AtomicUsize::new(0);+ // Held, never answered, so neither side's request returns.+ let mut parked = Vec::new();+ for connection in listener.incoming() {+ let Ok(mut stream) = connection else { break };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut length = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ length = n.trim().parse().unwrap_or(0);+ }+ }+ let mut body = vec![0; length];+ let _ = reader.read_exact(&mut body);+ if String::from_utf8_lossy(&body).contains("You are writer.") {+ parked.push(stream);+ continue;+ }+ if parent_turns.fetch_add(1, Ordering::SeqCst) == 0 {+ let dispatch = json!({ "subagents": [{ "agent": "writer", "task": "edit a.txt" }] })+ .to_string();+ let chunk = json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",+ "choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[+ {"index":0,"id":"c1","type":"function","function":{"name":"dispatch_subagent","arguments":dispatch}}]},+ "finish_reason":null}]});+ let done = json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",+ "choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]});+ let answer = format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n");+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len());+ continue;+ }+ let _ = second_tx.send(());+ match second {+ SecondTurn::Fails => {+ let body = "{\"error\":{\"message\":\"bad request\"}}";+ let _ = write!(stream, "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());+ }+ SecondTurn::Hangs => parked.push(stream),+ }+ }+ });++ let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ args.sandbox = Some(false);+ args.project_memory = false;+ args.provider_configs = Arc::new(Mutex::new(HashMap::from([(+ "stub".to_string(),+ ProviderConfig {+ provider: "stub".into(),+ base_url: Some(format!("http://{addr}/v1")),+ api_key: Some("k".into()),+ models: vec!["m".into()],+ ..Default::default()+ },+ )])));+ Some((root, args, second_rx))+ }++ /// The subagent checkouts still on disk for `root`'s project and the+ /// `jan/agent/*` branches still in its repository.+ #[cfg(feature = "cli")]+ fn leftover_worktrees(root: &std::path::Path) -> (Vec<String>, String) {+ let branches = std::process::Command::new("git")+ .arg("-C")+ .arg(root)+ .args(["branch", "--list", "jan/agent/*"])+ .output()+ .unwrap();+ let dir = crate::core::agent::child_workspace::project_worktrees_dir(root).unwrap();+ let checkouts = std::fs::read_dir(dir)+ .into_iter()+ .flatten()+ .filter_map(Result::ok)+ .filter(|e| e.file_name() != "cargo-target")+ .map(|e| e.path().display().to_string())+ .collect();+ (checkouts, String::from_utf8_lossy(&branches.stdout).trim().to_string())+ }++ /// A run that fails while a writer it dispatched is still working ends that+ /// writer before sweeping: the worktree holds nothing, so it and its branch+ /// go, and nothing claims it was kept for holding work.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_failed_run_sweeps_the_worktree_of_a_writer_it_was_still_running() {+ let Some((root, args, _second)) = run_with_a_stuck_writer(SecondTurn::Fails) else {+ return;+ };+ let (tx, mut rx) = mpsc::unbounded_channel();+ let body = json!({ "model": "m", "messages": [{ "role": "user", "content": "go" }] });+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(30),+ run_orchestration_streamed(&tx, &body, &args),+ )+ .await+ .expect("the run ends");+ assert!(result.is_err(), "{result:?}");+ drop(tx);++ let mut dispatched = false;+ while let Some(event) = rx.recv().await {+ match event {+ StreamEvent::ToolResult { content, .. } if content.contains("worktree") => {+ dispatched = true;+ }+ StreamEvent::Notice { text } => {+ assert!(!text.contains("kept"), "an empty worktree was reported kept: {text}");+ }+ _ => {}+ }+ }+ assert!(dispatched, "the writer was dispatched into a worktree");+ let (worktrees, branches) = leftover_worktrees(&root);+ assert!(worktrees.is_empty(), "{worktrees:?}");+ assert!(branches.is_empty(), "{branches}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A cancelled run never reaches its own end, so the sweep has to happen on+ /// the way down too: the writer is stopped and its empty worktree removed.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_cancelled_run_sweeps_the_worktree_of_a_writer_it_was_still_running() {+ let Some((root, args, second)) = run_with_a_stuck_writer(SecondTurn::Hangs) else {+ return;+ };+ let (tx, mut rx) = mpsc::unbounded_channel();+ let run = tokio::spawn(async move {+ let body = json!({ "model": "m", "messages": [{ "role": "user", "content": "go" }] });+ run_orchestration_streamed(&tx, &body, &args).await+ });+ let arrived = tokio::task::spawn_blocking(move || {+ second.recv_timeout(std::time::Duration::from_secs(30))+ })+ .await+ .unwrap();+ assert!(arrived.is_ok(), "the parent reached its second turn");+ let (worktrees, _) = leftover_worktrees(&root);+ assert_eq!(worktrees.len(), 1, "the writer is in its worktree: {worktrees:?}");++ run.abort();+ assert!(run.await.unwrap_err().is_cancelled());+ // The drop hands the sweep to the blocking pool, so it lands shortly+ // after the abort returns rather than inside it.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ while !leftover_worktrees(&root).0.is_empty() && std::time::Instant::now() < deadline {+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ while let Ok(event) = rx.try_recv() {+ if let StreamEvent::Notice { text } = event {+ assert!(!text.contains("kept"), "an empty worktree was reported kept: {text}");+ }+ }+ let (worktrees, branches) = leftover_worktrees(&root);+ assert!(worktrees.is_empty(), "{worktrees:?}");+ assert!(branches.is_empty(), "{branches}");+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 03bbc26f4..11300b772 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -8,6 +8,8 @@/// Completion pings for backgrounded `bash` commands.pub mod bg_shell;+/// Where each dispatched subagent works: its own worktree or a read-only root.+pub mod child_workspace;// Tauri IPC surface for the desktop agent; the CLI drives the loop directly.#[cfg(not(feature = "cli"))]pub mod commands;diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex b5c27b851..dcbecdf7e 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -772,6 +772,9 @@ pub struct SubagentRequest {/// Jan's own tidy subagent sets this. It is never read from a tool call, so/// neither the model nor a definition can ask for it.pub memory_access: bool,+ /// Where it works, when the dispatch said (see+ /// [`crate::core::agent::child_workspace`]); `None` takes the default.+ pub workspace: Option<crate::core::agent::child_workspace::WorkspaceRequest>,}/// A group of subagents that run concurrently. The next phase starts only once@@ -1091,6 +1094,10 @@ pub(crate) fn stop_subagent(}entry.abort.abort();entry.slot.release(bg);+ end_child_shells(&entry.run_id);+ // Under the lock the phase barrier reads `finished` under, so no next+ // phase can see this child done while its worktree is still held.+ entry.lease.release();let _ = entry.events.send(StreamEvent::SubagentEnd {run_id: entry.run_id.clone(),name: entry.name.clone(),@@ -1132,6 +1139,61 @@ struct BackgroundEntry {/// Parent messages this child has not picked up yet. Registry-owned so a/// child queued on the semaphore can be addressed before it starts.inbox: Arc<ChildInbox>,+ /// A writer's hold on its worktree, given up before the child is marked+ /// finished, by its task or by whoever stops it. See [`LeaseSlot`].+ lease: LeaseSlot,+}++/// End every shell the child `run_id` started and left running. Its run+/// registers them under its own id (see `CompositeToolInvoker::shell_owner`)+/// and runs each in a task of its own, which aborting the child does not+/// reach: they must be gone before the child gives its worktree up, or they+/// keep writing into a checkout the next writer or the sweep now owns.+fn end_child_shells(run_id: &str) {+ tauri_plugin_agent_tools::tools::proc::kill_thread(run_id);+}++/// A writer's answer with the line naming its branch, which this first brings+/// into the user's repository (git, so on the blocking pool) for the parent to+/// merge; a failed run's branch is left to the session's sweep. A reader's+/// answer is returned as it is.+async fn with_branch_footer(+ ws: crate::core::agent::child_workspace::ChildWorkspace,+ result: Result<String, SubagentError>,+) -> Result<String, SubagentError> {+ let Ok(answer) = result else { return result };+ let footer = tokio::task::spawn_blocking(move || {+ let problem = ws.bring_back();+ ws.answer_footer(problem.as_deref())+ })+ .await+ .ok()+ .flatten();+ Ok(match footer {+ Some(footer) => format!("{answer}\n\n{footer}"),+ None => answer,+ })+}++/// A writer child's [`WriterLease`](crate::core::agent::child_workspace::WriterLease),+/// shared by its task and its registry entry so either can give it up. The+/// task's own drop is too late: an aborted task is dropped whenever the+/// runtime gets to it, and by then a phase barrier may already have read the+/// child as finished and dispatched the next writer into the same worktree.+#[derive(Clone, Default)]+struct LeaseSlot(+ Arc<std::sync::Mutex<Option<crate::core::agent::child_workspace::WriterLease>>>,+);++impl LeaseSlot {+ fn new(lease: Option<crate::core::agent::child_workspace::WriterLease>) -> Self {+ Self(Arc::new(std::sync::Mutex::new(lease)))+ }++ /// Give the worktree up now (a no-op once done, or for a reader).+ fn release(&self) {+ drop(self.0.lock().unwrap().take());+ }}/// A finished child the parent has not been told about yet: the `<SYSTEM>` ping@@ -1204,6 +1266,10 @@ pub(crate) struct BackgroundSubagents {session_events: std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>>,>,+ /// Where each child of this registry works, kept for the registry's life+ /// so a later dispatch can name an earlier child's workspace, and swept+ /// when the session ends.+ pub(crate) workspaces: Arc<crate::core::agent::child_workspace::Ledger>,}/// Default cap on concurrently *running* subagents per parent run when@@ -1269,6 +1335,7 @@ impl BackgroundSubagents {plans_pending: std::sync::atomic::AtomicUsize::new(0),generation: std::sync::atomic::AtomicU64::new(0),session_events: std::sync::Mutex::new(None),+ workspaces: Arc::default(),}}@@ -1446,6 +1513,8 @@ impl BackgroundSubagents {let mut guard = self.inner.lock().unwrap();for (_, entry) in guard.drain() {entry.abort.abort();+ end_child_shells(&entry.run_id);+ entry.lease.release();// Release the counters here rather than leaving it to the aborted// tasks: a cancelled run must owe nothing the moment its teardown// returns, and a session-owned registry outlives this call. Exactly@@ -1491,6 +1560,8 @@ impl BackgroundSubagents {return false;};entry.abort.abort();+ end_child_shells(&entry.run_id);+ entry.lease.release();// Exactly once, whether the child finished or is cut off here: see// `ChildSlot::release`.entry.slot.release(self);@@ -1682,12 +1753,86 @@ impl Drop for SlotGuard {}/// RAII guard tying background children to the parent run's lifetime: dropping it-/// (on normal return or when the parent future is cancelled) aborts every child.-pub(crate) struct AbortOnDrop(pub Arc<BackgroundSubagents>);+/// (on normal return or when the parent future is cancelled) aborts every child,+/// then, in the CLI, ends the registry's workspace session: the worktrees that+/// hold nothing are removed and the rest are named on the run's events.+///+/// Abort first: a writer still running holds its worktree, and a sweep before+/// it was stopped would keep that worktree (and report it as holding work)+/// just before the abort left it empty for good.+///+/// The sweep runs git per worktree, so it never runs on an async worker: a+/// run ending normally awaits it on the blocking pool ([`Self::finish`]), and+/// a drop hands it to that pool and returns.+pub(crate) struct AbortOnDrop {+ bg: Arc<BackgroundSubagents>,+ #[cfg(feature = "cli")]+ events: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ /// Cleared by [`Self::finish`], which has already torn down.+ armed: bool,+}++impl AbortOnDrop {+ pub(crate) fn new(+ bg: Arc<BackgroundSubagents>,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) -> Self {+ // The desktop has no subagent worktrees, so nothing is ever reported.+ #[cfg(not(feature = "cli"))]+ let _ = events;+ Self {+ bg,+ #[cfg(feature = "cli")]+ events: events.clone(),+ armed: true,+ }+ }++ /// Tear down now and wait for the sweep, so its kept notice lands before+ /// whatever the caller sends next. The run's normal end; a cancelled run+ /// only ever reaches the drop.+ pub(crate) async fn finish(mut self) {+ self.armed = false;+ self.bg.abort_all();+ #[cfg(feature = "cli")]+ {+ let _ = tokio::task::spawn_blocking(self.sweep()).await;+ }+ }++ /// End the registry's workspace session and name what it kept.+ #[cfg(feature = "cli")]+ fn sweep(&self) -> impl FnOnce() + Send + 'static {+ let workspaces = self.bg.workspaces.clone();+ let events = self.events.clone();+ move || {+ let kept = workspaces.finish_session();+ if !kept.is_empty() {+ let _ = events.send(crate::core::agent::events::StreamEvent::Notice {+ text: crate::core::agent::child_workspace::kept_notice(&kept),+ });+ }+ }+ }+}impl Drop for AbortOnDrop {fn drop(&mut self) {- self.0.abort_all();+ if !self.armed {+ return;+ }+ self.bg.abort_all();+ #[cfg(feature = "cli")]+ {+ // A drop cannot wait: on a runtime the sweep goes to the blocking+ // pool rather than stalling the worker this drop is on, and off+ // one (a plain thread) inline is all there is.+ let sweep = self.sweep();+ match tokio::runtime::Handle::try_current() {+ Ok(rt) => drop(rt.spawn_blocking(sweep)),+ Err(_) => sweep(),+ }+ }}}@@ -1921,12 +2066,22 @@ async fn run_subagent(parent_link: ParentLink,transcript_dir: Option<PathBuf>,memory_access: bool,+ placed: Option<(+ crate::core::agent::child_workspace::ChildWorkspace,+ crate::core::agent::child_workspace::Placement,+ )>,) -> Result<String, SubagentError> {use crate::core::agent::events::StreamEvent;use crate::core::agent::r#loop::run_orchestration_steered;let name = resolved.definition.name.clone();let mut child_args = without_memory(parent_args, memory_access);+ // Where it works: its own worktree, or the parent's checkout read-only.+ // The git behind it was read at dispatch, on the blocking pool.+ let workspace = placed.map(|(ws, placement)| {+ crate::core::agent::child_workspace::apply(&mut child_args, &ws, placement);+ ws+ });child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());// The host wrote its prompt for the conversation it drives, not for a// delegate with a task of its own; left in place it would also replace the@@ -1988,6 +2143,7 @@ async fn run_subagent(run_id: run_id.clone(),name: name.clone(),task: Some(description.clone()),+ workspace: workspace.as_ref().map(|ws| ws.label()),});let (child_tx, mut child_rx) = tokio::sync::mpsc::unbounded_channel::<StreamEvent>();@@ -2093,7 +2249,7 @@ pub(crate) fn without_memory(/// once -- when the plan's last phase finishes (see [`run_phase_plan`]). Silence/// suppresses only the `<SYSTEM>` ping; the child still fills its blackboard/// file, decrements the running count, and wakes the phase driver's barrier.-pub(crate) fn spawn_subagent(+pub(crate) async fn spawn_subagent(scope: &DispatchScope,parent_args: &crate::core::agent::r#loop::OrchestrationArgs,req: SubagentRequest,@@ -2102,6 +2258,34 @@ pub(crate) fn spawn_subagent(scratch: Option<&Path>,notify_on_finish: bool,) -> Result<Dispatched, SubagentError> {+ let prepared = prepare_dispatch(scope, parent_args, req, parent).await?;+ start_dispatch(scope, parent_args, prepared, events, scratch, notify_on_finish)+}++/// A dispatch resolved and given its workspace, not yet registered. Dropping+/// it gives a writer's worktree back.+struct PreparedDispatch {+ name: String,+ description: String,+ resolved: ResolvedDispatch,+ /// The dispatching run's inheritance, re-priced for the child's model.+ parent: ParentRun,+ /// See [`SubagentRequest::memory_access`].+ memory_access: bool,+ workspace: crate::core::agent::child_workspace::ChildWorkspace,+ /// What the child's args take from `workspace`, read from git with it.+ placement: crate::core::agent::child_workspace::Placement,+ lease: LeaseSlot,+}++/// The half of [`spawn_subagent`] that can fail on the request: resolve it,+/// price it, and assign the child its workspace.+async fn prepare_dispatch(+ scope: &DispatchScope,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ req: SubagentRequest,+ parent: &ParentRun,+) -> Result<PreparedDispatch, SubagentError> {if !parent_args.subagents_enabled {return Err(SubagentError::PermissionDenied("subagents cannot dispatch nested subagents".to_string(),@@ -2132,19 +2316,88 @@ pub(crate) fn spawn_subagent()?,..resolved};- launch(scope, parent_args, resolved, req, parent, events, scratch, notify_on_finish)+ assign_dispatch(scope, parent_args, resolved, req, parent).await}-/// Start an already-resolved child on a background task: the half of-/// [`spawn_subagent`] after its definition and tools are settled, shared with-/// Jan's internal subagents, which are not in the registry.-#[allow(clippy::too_many_arguments)]-fn launch(+/// Give an already-resolved child its workspace: the part of+/// [`prepare_dispatch`] after its definition and tools are settled, shared+/// with Jan's internal subagents, which are not in the registry.+async fn assign_dispatch(scope: &DispatchScope,parent_args: &crate::core::agent::r#loop::OrchestrationArgs,resolved: ResolvedDispatch,req: SubagentRequest,parent: &ParentRun,+) -> Result<PreparedDispatch, SubagentError> {+ let project_root = parent_args+ .project_root+ .as_ref()+ .ok_or_else(|| SubagentError::Upstream("subagents require an active project".to_string()))?;+ let name = resolved.definition.name.clone();+ // A run already torn down has swept its worktrees and will not sweep+ // again, so a worktree made for it now would leak. Checked again under the+ // registry lock below, where a teardown racing this dispatch is caught.+ if scope.is_stale() {+ return Err(SubagentError::Cancelled);+ }+ // Assigned now, before the child can queue: the dispatch result names it,+ // and a second writer onto a busy worktree is refused here.+ let writer = crate::core::agent::child_workspace::is_writer(+ resolved.allowed_tools.as_deref(),+ &parent_args.permissions,+ );+ // On the blocking pool: assigning runs `git clone`, `git status` and for+ // a ref possibly a network fetch, and placing the child reads its branch,+ // which would otherwise stall every other task on this runtime worker+ // until git returns.+ let scratch = parent_args+ .session_id+ .as_deref()+ .map(tauri_plugin_agent_tools::workspace::scratch_dir);+ let (workspace, placement, lease) = {+ let scope = scope.clone();+ let root = project_root.clone();+ let name = name.clone();+ let request = req.workspace.clone();+ tokio::task::spawn_blocking(move || {+ let (ws, lease) = scope+ .bg+ .workspaces+ .assign(&root, &name, writer, request.as_ref())+ .map_err(SubagentError::Upstream)?;+ // Checked here too, not only under the registry lock: a run+ // cancelled while git worked drops this dispatch's future, and+ // then nothing would take the worktree back.+ if scope.is_stale() {+ drop(lease);+ scope.bg.workspaces.undo(&name, &ws);+ return Err(SubagentError::Cancelled);+ }+ let placement =+ crate::core::agent::child_workspace::place(&ws, &root, scratch.as_deref());+ Ok((ws, placement, lease))+ })+ .await+ .map_err(|e| SubagentError::Upstream(format!("assigning a workspace failed: {e}")))??+ };+ Ok(PreparedDispatch {+ name,+ description: req.description,+ resolved,+ parent: parent.clone(),+ memory_access: req.memory_access,+ workspace,+ placement,+ lease: LeaseSlot::new(lease),+ })+}++/// The half of [`spawn_subagent`] that registers the prepared child and+/// starts its task, or refuses it when its run was torn down meanwhile.+fn start_dispatch(+ scope: &DispatchScope,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ prepared: PreparedDispatch,events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,scratch: Option<&Path>,notify_on_finish: bool,@@ -2153,7 +2406,19 @@ fn launch(use std::sync::atomic::Ordering;let bg = &scope.bg;- let name = resolved.definition.name.clone();+ let PreparedDispatch {+ name,+ description,+ resolved,+ parent,+ memory_access,+ workspace,+ placement,+ lease,+ } = prepared;+ let workspace_note = workspace.note();+ let ws_done = workspace.clone();+ let task_lease = lease.clone();let run_id = next_subagent_run_id(&name);let (tx, rx) = tokio::sync::oneshot::channel();let result_file = scratch.and_then(|s| {@@ -2168,6 +2433,22 @@ fn launch(// a child reports its progress through `notices`.let mut entries = bg.inner.lock().unwrap();if scope.is_stale() {+ drop(entries);+ // Torn down between the check above and here: give the worktree back+ // and take back this assignment, since the teardown's own sweep may+ // already have run. Only this one: a session-owned registry outlives+ // the teardown (Esc stops its children mid-session), and its earlier+ // children's worktrees and names are still the session's to reuse.+ lease.release();+ // `undo` runs git, so it goes to the blocking pool rather than+ // stalling this async worker. Nothing waits on it: the dispatch is+ // refused either way.+ let ledger = bg.workspaces.clone();+ let undo = move || ledger.undo(&name, &workspace);+ match tokio::runtime::Handle::try_current() {+ Ok(handle) => drop(handle.spawn_blocking(undo)),+ Err(_) => undo(),+ }return Err(SubagentError::Cancelled);}@@ -2187,7 +2468,7 @@ fn launch(let _ = events.send(StreamEvent::SubagentQueued {run_id: run_id.clone(),name: name.clone(),- task: Some(req.description.clone()),+ task: Some(description.clone()),waiting,});}@@ -2197,9 +2478,7 @@ fn launch(// child outliving this run keeps reporting somewhere that is still read.let task_events = bg.child_events(events);let entry_events = bg.child_events(events);- let inherited = parent.clone();- let description = req.description.clone();- let memory_access = req.memory_access;+ let inherited = parent;let run_id_task = run_id.clone();let name_task = name.clone();let registry = bg.clone();@@ -2264,8 +2543,17 @@ fn launch(parent_link,transcript_dir,memory_access,+ Some((workspace, placement)),).await;+ // Before `finished` below: a next phase may reuse this worktree as+ // soon as the barrier sees the child done. A shell the run abandoned+ // at its park budget would still be writing in it.+ end_child_shells(&run_id_task);+ // Still holding the lease, with no shell of the child's left: nothing+ // writes the checkout while its branch is read.+ let result = with_branch_footer(ws_done, result).await;+ task_lease.release();if let Some((_, path)) = &result_file {fill_subagent_result(path, &spilled_text(&result));}@@ -2304,10 +2592,14 @@ fn launch(finished,slot,inbox,+ lease,},);drop(entries);- Ok(Dispatched { run_id })+ Ok(Dispatched {+ run_id,+ workspace: workspace_note,+ })}/// The name Jan's memory-tidy subagent runs under. Not a registry entry: the@@ -2353,7 +2645,7 @@ Finish with a short report, one line per change: `archived <name>`, `merged <a>/// caller collects it with [`await_subagent`]. It never rings the parent's/// doorbell, so a tidy never starts a model turn of its own.#[cfg(feature = "cli")]-pub(crate) fn spawn_memory_tidy(+pub(crate) async fn spawn_memory_tidy(scope: &DispatchScope,parent_args: &crate::core::agent::r#loop::OrchestrationArgs,parent: &ParentRun,@@ -2369,7 +2661,8 @@ pub(crate) fn spawn_memory_tidy(..parent.clone()};let args = memory_tidy_args(parent_args, budget);- launch(scope, &args, resolved, req, parent, events, None, false)+ let prepared = assign_dispatch(scope, &args, resolved, req, parent).await?;+ start_dispatch(scope, &args, prepared, events, None, false)}/// The tidy child's run args: the parent's, with the change cap its `memory`@@ -2412,6 +2705,9 @@ fn memory_tidy_dispatch() -> (ResolvedDispatch, SubagentRequest) {allowed_tools: None,agent: MEMORY_TIDY_AGENT.to_string(),memory_access: true,+ // Never a worktree: with no write or edit tool the tidy is a reader,+ // so it gets the default, the parent's checkout read-only.+ workspace: None,};(resolved, req)}@@ -2463,6 +2759,8 @@ pub(crate) fn worker_names_in(result: &str) -> Option<Vec<String>> {pub(crate) struct DispatchedChild {pub(crate) name: String,pub(crate) run_id: String,+ /// Where it works (see [`Dispatched::workspace`]).+ pub(crate) workspace: String,}/// `<scratch>/blackboard`.@@ -2536,7 +2834,7 @@ fn inject_inputs(task: &str, inputs: &[(String, String)]) -> String {/// each completes, handing every phase its predecessor's blackboard results./// Returns as soon as phase 1 is dispatched. The whole plan is validated up front/// so a bad subagent fails the dispatch atomically, before any child starts.-pub(crate) fn spawn_dispatch_plan(+pub(crate) async fn spawn_dispatch_plan(bg: &Arc<BackgroundSubagents>,generation: u64,parent_args: &crate::core::agent::r#loop::OrchestrationArgs,@@ -2618,7 +2916,8 @@ pub(crate) fn spawn_dispatch_plan(children: first_children,} = spawn_first_phase(bg, multi, first.subagents, |req| {spawn_subagent(&scope, parent_args, req, parent, events, scratch, !multi)- })?;+ })+ .await?;if multi {let remaining: Vec<Phase> = phases.collect();@@ -2675,12 +2974,15 @@ struct FirstPhase {/// owes nothing the moment it reports its failure. `spawn` is a parameter so a/// test can make a later child fail, which no request that passed the up-front/// checks otherwise does on demand.-fn spawn_first_phase(+async fn spawn_first_phase<F>(bg: &BackgroundSubagents,multi: bool,reqs: Vec<SubagentRequest>,- mut spawn: impl FnMut(SubagentRequest) -> Result<Dispatched, SubagentError>,-) -> Result<FirstPhase, SubagentError> {+ mut spawn: impl FnMut(SubagentRequest) -> F,+) -> Result<FirstPhase, SubagentError>+where+ F: std::future::Future<Output = Result<Dispatched, SubagentError>>,+{let mut started = FirstPhase {names: Vec::with_capacity(reqs.len()),ids: Vec::with_capacity(reqs.len()),@@ -2689,11 +2991,12 @@ fn spawn_first_phase(for req in reqs {let name = req.name.clone();started.names.push(name.clone());- match spawn(req) {+ match spawn(req).await {Ok(d) => {started.children.push(DispatchedChild {name,run_id: d.run_id.clone(),+ workspace: d.workspace,});started.ids.push(d.run_id);}@@ -2773,7 +3076,9 @@ async fn run_phase_plan(&events,scratch.as_deref(),false,- ) {+ )+ .await+ {Ok(d) => {ids.push(d.run_id);names.push(name);@@ -2909,6 +3214,9 @@ fn completion_notice(/// file is the child's blackboard entry, reported by the plan as a whole.pub(crate) struct Dispatched {pub(crate) run_id: String,+ /// Where it works, as the dispatch result says (see+ /// [`crate::core::agent::child_workspace::ChildWorkspace::note`]).+ pub(crate) workspace: String,}/// Block until the background subagent `run_id` finishes and return its final@@ -3166,7 +3474,7 @@ pub fn subagent_tool_schemas(let dispatch_desc = format!("Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} Every subagent gets your full toolset unless its agent's definition or allowed_tools restricts it, except memory: subagents have no memory tool and no memory index, so put any remembered fact a subagent needs into its task.");- vec![+ let mut tools = vec![json!({"type": "function","function": {@@ -3245,7 +3553,24 @@ pub fn subagent_tool_schemas("parameters": { "type": "object", "properties": {}, "required": [] }}}),- ]+ ];+ // Only the CLI build gives a child a worktree or a read-only checkout, so+ // only there is the field offered (and read: see `parse_dispatch_plan`).+ if cfg!(feature = "cli") {+ tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]["properties"]+ ["workspace"] = json!({+ "description": "Optional; where the subagent works. OMIT for the default: one that can write or edit gets a fresh worktree (a clone of its own) on its own branch, any other works read-only in your checkout. \"new\": a fresh worktree. \"shared\": your checkout. The name of an earlier subagent: that subagent's workspace (one writer at a time). {\"ref\": \"<git ref>\"}: a fresh worktree at that ref, fetched if needed (e.g. pull/123/head).",+ "anyOf": [+ { "type": "string" },+ {+ "type": "object",+ "properties": { "ref": { "type": "string" } },+ "required": ["ref"]+ }+ ]+ });+ }+ tools}fn required_str(args: &serde_json::Value, key: &str) -> Result<String, SubagentError> {@@ -3318,6 +3643,14 @@ pub fn parse_dispatch_plan(let names = number_workers(agents.iter().map(String::as_str), taken);for ((sub, agent), name) in subs_val.iter().zip(agents).zip(names.iter().cloned()) {let description = required_str(sub, "task")?;+ // The desktop schema has no `workspace`, so one sent there is ignored+ // like any other unknown field: every child shares the checkout anyway.+ let workspace = if cfg!(feature = "cli") {+ crate::core::agent::child_workspace::parse_request(sub.get("workspace"))+ .map_err(|e| SubagentError::Upstream(format!("subagent '{name}': {e}")))?+ } else {+ None+ };let phase = match sub.get("phase") {None | Some(serde_json::Value::Null) => 0,Some(v) => v@@ -3336,6 +3669,7 @@ pub fn parse_dispatch_plan(allowed_tools: optional_tool_list(sub),agent,memory_access: false,+ workspace,});}let phases = by_phase@@ -4041,6 +4375,7 @@ pub(crate) mod tests {allowed_tools: allowed,agent: name.to_string(),memory_access: false,+ workspace: None,}}@@ -4544,6 +4879,7 @@ pub(crate) mod tests {finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),slot: ChildSlot::new(),inbox: Arc::new(ChildInbox::default()),+ lease: LeaseSlot::default(),}}@@ -4579,7 +4915,7 @@ pub(crate) mod tests {"r1".to_string(),test_entry(rx, handle.abort_handle(), ev_tx),);- let guard = AbortOnDrop(bg.clone());+ let guard = AbortOnDrop::new(bg.clone(), &tokio::sync::mpsc::unbounded_channel().0);drop(guard);assert!(bg.inner.lock().unwrap().is_empty(), "abort_all drains the map");assert!(handle.await.unwrap_err().is_cancelled(), "child was aborted");@@ -4673,7 +5009,8 @@ pub(crate) mod tests {"entry must remain registered while being awaited");- AbortOnDrop(bg.clone()); // constructs + drops -> abort_all+ // constructs + drops -> abort_all+ AbortOnDrop::new(bg.clone(), &tokio::sync::mpsc::unbounded_channel().0);assert!(handle.await.unwrap_err().is_cancelled(), "child was aborted");assert!(matches!(awaiting.await.unwrap(), Err(SubagentError::Cancelled)),@@ -4844,6 +5181,7 @@ pub(crate) mod tests {compaction: None,session_start: None,memory_change_budget: None,+ child_scope: None,}}@@ -4909,6 +5247,7 @@ pub(crate) mod tests {Some(&scratch),true,)+ .await.unwrap().run_id;let _ = await_subagent(&bg, &run_id).await;@@ -4941,7 +5280,7 @@ pub(crate) mod tests {let args = max_par_args(&root);let bg = Arc::new(BackgroundSubagents::new(1));let (events_tx, _rx) = tokio::sync::mpsc::unbounded_channel();- let run_id = dispatch_reviewer(&bg, &args, &events_tx);+ let run_id = dispatch_reviewer(&bg, &args, &events_tx).await;let _ = await_subagent(&bg, &run_id).await;assert!(!root.join("subagents").exists());let _ = std::fs::remove_dir_all(&root);@@ -4972,12 +5311,13 @@ pub(crate) mod tests {/// One queue-test dispatch, with no scratch: these assert admission order,/// not spilling, and a child that fails fast has nothing to write anyway.#[cfg(feature = "cli")]- fn dispatch_reviewer(+ async fn dispatch_reviewer(bg: &Arc<BackgroundSubagents>,args: &crate::core::agent::r#loop::OrchestrationArgs,events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,) -> String {spawn_subagent(&bg.scope(), args, req("reviewer", None), &parent_run(), events, None, true)+ .await.unwrap().run_id}@@ -4997,7 +5337,7 @@ pub(crate) mod tests {let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();// Hold the only permit so the next dispatch is guaranteed to queue.let held = bg.semaphore.clone().try_acquire_owned().unwrap();- let queued_id = dispatch_reviewer(&bg, &args, &events_tx);+ let queued_id = dispatch_reviewer(&bg, &args, &events_tx).await;let reply = message_subagent(&bg, &queued_id, "narrow it to the parser").unwrap();assert!(reply.contains("Queued for subagent"), "{reply}");@@ -5022,6 +5362,273 @@ pub(crate) mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A dispatch that resolves after its run was torn down (a later plan+ /// phase, an in-flight tool call) is refused without leaving a worktree or+ /// `jan/agent/*` branch behind: nothing would sweep it again.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_dispatch_after_teardown_leaves_no_worktree_behind() {+ let root = unique_root("stale-wt");+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ };+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"])+ && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))+ {+ return;+ }+ write_def(&project_subagents_dir(&root), "writer", "");+ let args = max_par_args(&root);+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();+ // The scope is taken, then the run is torn down before it dispatches.+ let scope = bg.scope();+ bg.abort_all();+ let refused = spawn_subagent(+ &scope,+ &args,+ req("writer", None),+ &parent_run(),+ &events_tx,+ None,+ false,+ )+ .await;+ assert!(matches!(refused, Err(SubagentError::Cancelled)));+ assert!(bg.workspaces.live().is_empty(), "{:?}", bg.workspaces.live());+ let branches = std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(["branch", "--list", "jan/agent/*"])+ .output()+ .unwrap();+ assert!(branches.stdout.is_empty(), "{}", String::from_utf8_lossy(&branches.stdout));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A dispatch's git work (here a `{ref}` fetch from a remote that takes a+ /// second to fail) runs off the async worker: on a single-threaded+ /// runtime, another task keeps running while it waits.+ #[cfg(feature = "cli")]+ #[tokio::test(flavor = "current_thread")]+ async fn a_dispatch_waiting_on_git_does_not_stall_the_runtime() {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ let root = unique_root("no-stall");+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ };+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"])+ && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"])+ && git(&["config", "protocol.ext.allow", "always"])+ && git(&["remote", "add", "origin", "ext::sh -c sleep% 1"]))+ {+ return;+ }+ write_def(&project_subagents_dir(&root), "writer", "");+ let args = max_par_args(&root);+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();+ let ticks = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let ticker = {+ let ticks = ticks.clone();+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ ticks.fetch_add(1, Ordering::SeqCst);+ }+ })+ };+ let request = SubagentRequest {+ workspace: Some(WorkspaceRequest::Ref("pull/1/head".to_string())),+ ..req("writer", None)+ };+ let before = ticks.load(Ordering::SeqCst);+ let refused =+ spawn_subagent(&bg.scope(), &args, request, &parent_run(), &events_tx, None, false)+ .await;+ let during = ticks.load(Ordering::SeqCst) - before;+ ticker.abort();+ assert!(+ matches!(&refused, Err(SubagentError::Upstream(e)) if e.contains("fetch")),+ "{:?}",+ refused.err()+ );+ assert!(during >= 20, "the runtime stalled while git ran: {during} tick(s)");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A teardown landing between a dispatch's workspace assignment and its+ /// registration takes back that dispatch's worktree and nothing else. A+ /// session-owned registry outlives the teardown (Esc stops its children+ /// mid-session), so an earlier reader's fresh worktree, which holds no+ /// lease, and an earlier writer's stay on disk and nameable.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_stale_dispatch_takes_back_only_its_own_worktree() {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ let root = unique_root("stale-own");+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ };+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"])+ && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))+ {+ return;+ }+ write_def(&project_subagents_dir(&root), "writer", "");+ write_def(&project_subagents_dir(&root), "reader", "allowed_tools = [\"read\"]\n");+ let args = max_par_args(&root);+ let bg = Arc::new(BackgroundSubagents::new(2));+ let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();+ bg.install_session_events(events_tx.clone());+ let earlier = [+ SubagentRequest {+ workspace: Some(WorkspaceRequest::New),+ ..req("reader", None)+ },+ req("writer", None),+ ];+ for r in earlier {+ let d = spawn_subagent(&bg.scope(), &args, r, &parent_run(), &events_tx, None, false)+ .await+ .unwrap();+ assert!(d.workspace.contains("worktree"), "{}", d.workspace);+ let _ = await_subagent(&bg, &d.run_id).await;+ }+ let before = bg.workspaces.live();+ assert_eq!(before.len(), 2, "{before:?}");++ let scope = bg.scope();+ // Its own worker name, as `plan_dispatch` would have reserved.+ let late = SubagentRequest {+ agent: "writer".to_string(),+ ..req("late", None)+ };+ let late = prepare_dispatch(&scope, &args, late, &parent_run()).await.unwrap();+ let late_wt = late.workspace.worktree.clone().expect("a writer gets a worktree");+ bg.abort_all(); // Esc: the session's registry lives on+ let refused = start_dispatch(&scope, &args, late, &events_tx, None, false);+ assert!(matches!(refused, Err(SubagentError::Cancelled)));++ // The undo runs on the blocking pool; give it a bounded moment.+ for _ in 0..300 {+ if !late_wt.path.exists() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ assert!(!late_wt.path.exists(), "the stale dispatch's worktree is removed");+ let branches = std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(["branch", "--list", "jan/agent/*"])+ .output()+ .unwrap();+ let branches = String::from_utf8_lossy(&branches.stdout).into_owned();+ assert!(!branches.contains(&late_wt.branch), "{branches}");+ assert_eq!(bg.workspaces.live(), before, "the earlier worktrees stay");+ for name in ["reader", "writer"] {+ let reuse = WorkspaceRequest::Reuse(name.to_string());+ let again = bg.workspaces.assign(&root, "next", false, Some(&reuse));+ assert!(again.is_ok(), "{name}: {:?}", again.err());+ }+ let _ = bg.workspaces.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A stopped writer gives its worktree up the moment the stop returns, not+ /// when the runtime gets round to dropping its aborted task: a phase+ /// barrier opens on `finished`, and a next-phase item reusing that+ /// worktree would otherwise be refused as "still writing" and fail the+ /// whole phase.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_stopped_writer_releases_its_worktree_before_the_stop_returns() {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ let root = unique_root("lease-stop");+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .arg("-C")+ .arg(&root)+ .args(args)+ .env("GIT_AUTHOR_NAME", "t")+ .env("GIT_AUTHOR_EMAIL", "t@t")+ .env("GIT_COMMITTER_NAME", "t")+ .env("GIT_COMMITTER_EMAIL", "t@t")+ .output()+ .is_ok_and(|o| o.status.success())+ };+ std::fs::write(root.join("a.txt"), "a\n").unwrap();+ if !(git(&["init", "-q"])+ && git(&["add", "a.txt"])+ && git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]))+ {+ return;+ }+ write_def(&project_subagents_dir(&root), "writer", "");+ let args = max_par_args(&root);+ let bg = Arc::new(BackgroundSubagents::new(1));+ let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();+ // Queued behind the only permit, so it is still holding its lease.+ let held = bg.semaphore.clone().try_acquire_owned().unwrap();+ let d = spawn_subagent(+ &bg.scope(),+ &args,+ req("writer", None),+ &parent_run(),+ &events_tx,+ None,+ false,+ )+ .await+ .unwrap();+ assert!(d.workspace.contains("worktree"), "{}", d.workspace);+ let reuse = WorkspaceRequest::Reuse("writer".to_string());+ let busy = bg.workspaces.assign(&root, "next", true, Some(&reuse)).unwrap_err();+ assert!(busy.contains("still writing"), "{busy}");++ stop_subagent(&bg, "writer").unwrap();+ let next = bg.workspaces.assign(&root, "next", true, Some(&reuse));+ assert!(next.is_ok(), "{:?}", next.err());+ drop(next);+ drop(held);+ let _ = bg.workspaces.finish_session();+ let _ = std::fs::remove_dir_all(&root);+ }+/// Provenance and authority: the message is data in the child's/// conversation, never a channel that grants it anything. The dispatch-time/// intersection stays the ceiling for the child's whole life.@@ -5033,7 +5640,7 @@ pub(crate) mod tests {let args = max_par_args(&root);let bg = Arc::new(BackgroundSubagents::new(1));let (events_tx, _events_rx) = tokio::sync::mpsc::unbounded_channel();- let run_id = dispatch_reviewer(&bg, &args, &events_tx);+ let run_id = dispatch_reviewer(&bg, &args, &events_tx).await;// Whatever the message says, delivery only ever appends a `user` turn:// there is no field on it for tools, permissions, sandbox, or model.@@ -5069,8 +5676,8 @@ pub(crate) mod tests {/// The scope boundary in the registry rather than the schema: a child never/// gets a subagent registry, so it has nothing to message a sibling through.#[cfg(feature = "cli")]- #[test]- fn a_child_cannot_dispatch_and_so_has_no_registry_to_message_through() {+ #[tokio::test]+ async fn a_child_cannot_dispatch_and_so_has_no_registry_to_message_through() {let root = unique_root("msg-nested");write_def(&project_subagents_dir(&root), "reviewer", "");let mut child_args = max_par_args(&root);@@ -5086,7 +5693,8 @@ pub(crate) mod tests {&events_tx,None,true- ),+ )+ .await,Err(SubagentError::PermissionDenied(_))));let _ = std::fs::remove_dir_all(&root);@@ -5157,13 +5765,17 @@ pub(crate) mod tests {let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();let mut starts = Vec::new();- let r1 = dispatch_reviewer(&bg, &args, &events_tx);- let r2 = dispatch_reviewer(&bg, &args, &events_tx);- let r3 = dispatch_reviewer(&bg, &args, &events_tx);+ // The only slot is taken by a child already running. Held here rather+ // than by a first dispatch: a dispatch yields while its workspace is+ // assigned, and a provider-less child would finish in that window.+ let running = bg.semaphore.clone().try_acquire_owned().unwrap();+ let r1 = dispatch_reviewer(&bg, &args, &events_tx).await;+ let r2 = dispatch_reviewer(&bg, &args, &events_tx).await;+ let r3 = dispatch_reviewer(&bg, &args, &events_tx).await;assert_ne!(r1, r2);assert_ne!(r2, r3);- // The two beyond-cap dispatches must be reported queued, with their+ // The beyond-cap dispatches must be reported queued, with their// 1-based queue positions in dispatch order.let mut queued = Vec::new();while let Ok(ev) = events_rx.try_recv() {@@ -5171,20 +5783,21 @@ pub(crate) mod tests {queued.push((run_id, waiting));}}- assert_eq!(queued.len(), 2, "two dispatches exceeded the cap of 1");- assert_eq!(queued[0], (r2.clone(), 1), "second dispatch queues first");- assert_eq!(queued[1], (r3.clone(), 2), "third dispatch queues behind it");+ assert_eq!(queued.len(), 3, "three dispatches exceeded the cap of 1");+ assert_eq!(queued[0], (r1.clone(), 1), "first dispatch queues first");+ assert_eq!(queued[1], (r2.clone(), 2), "second dispatch queues behind it");+ assert_eq!(queued[2], (r3.clone(), 3), "third dispatch queues behind that");- // The first dispatch is admitted immediately: it starts without a- // queued event (children fail fast without a provider, which is fine --- // we only assert the queueing/ordering contract here).+ // Children fail fast without a provider, which is fine -- we only+ // assert the queueing/ordering contract here.+ drop(running);let out1 = await_subagent(&bg, &r1).await;let out2 = await_subagent(&bg, &r2).await;let out3 = await_subagent(&bg, &r3).await;assert!(out1.is_err(), "child run fails without a provider (expected)");assert!(out2.is_err() && out3.is_err(), "queued children also complete");- // Promotion must be FIFO: r2 started before r3.+ // Promotion must be FIFO: r1, then r2, then r3.while let Ok(ev) = events_rx.try_recv() {if let StreamEvent::SubagentStart { run_id, .. } = ev {starts.push(run_id);@@ -5192,7 +5805,7 @@ pub(crate) mod tests {}let pos = |id: &str| starts.iter().position(|s| s == id);assert!(- pos(&r2).unwrap() < pos(&r3).unwrap(),+ pos(&r1).unwrap() < pos(&r2).unwrap() && pos(&r2).unwrap() < pos(&r3).unwrap(),"FIFO promotion: {starts:?}");let _ = std::fs::remove_dir_all(&root);@@ -5243,6 +5856,7 @@ pub(crate) mod tests {],};let d = spawn_dispatch_plan(&bg, bg.generation(), &args, plan, &parent_run(), &tx, Some(&scratch))+ .await.unwrap();assert_eq!(d.phase_count, 2);assert_eq!(d.total_subagents, 3);@@ -5328,6 +5942,7 @@ pub(crate) mod tests {&tx,Some(&scratch),)+ .await.unwrap();// Phase 1 started; the driver owns the remaining phase.assert_eq!(d.first_phase.len(), 1);@@ -5377,7 +5992,7 @@ pub(crate) mod tests {bg.abort_all();let dispatched =- spawn_subagent(&scope, &args, worker("late"), &parent_run(), &tx, None, true);+ spawn_subagent(&scope, &args, worker("late"), &parent_run(), &tx, None, true).await;assert!(matches!(dispatched, Err(SubagentError::Cancelled)),"a dispatch after teardown must be refused, not started"@@ -5424,7 +6039,7 @@ pub(crate) mod tests {let bg = Arc::new(BackgroundSubagents::new(1));let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();- let id = dispatch_reviewer(&bg, &args, &tx);+ let id = dispatch_reviewer(&bg, &args, &tx).await;// Wait for it to finish without collecting it, then collect it: the// entry stays either way, and both states are "done" to the barrier.let gate = tokio::time::timeout(@@ -5464,8 +6079,8 @@ pub(crate) mod tests {// Occupy the only slot, so the first dispatch parks on the semaphore// (queued) rather than being admitted -- both accounting fields in play.let running = bg.semaphore.clone().try_acquire_owned().unwrap();- let _r1 = dispatch_reviewer(&bg, &args, &tx);- let _r2 = dispatch_reviewer(&bg, &args, &tx);+ let _r1 = dispatch_reviewer(&bg, &args, &tx).await;+ let _r2 = dispatch_reviewer(&bg, &args, &tx).await;assert_eq!(bg.running.load(Ordering::SeqCst), 2);assert_eq!(bg.queued.load(Ordering::SeqCst), 2);// Admit the first, so the abort below has to release a running child and@@ -5509,7 +6124,7 @@ pub(crate) mod tests {let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();// A free permit: admitted here and now, never queued.- let _r1 = dispatch_reviewer(&bg, &args, &tx);+ let _r1 = dispatch_reviewer(&bg, &args, &tx).await;assert_eq!(bg.queued.load(Ordering::SeqCst), 0);bg.abort_all();@@ -5537,7 +6152,7 @@ pub(crate) mod tests {// Hold the slot so the child cannot finish on its own: the waiter must// park, deterministically, with exactly one child outstanding.let _running = bg.semaphore.clone().try_acquire_owned().unwrap();- let _r1 = dispatch_reviewer(&bg, &args, &tx);+ let _r1 = dispatch_reviewer(&bg, &args, &tx).await;let waiter_bg = bg.clone();let waiter = tokio::spawn(async move { waiter_bg.wait_for_notice().await });@@ -5593,6 +6208,7 @@ pub(crate) mod tests {&tx,Some(&scratch),)+ .await.unwrap();let mut all = Vec::new();@@ -5650,6 +6266,7 @@ pub(crate) mod tests {],};spawn_dispatch_plan(&bg, bg.generation(), &args, plan, &parent_run(), &tx, Some(&scratch))+ .await.unwrap();let mut all = Vec::new();@@ -5701,8 +6318,8 @@ pub(crate) mod tests {// Occupy the only slot BEFORE dispatching, so every dispatch queues and// the await below is deterministic: nothing can start while held.let _running = bg.semaphore.clone().try_acquire_owned().unwrap();- let r1 = dispatch_reviewer(&bg, &args, &events_tx);- let r2 = dispatch_reviewer(&bg, &args, &events_tx);+ let r1 = dispatch_reviewer(&bg, &args, &events_tx).await;+ let r2 = dispatch_reviewer(&bg, &args, &events_tx).await;// r2 is queued (not started), and awaiting it must NOT start it: the// slot is still held, so the await parks. Assert via the events: no@@ -5743,11 +6360,11 @@ pub(crate) mod tests {// Hold the slot before dispatching so r1, r2, r3 all queue (parked on// the semaphore) -- the interesting teardown case.let _running = bg.semaphore.clone().try_acquire_owned().unwrap();- let _r1 = dispatch_reviewer(&bg, &args, &events_tx);- let r2 = dispatch_reviewer(&bg, &args, &events_tx);- let r3 = dispatch_reviewer(&bg, &args, &events_tx);+ let _r1 = dispatch_reviewer(&bg, &args, &events_tx).await;+ let r2 = dispatch_reviewer(&bg, &args, &events_tx).await;+ let r3 = dispatch_reviewer(&bg, &args, &events_tx).await;- AbortOnDrop(bg.clone()); // teardown with queued children parked+ AbortOnDrop::new(bg.clone(), &events_tx); // teardown with queued children parkedlet mut ends = Vec::new();while let Ok(ev) = events_rx.try_recv() {@@ -5778,7 +6395,7 @@ pub(crate) mod tests {let bg = Arc::new(BackgroundSubagents::new(1));let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();// No provider is configured, so the child's run errors out at once.- let run_id = dispatch_reviewer(&bg, &args, &events_tx);+ let run_id = dispatch_reviewer(&bg, &args, &events_tx).await;tokio::time::timeout(std::time::Duration::from_secs(10), async {while !bg.live_run_ids().is_empty() {tokio::time::sleep(std::time::Duration::from_millis(5)).await;@@ -5830,6 +6447,7 @@ pub(crate) mod tests {None,false,)+ .await.expect("the child registers");assert_eq!(bg.running.load(Ordering::SeqCst), 1, "the child is owed");@@ -5878,25 +6496,32 @@ pub(crate) mod tests {// As `spawn_dispatch_plan` does for a multi-phase plan before phase 0.bg.begin_plan();- let mut started = Vec::new();+ let started = std::sync::Mutex::new(Vec::new());let result = spawn_first_phase(&bg,true,vec![req("reviewer", None), req("broken", None)],|r| {- if r.name == "broken" {- assert_eq!(- bg.running.load(Ordering::SeqCst),- 1,- "the good child is live when its sibling fails"- );- return Err(SubagentError::Upstream("cannot start".to_string()));+ let (bg, scope, args, events_tx, started) =+ (&bg, &scope, &args, &events_tx, &started);+ async move {+ if r.name == "broken" {+ assert_eq!(+ bg.running.load(Ordering::SeqCst),+ 1,+ "the good child is live when its sibling fails"+ );+ return Err(SubagentError::Upstream("cannot start".to_string()));+ }+ let d = spawn_subagent(scope, args, r, &parent_run(), events_tx, None, false)+ .await?;+ started.lock().unwrap().push(d.run_id.clone());+ Ok(d)}- let d = spawn_subagent(&scope, &args, r, &parent_run(), &events_tx, None, false)?;- started.push(d.run_id.clone());- Ok(d)},- );+ )+ .await;+ let started = started.into_inner().unwrap();assert!(matches!(result, Err(SubagentError::Upstream(ref m)) if m == "cannot start"),@@ -6131,6 +6756,75 @@ pub(crate) mod tests {);}+ /// The optional per-item `workspace` takes a keyword or an earlier+ /// worker's name as a string, or a `{ref}` object; it is never required,+ /// and the schema is the same bytes every time it is built.+ #[cfg(feature = "cli")]+ #[test]+ fn the_dispatch_schema_offers_an_optional_workspace() {+ let reg = SubagentRegistry::load(&unique_root("workspace_schema"));+ let schemas = subagent_tool_schemas(®, DEFAULT_MAX_PARALLEL_SUBAGENTS);+ let item = &schemas[0]["function"]["parameters"]["properties"]["subagents"]["items"];+ let ws = &item["properties"]["workspace"];+ let shapes = ws["anyOf"].as_array().expect("anyOf");+ assert_eq!(shapes[0]["type"], "string");+ assert_eq!(shapes[1]["type"], "object");+ assert_eq!(shapes[1]["required"], serde_json::json!(["ref"]));+ assert!(ws["description"].as_str().unwrap().contains("\"shared\""));+ assert_eq!(item["required"], serde_json::json!(["agent", "task"]));+ assert_eq!(+ schemas,+ subagent_tool_schemas(®, DEFAULT_MAX_PARALLEL_SUBAGENTS),+ "stable across turns"+ );+ }++ /// The desktop makes no worktrees, so it neither offers `workspace` nor+ /// acts on one: a model that sends it anyway (even a malformed one) gets+ /// the plain shared checkout rather than a failed plan.+ #[cfg(not(feature = "cli"))]+ #[test]+ fn the_desktop_dispatch_schema_has_no_workspace_and_ignores_one() {+ let reg = SubagentRegistry::load(&unique_root("workspace_schema_desktop"));+ let schemas = subagent_tool_schemas(®, DEFAULT_MAX_PARALLEL_SUBAGENTS);+ let item = &schemas[0]["function"]["parameters"]["properties"]["subagents"]["items"];+ assert!(item["properties"].get("workspace").is_none(), "{item}");+ assert!(!schemas[0].to_string().contains("worktree"), "{}", schemas[0]);+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({ "subagents": [+ { "agent": "general", "task": "a", "workspace": "new" },+ { "agent": "explore", "task": "b", "workspace": 7 },+ ]}))+ .unwrap();+ assert!(plan.phases[0].subagents.iter().all(|s| s.workspace.is_none()));+ }++ #[cfg(feature = "cli")]+ #[test]+ fn a_dispatch_item_carries_its_workspace_and_a_bad_one_fails_the_plan() {+ use crate::core::agent::child_workspace::WorkspaceRequest;+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({ "subagents": [+ { "agent": "general", "task": "a", "workspace": "new" },+ { "agent": "review", "task": "b", "workspace": { "ref": "pull/1/head" } },+ { "agent": "explore", "task": "c" },+ ]}))+ .unwrap();+ let ws: Vec<_> = plan.phases[0].subagents.iter().map(|s| s.workspace.clone()).collect();+ assert_eq!(+ ws,+ vec![+ Some(WorkspaceRequest::New),+ Some(WorkspaceRequest::Ref("pull/1/head".to_string())),+ None+ ]+ );+ let err = parse_dispatch_plan_fresh(&serde_json::json!({ "subagents": [+ { "agent": "general", "task": "a", "workspace": 7 },+ ]}))+ .unwrap_err()+ .to_string();+ assert!(err.contains("general") && err.contains("workspace"), "{err}");+ }+/// Every `allowed_tools` array is pinned to the names the run offers, minus/// the tools no child can get, plus the search tools a child may ask for.#[test]@@ -6539,6 +7233,7 @@ pub(crate) mod tests {finished: Arc::new(std::sync::atomic::AtomicBool::new(false)),slot: ChildSlot::new(),inbox: inbox.clone(),+ lease: LeaseSlot::default(),},inbox,)@@ -6792,6 +7487,37 @@ pub(crate) mod tests {assert!(handle.await.unwrap_err().is_cancelled(), "the task was aborted");}+ /// A child's shells run in tasks its abort does not reach, so stopping it+ /// must end them itself: a shell left writing after the worktree's lease+ /// is released races the next writer, or the sweep that removes it.+ #[cfg(unix)]+ #[tokio::test]+ async fn stopping_a_child_ends_the_shells_it_started() {+ use tauri_plugin_agent_tools::tools::proc;+ let bg = Arc::new(BackgroundSubagents::default());+ let run_id = format!("sub-shells-{}", std::process::id());+ let (entry, _inbox) = live_entry(&run_id, "shells");+ bg.inner.lock().unwrap().insert(run_id.clone(), entry);+ let child = proc::spawn(+ proc::shell(),+ "sleep 300",+ &std::env::temp_dir(),+ None,+ proc::ShellEnv::default(),+ Some(&run_id),+ )+ .await+ .unwrap();+ let pid = child.id().unwrap();+ // Held the way `bash` holds it: by a task of its own.+ let waiter = tokio::spawn(child.wait_with_output());++ stop_subagent(&bg, "shells").unwrap();+ let ended = tokio::time::timeout(std::time::Duration::from_secs(5), waiter).await;+ proc::kill(pid);+ assert!(ended.is_ok(), "the stopped child's shell is still running");+ }+/// The counters a child holds are released exactly once: stopping it and then/// tearing the session down must not drive `running` below zero.#[tokio::test]diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 75a90776f..4c361f97c 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1482,6 +1482,8 @@ fn build_cli_orchestration_args())),// Only Jan's memory tidy subagent has one.memory_change_budget: None,+ // A top-level run works in its own checkout as given.+ child_scope: None,}}@@ -3326,9 +3328,12 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: boo};eprintln!("\x1b[2m[{tag}] {content}\x1b[0m");}- StreamEvent::SubagentStart { name, .. } => {- eprintln!("\x1b[2m[subagent:{name}] started (background)\x1b[0m")- }+ StreamEvent::SubagentStart {+ name, workspace, ..+ } => match workspace {+ Some(ws) => eprintln!("\x1b[2m[subagent:{name}] started (background) in {ws}\x1b[0m"),+ None => eprintln!("\x1b[2m[subagent:{name}] started (background)\x1b[0m"),+ },StreamEvent::SubagentQueued { name, waiting, .. } => {eprintln!("\x1b[2m[subagent:{name}] queued ({waiting} waiting)\x1b[0m")}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex c28cabef4..890ce0bf8 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -4763,6 +4763,9 @@ struct App {/// loop (it sizes the tool segment, which takes the MCP server lock a turn/// may be holding). Taken once, like `mcp_job_request`.context_request: bool,+ /// Set by `/worktree` to ask the loop to gather its report off the render+ /// loop: it runs git per worktree. Taken once, like `context_request`.+ worktree_request: bool,/// The provider's execution id for the most recent request that reported/// one, so `/usage` can name something concrete to look up. `None` when no/// request has reported one -- which is the normal case on the default@@ -5208,6 +5211,9 @@ struct SubagentPanel {/// When the child's `SubagentStart` arrived, for the elapsed time beside/// it once the main turn has ended. `None` while it is queued or pending.started: Option<Instant>,+ /// Where the child works, from its `SubagentStart` (see+ /// `child_workspace::ChildWorkspace::label`). Shown in `/agents`.+ workspace: Option<String>,/// The child's run as rows, built from its own stream by the same code/// that builds the main transcript, for the `/agents` detail view and the/// finished summary row's expand. A child's stream never reaches the@@ -5258,6 +5264,7 @@ impl SubagentPanel {phase: None,parked: false,started: None,+ workspace: None,transcript: Transcript::for_child(INITIAL_THINK_TAGS),}}@@ -5615,6 +5622,7 @@ impl App {vibe_confirm: None,readout: None,context_request: false,+ worktree_request: false,last_execution_id: None,reported_usage_request: None,mcp_prompt: None,@@ -8387,7 +8395,12 @@ impl App {});}}- StreamEvent::SubagentStart { run_id, name, task } => {+ StreamEvent::SubagentStart {+ run_id,+ name,+ task,+ workspace,+ } => {// A child with no model of its own runs on the parent's, so it// starts on the parent's tag setting; its first request moves it// to its own provider's if that differs.@@ -8400,6 +8413,7 @@ impl App {panel.queued = false;panel.started = Some(Instant::now());panel.transcript.parse_think_tags = inherited;+ panel.workspace = workspace;} else if let Some(panel) = self.subagents.iter_mut()@@ -8410,6 +8424,7 @@ impl App {panel.queued = false;panel.started = Some(Instant::now());panel.transcript.parse_think_tags = inherited;+ panel.workspace = workspace;if let Some(t) = task {panel.task = t;}@@ -8419,6 +8434,7 @@ impl App {let mut panel = SubagentPanel::new(run_id, name, task.unwrap_or_default());panel.started = Some(Instant::now());panel.transcript.parse_think_tags = inherited;+ panel.workspace = workspace;self.subagents.push(panel);}}@@ -13504,6 +13520,20 @@ pub async fn run(if let Some(session) = session_scratch.as_deref() {let _ = workspace::remove_scratch_dir(session).await;}+ // And its subagents' worktrees that hold nothing; the rest are named on+ // the real terminal, since they are what is left to merge. Children still+ // running are stopped first: a live writer holds its worktree, which would+ // otherwise be kept as busy and outlive the process even when empty.+ // On the blocking pool, as every worktree sweep is: it runs git per+ // worktree, and a runtime worker is no place to wait on that.+ app.subagent_set.abort_all();+ let workspaces = app.subagent_set.workspaces.clone();+ let kept = tokio::task::spawn_blocking(move || workspaces.finish_session())+ .await+ .unwrap_or_default();+ if !kept.is_empty() {+ eprintln!("{}", crate::core::agent::child_workspace::kept_notice(&kept));+ }res}@@ -13687,6 +13717,9 @@ async fn chat_loop<B: Backend>(// executing an MCP tool call holds it for up to the tool-call timeout), so// it must never run on the render loop. One at a time.let mut context_task: Option<tokio::task::JoinHandle<ContextReport>> = None;+ // `/worktree` gathering its report: git per worktree, so on the blocking+ // pool. One at a time.+ let mut worktree_task: Option<tokio::task::JoinHandle<WorktreeReport>> = None;type ReportedUsageResult = (super::tokamak::usage::Query,Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,@@ -13847,6 +13880,10 @@ async fn chat_loop<B: Backend>(let snapshot = app.context_snapshot();context_task = Some(tokio::spawn(compute_context_report(snapshot)));}+ if worktree_task.is_none() && app.worktree_request {+ app.worktree_request = false;+ worktree_task = Some(spawn_worktree_report(app));+ }// `/usage <view>` asked for an account read. It is a network call, so// it runs off the render loop exactly like `/context`'s report: one at// a time, with the overlay sitting on its loading state until it lands.@@ -13963,7 +14000,7 @@ async fn chat_loop<B: Backend>(// the session is doing.if tidy_task.is_none() {if let Some(kind) = app.tidy_request.take() {- tidy_task = start_memory_tidy(app, kind, &session_events_tx);+ tidy_task = start_memory_tidy(app, kind, &session_events_tx).await;}}@@ -14190,6 +14227,9 @@ async fn chat_loop<B: Backend>(// landing after the overlay was closed must not reopen it.finish_context_report(app, report);}+ Some(report) = await_worktree_report(&mut worktree_task) => {+ finish_worktree_report(app, report);+ }Some((query, result)) = await_reported_usage(&mut reported_usage_task) => {finish_reported_usage(app, &query, result);}@@ -17561,7 +17601,7 @@ enum TidyKind {/// Start the requested tidy on the session's registry. Fire-and-forget from/// the caller's view: the result is collected off the render loop.-fn start_memory_tidy(+async fn start_memory_tidy(app: &mut App,kind: TidyKind,events: &mpsc::UnboundedSender<StreamEvent>,@@ -17592,7 +17632,8 @@ fn start_memory_tidy(&parent,events,budget.clone(),- );+ )+ .await;match dispatched {Ok(dispatched) => {app.tidy_running = Some(kind);@@ -20933,6 +20974,13 @@ fn agent_detail_header(row.extend(agent_activity(panel));}out.push(Line::from(row));+ if let Some(workspace) = &panel.workspace {+ out.extend(+ wrap_text(&format!("workspace {workspace}"), dim, max)+ .into_iter()+ .map(Line::from),+ );+ }if let Some(brief) = panel.task.lines().find(|l| !l.trim().is_empty()) {out.push(Line::from(""));out.extend(@@ -22361,8 +22409,56 @@ fn note_workspace_mismatch(app: &mut App, thread: &serde_json::Value) {////// Read-only on purpose. Getting the work out is the user's own git: this/// session must never write to the branch they left behind.+///+/// It runs git once per worktree, so this only raises a flag; the loop+/// gathers the report on the blocking pool and [`finish_worktree_report`]+/// shows it when it lands, keeping the frame live meanwhile.fn worktree_command(app: &mut App) {- let Some(workspace) = app.workspace.clone() else {+ app.worktree_request = true;+}++/// What `/worktree` shows, gathered off the render loop.+struct WorktreeReport {+ /// A line per live subagent worktree.+ children: Vec<String>,+ /// The session's own worktree and its changed paths, if it has one.+ workspace: Option<(Worktree, Vec<String>)>,+}++/// Gather `/worktree`'s report on the blocking pool.+fn spawn_worktree_report(app: &App) -> tokio::task::JoinHandle<WorktreeReport> {+ let ledger = app.subagent_set.workspaces.clone();+ let workspace = app.workspace.clone();+ tokio::task::spawn_blocking(move || WorktreeReport {+ children: ledger.live(),+ workspace: workspace.map(|ws| {+ let changed = git::changed_paths(&ws.path);+ (ws, changed)+ }),+ })+}++/// Await an in-flight `/worktree` report, parking forever when none is+/// running so this can sit in the loop's `select!` unconditionally.+async fn await_worktree_report(+ task: &mut Option<tokio::task::JoinHandle<WorktreeReport>>,+) -> Option<WorktreeReport> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ joined.ok()+}++fn finish_worktree_report(app: &mut App, report: WorktreeReport) {+ if !report.children.is_empty() {+ app.note("subagent worktrees:");+ for line in &report.children {+ app.system_detail_text(&format!(" {line}"));+ }+ }+ let Some((workspace, changed)) = report.workspace else {app.note("working in the project directory; start with --worktree for a dedicated checkout",);@@ -22371,7 +22467,6 @@ fn worktree_command(app: &mut App) {app.note("worktree:");app.system_detail_text(&format!("path {}", tilde_path(&workspace.path)));app.system_detail_text(&format!("branch {}", workspace.branch));- let changed = git::changed_paths(&workspace.path);if changed.is_empty() {app.system_detail_text("changes nothing yet");return;@@ -26089,7 +26184,8 @@ mod tests {subagent_name_from_run_id, summarize_result, sync_output_for,thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,transcript_top_padding, unescape_partial_json_string, user_content_parts,- with_real_think_tag_gate, worktree_command, AgentStatus, App, CompactKind, ContextReport,+ with_real_think_tag_gate, worktree_command, await_worktree_report, spawn_worktree_report,+ finish_worktree_report, AgentStatus, App, CompactKind, ContextReport,ContextSegment, CurrentRun, Readout, McpField, McpPrompt, MonitorSet, Pending,PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeRequest, ResumeTarget, Row,RowKind, Selection, SelectionMode, SnapshotJob, Status, ToolState, Worktree, AGENT_SETTINGS,@@ -26565,6 +26661,22 @@ mod tests {assert!(text.contains("5 tools · 0 req Running · ⚠ looping ×5"), "{text}");}+ /// `/agents` names where a child works: its worktree and branch, or the+ /// checkout it was given read-only.+ #[test]+ fn agent_detail_names_the_childs_workspace() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "sub-general-1".into(),+ name: "general".into(),+ task: Some("fix it".into()),+ workspace: Some("~/.jan/worktrees/jan-1/general-3f2a (jan/agent/general-3f2a)".into()),+ });+ let text = agent_detail_text(&mut app, "sub-general-1", 120, 20);+ assert!(text.contains("workspace ~/.jan/worktrees/jan-1/general-3f2a"), "{text}");+ assert!(text.contains("jan/agent/general-3f2a"), "{text}");+ }+#[test]fn agent_detail_notes_a_child_it_no_longer_has() {let mut app = test_app();@@ -26598,6 +26710,7 @@ mod tests {run_id: "sub-collector-1".to_string(),name: "collector".to_string(),task: Some("synthesize".to_string()),+ workspace: None,});assert_eq!(app.subagents.len(), 1, "promoted in place, not duplicated");assert!(!app.subagents[0].pending);@@ -26619,6 +26732,7 @@ mod tests {run_id: "sub-a-1".to_string(),name: "a".to_string(),task: Some("do it".to_string()),+ workspace: None,});open_agents_picker(&mut app);assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::Agents);@@ -26639,6 +26753,7 @@ mod tests {run_id: "sub-counter-1".to_string(),name: "counter".to_string(),task: Some("count things".to_string()),+ workspace: None,});let child = |event: StreamEvent| StreamEvent::Subagent {run_id: "sub-counter-1".to_string(),@@ -26842,6 +26957,7 @@ mod tests {run_id: "sub-counter-1".to_string(),name: "counter".to_string(),task: Some("count".to_string()),+ workspace: None,});open_agents_picker(&mut app);press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;@@ -26889,6 +27005,7 @@ mod tests {run_id: "sub-counter-1".to_string(),name: "counter".to_string(),task: None,+ workspace: None,});open_agents_picker(&mut app);press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;@@ -26912,6 +27029,7 @@ mod tests {run_id: "sub-counter-1".to_string(),name: "counter".to_string(),task: None,+ workspace: None,});open_agents_picker(&mut app);press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;@@ -26935,6 +27053,7 @@ mod tests {run_id: "sub-waster-1".to_string(),name: "waster".to_string(),task: None,+ workspace: None,});open_agents_picker(&mut app);press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;@@ -33410,6 +33529,7 @@ mod tests {run_id: "sub-a-1".into(),name: "a".into(),task: None,+ workspace: None,});if let Some((provider, model)) = child_on {app.apply(child_request_on(provider, model));@@ -33491,6 +33611,7 @@ mod tests {run_id: "sub-a-1".into(),name: "a".into(),task: None,+ workspace: None,});app.apply(child_request_on("tokamak", "tk-1"));app.submit_user("go".into());@@ -33529,6 +33650,7 @@ mod tests {run_id: "sub-a-1".into(),name: "a".into(),task: None,+ workspace: None,});let rt = tokio::runtime::Runtime::new().expect("runtime");let held = rt.block_on(args.provider_configs.lock());@@ -33626,6 +33748,7 @@ mod tests {compaction: None,session_start: None,memory_change_budget: None,+ child_scope: None,})}@@ -33748,6 +33871,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});let call = |i: u32, offset: u64| {wrap(@@ -33776,6 +33900,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});// Seven calls; only the last SUBAGENT_WINDOW remain visible.for i in 0..7 {@@ -33841,11 +33966,13 @@ mod tests {run_id: "r1".into(),name: "alpha".into(),task: None,+ workspace: None,});app.apply(StreamEvent::SubagentStart {run_id: "r2".into(),name: "beta".into(),task: None,+ workspace: None,});app.apply(wrap("r2",@@ -33890,6 +34017,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});assert_eq!(app.subagents.len(), 1, "no duplicate panel on promotion");let promoted = app.subagents.iter().find(|p| p.run_id == "r1").unwrap();@@ -35994,6 +36122,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});// More calls than the live window, so expansion reveals ones it hid.for i in 0..7 {@@ -36053,6 +36182,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});app.apply(wrap("r1",@@ -36087,6 +36217,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});app.apply(StreamEvent::SubagentEnd {run_id: "r1".into(),@@ -36151,6 +36282,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});// A wrapped child token is internal and dropped.app.apply(wrap(@@ -36175,6 +36307,7 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});app.apply(wrap("r1",@@ -36209,11 +36342,13 @@ mod tests {run_id: "r1".into(),name: "reviewer".into(),task: None,+ workspace: None,});app.apply(StreamEvent::SubagentStart {run_id: "r2".into(),name: "explorer".into(),task: None,+ workspace: None,});app.apply(wrap("r1",@@ -36703,6 +36838,7 @@ mod tests {run_id: "sub-reviewer-1".into(),name: "reviewer".into(),task: None,+ workspace: None,});app.apply(StreamEvent::ToolCall {id: "a1".into(),@@ -39418,10 +39554,61 @@ mod tests {assert_eq!(app.workspace, Some(test_worktree("/tmp/wt-a")));}- #[test]- fn worktree_command_without_one_points_at_the_flag() {+ /// `/worktree` the way the loop runs it: the command only asks, and the+ /// report (git per worktree) is gathered on the blocking pool and shown+ /// when it lands.+ async fn run_worktree_command(app: &mut App) {+ worktree_command(app);+ assert!(app.transcript.rows.is_empty(), "nothing is shown before git answers");+ assert!(std::mem::take(&mut app.worktree_request));+ let mut task = Some(spawn_worktree_report(app));+ let report = await_worktree_report(&mut task).await.unwrap();+ finish_worktree_report(app, report);+ }++ #[tokio::test]+ async fn worktree_command_lists_live_subagent_worktrees() {+ use std::process::Command;+ let root = tempfile::tempdir().unwrap();+ let r = root.path().to_string_lossy().to_string();+ let git = |args: &[&str]| {+ Command::new("git")+ .args(["-C", &r, "-c", "user.email=t@t", "-c", "user.name=t"])+ .args(args)+ .status()+ .is_ok_and(|s| s.success())+ };+ if !git(&["init", "-q"]) {+ return;+ }+ std::fs::write(root.path().join("a.txt"), "a\n").unwrap();+ assert!(git(&["add", "a.txt"]));+ assert!(git(&["commit", "-q", "--no-gpg-sign", "-m", "a"]));let mut app = test_app();- worktree_command(&mut app);+ let ledger = app.subagent_set.workspaces.clone();+ let (ws, lease) = ledger.assign(root.path(), "general", true, None).unwrap();+ drop(lease);+ let branch = ws.worktree.as_ref().unwrap().branch.clone();++ run_worktree_command(&mut app).await;+ let notes: String = app+ .transcript+ .rows+ .iter()+ .map(row_text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(notes.contains("subagent worktrees:"), "{notes}");+ assert!(notes.contains(&branch), "{notes}");+ assert!(notes.contains("(0 commit(s), 0 uncommitted file(s))"), "{notes}");+ assert!(notes.contains("--worktree"), "{notes}");+ let _ = tokio::task::spawn_blocking(move || ledger.finish_session()).await;+ }++ #[tokio::test]+ async fn worktree_command_without_one_points_at_the_flag() {+ let mut app = test_app();+ run_worktree_command(&mut app).await;let notes: String = app.transcript.rows@@ -40757,6 +40944,7 @@ mod tests {run_id: run_id.into(),name: name.into(),task: task.map(str::to_string),+ workspace: None,});}@@ -44700,7 +44888,7 @@ mod tests {own_project(&mut app);app.args = Some(test_args(&app, providers));let (tx, _rx) = mpsc::unbounded_channel();- let task = start_memory_tidy(&mut app, TidyKind::Manual, &tx).expect("tidy started");+ let task = start_memory_tidy(&mut app, TidyKind::Manual, &tx).await.expect("tidy started");assert_eq!(app.tidy_running, Some(TidyKind::Manual));assert_eq!(app.subagent_set.live_run_ids().len(), 1, "the tidy child is live");run_command(&mut app, "plan", &no_mcp()).await;@@ -46437,6 +46625,7 @@ mod tests {home_readonly: false,// Bare shell: these exercise the TUI wiring, not the jail.sandbox: false,+ workspace_readonly: false,}}diff --git a/src-tauri/src/core/cli/tui/tests/snapshot.rs b/src-tauri/src/core/cli/tui/tests/snapshot.rsindex 6f05c0b71..ec574279b 100644--- a/src-tauri/src/core/cli/tui/tests/snapshot.rs+++ b/src-tauri/src/core/cli/tui/tests/snapshot.rs@@ -764,6 +764,7 @@ fn start_kv_review(app: &mut App) {run_id: "sub-kv-review-1".into(),name: "kv-review".into(),task: Some("Review the key-value store for races.\nThen report.".into()),+ workspace: None,});}