graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Give desktop task workspaces their own Git checkouts
justrach4f7d51d03803
diff --git a/gui/src-tauri/src/persistence/project_store.rs b/gui/src-tauri/src/persistence/project_store.rsindex caa16c00..b966111f 100644--- a/gui/src-tauri/src/persistence/project_store.rs+++ b/gui/src-tauri/src/persistence/project_store.rs@@ -1,44 +1,40 @@use std::fs;use std::path::{Path, PathBuf};use std::sync::Mutex;-use anyhow::Context;use diesel::connection::SimpleConnection;use diesel::prelude::*;use diesel::sql_types::{BigInt, Nullable, Text};use diesel::{QueryableByName, RunQueryDsl, SqliteConnection, sql_query};use uuid::Uuid;-#[path = "project_store_support.rs"]mod support;use support::*;-+#[path = "project_store_tasks.rs"]+mod tasks;+pub use tasks::TaskWorkspaceRecord;#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RegisteredWorkspaceKind {Project,ManagedChat,}-#[derive(Debug, Clone)]pub struct RegisteredWorkspace {pub kind: RegisteredWorkspaceKind,pub path: PathBuf,pub display_name: Option<String>,}-#[derive(Debug, Clone)]pub struct RegisteredWorkspaceMetadata {pub kind: RegisteredWorkspaceKind,pub display_name: Option<String>,}-#[derive(Debug)]pub struct ProjectStore {db_path: PathBuf,managed_chats_root: PathBuf,connection_lock: Mutex<()>,}-#[derive(Debug, Clone, QueryableByName)]pub struct SavedWorkspaceSummaryRecord {#[diesel(sql_type = Text)]@@ -48,35 +44,6 @@ pub struct SavedWorkspaceSummaryRecord {#[diesel(sql_type = BigInt)]pub updated_at: i64,}--#[derive(Debug, Clone, QueryableByName)]-pub struct TaskWorkspaceRecord {- #[diesel(sql_type = Text)]- pub path: String,- #[diesel(sql_type = Text)]- pub branch: String,- #[diesel(sql_type = Text)]- pub base_branch: String,- #[diesel(sql_type = Text)]- pub base_commit: String,- #[diesel(sql_type = Nullable<Text>)]- pub setup_script: Option<String>,- #[diesel(sql_type = Nullable<Text>)]- pub run_script: Option<String>,- #[diesel(sql_type = Nullable<Text>)]- pub teardown_script: Option<String>,- #[diesel(sql_type = BigInt)]- pub setup_ran: i64,- #[diesel(sql_type = Nullable<Text>)]- pub setup_error: Option<String>,- #[diesel(sql_type = Nullable<Text>)]- pub run_error: Option<String>,- #[diesel(sql_type = Nullable<Text>)]- pub keep_reason: Option<String>,- #[diesel(sql_type = BigInt)]- pub merged_back: i64,-}-#[derive(Debug, Clone, QueryableByName)]pub struct SavedWorkspaceRecord {#[diesel(sql_type = Text)]@@ -88,7 +55,6 @@ pub struct SavedWorkspaceRecord {#[diesel(sql_type = BigInt)]pub updated_at: i64,}-impl ProjectStore {pub fn new(db_path: PathBuf, managed_chats_root: PathBuf) -> anyhow::Result<Self> {let store = Self {@@ -489,122 +455,6 @@ impl ProjectStore {})}- pub fn upsert_task_workspace(&self, record: &TaskWorkspaceRecord) -> anyhow::Result<()> {- self.with_connection(|connection| {- sql_query(- "- INSERT INTO task_workspaces (- path, branch, base_branch, base_commit, setup_script, run_script,- teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back- )- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)- ON CONFLICT(path) DO UPDATE SET- branch = excluded.branch,- base_branch = excluded.base_branch,- base_commit = excluded.base_commit,- setup_script = excluded.setup_script,- run_script = excluded.run_script,- teardown_script = excluded.teardown_script,- setup_ran = excluded.setup_ran,- setup_error = excluded.setup_error,- run_error = excluded.run_error,- keep_reason = excluded.keep_reason,- merged_back = excluded.merged_back- ",- )- .bind::<Text, _>(&record.path)- .bind::<Text, _>(&record.branch)- .bind::<Text, _>(&record.base_branch)- .bind::<Text, _>(&record.base_commit)- .bind::<Nullable<Text>, _>(record.setup_script.as_deref())- .bind::<Nullable<Text>, _>(record.run_script.as_deref())- .bind::<Nullable<Text>, _>(record.teardown_script.as_deref())- .bind::<BigInt, _>(record.setup_ran)- .bind::<Nullable<Text>, _>(record.setup_error.as_deref())- .bind::<Nullable<Text>, _>(record.run_error.as_deref())- .bind::<Nullable<Text>, _>(record.keep_reason.as_deref())- .bind::<BigInt, _>(record.merged_back)- .execute(connection)?;- Ok(())- })- }-- pub fn list_task_workspaces(&self) -> anyhow::Result<Vec<TaskWorkspaceRecord>> {- self.with_connection(|connection| {- let rows = sql_query(- "- SELECT path, branch, base_branch, base_commit, setup_script, run_script,- teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back- FROM task_workspaces- ORDER BY path- ",- )- .load(connection)?;- Ok(rows)- })- }-- pub fn get_task_workspace(&self, path: &Path) -> anyhow::Result<Option<TaskWorkspaceRecord>> {- let canonical = canonicalize_workspace_removal_path(path);- self.with_connection(|connection| {- let row = sql_query(- "- SELECT path, branch, base_branch, base_commit, setup_script, run_script,- teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back- FROM task_workspaces- WHERE path = ?1- ",- )- .bind::<Text, _>(canonical)- .get_result(connection)- .optional()?;- Ok(row)- })- }-- pub fn set_task_keep_reason(&self, path: &str, reason: Option<&str>) -> anyhow::Result<()> {- self.with_connection(|connection| {- sql_query("UPDATE task_workspaces SET keep_reason = ?2 WHERE path = ?1")- .bind::<Text, _>(path)- .bind::<Nullable<Text>, _>(reason)- .execute(connection)?;- Ok(())- })- }-- pub fn set_task_setup_result(- &self,- path: &str,- error: Option<&str>,- ) -> anyhow::Result<()> {- self.with_connection(|connection| {- sql_query(- "UPDATE task_workspaces SET setup_ran = 1, setup_error = ?2 WHERE path = ?1",- )- .bind::<Text, _>(path)- .bind::<Nullable<Text>, _>(error)- .execute(connection)?;- Ok(())- })- }-- pub fn set_task_merged_back(&self, path: &str) -> anyhow::Result<()> {- self.with_connection(|connection| {- sql_query("UPDATE task_workspaces SET merged_back = 1, keep_reason = NULL WHERE path = ?1")- .bind::<Text, _>(path)- .execute(connection)?;- Ok(())- })- }-- pub fn delete_task_workspace(&self, path: &str) -> anyhow::Result<()> {- self.with_connection(|connection| {- sql_query("DELETE FROM task_workspaces WHERE path = ?1")- .bind::<Text, _>(path)- .execute(connection)?;- Ok(())- })- }fn init(&self) -> anyhow::Result<()> {if let Some(parent) = self.db_path.parent() {diff --git a/gui/src-tauri/src/persistence/project_store_tasks.rs b/gui/src-tauri/src/persistence/project_store_tasks.rsnew file mode 100644index 00000000..996cec48--- /dev/null+++ b/gui/src-tauri/src/persistence/project_store_tasks.rs@@ -0,0 +1,155 @@+use std::path::Path;++use diesel::prelude::*;+use diesel::sql_types::{BigInt, Nullable, Text};+use diesel::{QueryableByName, RunQueryDsl, sql_query};++use super::support::canonicalize_workspace_removal_path;+use super::ProjectStore;++#[derive(Debug, Clone, QueryableByName)]+pub struct TaskWorkspaceRecord {+ #[diesel(sql_type = Text)]+ pub path: String,+ #[diesel(sql_type = Text)]+ pub branch: String,+ #[diesel(sql_type = Text)]+ pub base_branch: String,+ #[diesel(sql_type = Text)]+ pub base_commit: String,+ #[diesel(sql_type = Nullable<Text>)]+ pub setup_script: Option<String>,+ #[diesel(sql_type = Nullable<Text>)]+ pub run_script: Option<String>,+ #[diesel(sql_type = Nullable<Text>)]+ pub teardown_script: Option<String>,+ #[diesel(sql_type = BigInt)]+ pub setup_ran: i64,+ #[diesel(sql_type = Nullable<Text>)]+ pub setup_error: Option<String>,+ #[diesel(sql_type = Nullable<Text>)]+ pub run_error: Option<String>,+ #[diesel(sql_type = Nullable<Text>)]+ pub keep_reason: Option<String>,+ #[diesel(sql_type = BigInt)]+ pub merged_back: i64,+}++impl ProjectStore {+ pub fn upsert_task_workspace(&self, record: &TaskWorkspaceRecord) -> anyhow::Result<()> {+ self.with_connection(|connection| {+ sql_query(+ "+ INSERT INTO task_workspaces (+ path, branch, base_branch, base_commit, setup_script, run_script,+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back+ )+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)+ ON CONFLICT(path) DO UPDATE SET+ branch = excluded.branch,+ base_branch = excluded.base_branch,+ base_commit = excluded.base_commit,+ setup_script = excluded.setup_script,+ run_script = excluded.run_script,+ teardown_script = excluded.teardown_script,+ setup_ran = excluded.setup_ran,+ setup_error = excluded.setup_error,+ run_error = excluded.run_error,+ keep_reason = excluded.keep_reason,+ merged_back = excluded.merged_back+ ",+ )+ .bind::<Text, _>(&record.path)+ .bind::<Text, _>(&record.branch)+ .bind::<Text, _>(&record.base_branch)+ .bind::<Text, _>(&record.base_commit)+ .bind::<Nullable<Text>, _>(record.setup_script.as_deref())+ .bind::<Nullable<Text>, _>(record.run_script.as_deref())+ .bind::<Nullable<Text>, _>(record.teardown_script.as_deref())+ .bind::<BigInt, _>(record.setup_ran)+ .bind::<Nullable<Text>, _>(record.setup_error.as_deref())+ .bind::<Nullable<Text>, _>(record.run_error.as_deref())+ .bind::<Nullable<Text>, _>(record.keep_reason.as_deref())+ .bind::<BigInt, _>(record.merged_back)+ .execute(connection)?;+ Ok(())+ })+ }++ pub fn list_task_workspaces(&self) -> anyhow::Result<Vec<TaskWorkspaceRecord>> {+ self.with_connection(|connection| {+ let rows = sql_query(+ "+ SELECT path, branch, base_branch, base_commit, setup_script, run_script,+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back+ FROM task_workspaces+ ORDER BY path+ ",+ )+ .load(connection)?;+ Ok(rows)+ })+ }++ pub fn get_task_workspace(&self, path: &Path) -> anyhow::Result<Option<TaskWorkspaceRecord>> {+ let canonical = canonicalize_workspace_removal_path(path);+ self.with_connection(|connection| {+ let row = sql_query(+ "+ SELECT path, branch, base_branch, base_commit, setup_script, run_script,+ teardown_script, setup_ran, setup_error, run_error, keep_reason, merged_back+ FROM task_workspaces+ WHERE path = ?1+ ",+ )+ .bind::<Text, _>(canonical)+ .get_result(connection)+ .optional()?;+ Ok(row)+ })+ }++ pub fn set_task_keep_reason(&self, path: &str, reason: Option<&str>) -> anyhow::Result<()> {+ self.with_connection(|connection| {+ sql_query("UPDATE task_workspaces SET keep_reason = ?2 WHERE path = ?1")+ .bind::<Text, _>(path)+ .bind::<Nullable<Text>, _>(reason)+ .execute(connection)?;+ Ok(())+ })+ }++ pub fn set_task_setup_result(+ &self,+ path: &str,+ error: Option<&str>,+ ) -> anyhow::Result<()> {+ self.with_connection(|connection| {+ sql_query(+ "UPDATE task_workspaces SET setup_ran = 1, setup_error = ?2 WHERE path = ?1",+ )+ .bind::<Text, _>(path)+ .bind::<Nullable<Text>, _>(error)+ .execute(connection)?;+ Ok(())+ })+ }++ pub fn set_task_merged_back(&self, path: &str) -> anyhow::Result<()> {+ self.with_connection(|connection| {+ sql_query("UPDATE task_workspaces SET merged_back = 1, keep_reason = NULL WHERE path = ?1")+ .bind::<Text, _>(path)+ .execute(connection)?;+ Ok(())+ })+ }++ pub fn delete_task_workspace(&self, path: &str) -> anyhow::Result<()> {+ self.with_connection(|connection| {+ sql_query("DELETE FROM task_workspaces WHERE path = ?1")+ .bind::<Text, _>(path)+ .execute(connection)?;+ Ok(())+ })+ }+}diff --git a/gui/src-tauri/src/runtime/simple.rs b/gui/src-tauri/src/runtime/simple.rsindex a24891a1..0b6251f3 100644--- a/gui/src-tauri/src/runtime/simple.rs+++ b/gui/src-tauri/src/runtime/simple.rs@@ -1,6 +1,7 @@#[path = "simple_prompt.rs"]mod prompt;-+#[path = "task_host.rs"]+mod task_host;use crate::{bridge::emitter::UiEventEmitter,desktop_open,@@ -21,14 +22,12 @@ use std::{use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tokio::sync::Mutex;use uuid::Uuid;-#[derive(Clone)]struct QueuedPrompt {agent_id: Option<String>,engine_prompt: String,request_id: String,}-#[derive(Clone, Default)]struct ConversationState {workspace_path: String,@@ -53,7 +52,6 @@ struct ConversationState {ultracode_enabled: bool,updated_at: i64,}-#[derive(Default)]struct RuntimeState {active_workspace_path: Option<String>,@@ -79,7 +77,6 @@ struct RuntimeState {/// Surfaced as the conversation's `followup` so the FollowupComposer renders.pending_followups: HashMap<String, FollowupRequestDto>,}-/// One model the `graff` CLI advertises in `--schema`.#[derive(Clone)]struct ModelOption {@@ -89,7 +86,6 @@ struct ModelOption {context: Option<u64>,is_default: bool,}-/// A persistent `graff --json` child bound to one conversation. Keeping the/// process alive across turns preserves conversation context (and the model's/// KV cache).@@ -1601,11 +1597,6 @@ impl RuntimeManager {.await}- /// Handles chat handoff as a no-op in the MVP adapter.- pub async fn handoff_chat(&self, _: HandoffChatInput) -> Result<SessionSnapshotDto> {- self.snapshot().await- }-/// Answers an in-flight `ask_user` prompt: writes the reply to the graff/// child's stdin (unblocking it), clears the pending followup, and lets the/// still-running stream_turn loop pick up the resulting tool_result.@@ -1705,7 +1696,11 @@ impl RuntimeManager {}/// Archives a workspace from the local registry.+ /// Task checkouts go through the keep gate first.pub async fn archive_workspace(&self, workspace_path: String) -> Result<SessionSnapshotDto> {+ if let Some(snapshot) = self.archive_if_task(&workspace_path).await? {+ return Ok(snapshot);+ }self.projects.archive_workspace(Path::new(&workspace_path))?;let conversation_ids: Vec<String> = {@@ -1917,6 +1912,8 @@ impl RuntimeManager {}async fn snapshot(&self) -> Result<SessionSnapshotDto> {+ self.auto_archive_merged_tasks(false).await;+ let task_by_path = self.task_records();let mut state = self.state.lock().await;let registered = self.projects.list_workspaces().unwrap_or_default();for workspace in ®istered {@@ -1998,6 +1995,7 @@ impl RuntimeManager {configuration_error: None,selected_conversation_id,conversations,+ task: task_by_path.get(path).map(task_host::summary),}}).collect();diff --git a/gui/src-tauri/src/runtime/task_host.rs b/gui/src-tauri/src/runtime/task_host.rsnew file mode 100644index 00000000..67cda1a4--- /dev/null+++ b/gui/src-tauri/src/runtime/task_host.rs@@ -0,0 +1,454 @@+//! Task-workspace host methods, split out of runtime/simple.rs so that file+//! does not grow.++use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};++use anyhow::{Context, Result};++use crate::dto::*;+use crate::persistence::project_store::TaskWorkspaceRecord;+use crate::task_workspace;++use super::{+ RuntimeManager, canonicalize_workspace_path, first_workspace_conversation_id, run_git,+ set_active_workspace,+};++pub(super) fn summary(record: &TaskWorkspaceRecord) -> TaskWorkspaceSummaryDto {+ let inspection = task_workspace::inspect(Path::new(&record.path), &record.base_commit);+ TaskWorkspaceSummaryDto {+ branch: record.branch.clone(),+ base_branch: record.base_branch.clone(),+ base_commit: record.base_commit.clone(),+ checkout_bytes: inspection.checkout_bytes,+ keep_reason: record+ .keep_reason+ .clone()+ .or_else(|| inspection.keep.text().map(str::to_string)),+ setup_script: record.setup_script.clone(),+ run_script: record.run_script.clone(),+ teardown_script: record.teardown_script.clone(),+ setup_error: record.setup_error.clone(),+ run_error: record.run_error.clone(),+ merged_back: record.merged_back != 0,+ }+}++impl RuntimeManager {+ pub(super) async fn archive_if_task(+ &self,+ path: &str,+ ) -> Result<Option<crate::dto::SessionSnapshotDto>> {+ if self.projects.get_task_workspace(Path::new(path))?.is_some() {+ return Ok(Some(self.finish_task_workspace(path, false, false).await?));+ }+ Ok(None)+ }++ pub(super) fn task_records(&self) -> HashMap<String, TaskWorkspaceRecord> {+ self.projects+ .list_task_workspaces()+ .unwrap_or_default()+ .into_iter()+ .map(|record| (record.path.clone(), record))+ .collect()+ }++ /// Moves a chat onto a fresh task worktree, or checks out a local branch.+ pub async fn handoff_chat(&self, input: HandoffChatInput) -> Result<SessionSnapshotDto> {+ match input.target {+ ChatHandoffTargetDto::Local => {+ if let Some(branch) = input+ .branch_name+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ {+ run_git(&input.source_workspace_path, &["checkout", "-b", branch])?;+ }+ if let Some(conversation_id) = input.conversation_id {+ self.select_conversation(input.source_workspace_path, conversation_id)+ .await+ } else {+ self.start_new_chat(input.source_workspace_path).await+ }+ }+ ChatHandoffTargetDto::Worktree => {+ let branch = input+ .branch_name+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .context("a branch name is required to start a worktree")?;+ self.create_task_workspace(+ &input.source_workspace_path,+ None,+ branch,+ None,+ None,+ None,+ input.conversation_id,+ )+ .await+ }+ }+ }++ pub async fn task_workspace_action(+ &self,+ input: TaskWorkspaceActionInput,+ ) -> Result<SessionSnapshotDto> {+ match input.action {+ TaskWorkspaceActionDto::Create => {+ let source = input+ .source_workspace_path+ .as_deref()+ .filter(|path| !path.is_empty())+ .context("choose a repository to branch from")?;+ let branch = input+ .branch_name+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .context("a branch name is required")?;+ self.create_task_workspace(+ source,+ input.base_branch.as_deref(),+ branch,+ input.setup_script.as_deref(),+ input.run_script.as_deref(),+ input.teardown_script.as_deref(),+ None,+ )+ .await+ }+ TaskWorkspaceActionDto::Archive => {+ let path = input+ .workspace_path+ .as_deref()+ .context("workspace path required")?;+ self.finish_task_workspace(path, false, input.delete_branch)+ .await+ }+ TaskWorkspaceActionDto::Discard => {+ let path = input+ .workspace_path+ .as_deref()+ .context("workspace path required")?;+ self.finish_task_workspace(path, true, input.delete_branch)+ .await+ }+ TaskWorkspaceActionDto::MergeBack => self.merge_task_workspace(&input).await,+ TaskWorkspaceActionDto::UpdateFromBase => self.update_task_workspace(&input).await,+ TaskWorkspaceActionDto::SyncMerged => {+ self.auto_archive_merged_tasks(true).await;+ self.snapshot().await+ }+ }+ }++ pub async fn task_workspace_review(+ &self,+ workspace_path: String,+ ) -> Result<TaskWorkspaceReviewDto> {+ let record = self+ .projects+ .get_task_workspace(Path::new(&workspace_path))?+ .context("not a task workspace")?;+ match task_workspace::review_diff(Path::new(&record.path), &record.base_branch) {+ Ok(diff) => Ok(TaskWorkspaceReviewDto {+ workspace_path: record.path,+ branch: record.branch,+ base_branch: record.base_branch,+ stat: diff.stat,+ patch: diff.patch,+ error: None,+ }),+ Err(error) => Ok(TaskWorkspaceReviewDto {+ workspace_path: record.path,+ branch: record.branch,+ base_branch: record.base_branch,+ stat: String::new(),+ patch: String::new(),+ error: Some(error.to_string()),+ }),+ }+ }++ async fn create_task_workspace(+ &self,+ source: &str,+ base_branch: Option<&str>,+ branch: &str,+ setup_script: Option<&str>,+ run_script: Option<&str>,+ teardown_script: Option<&str>,+ conversation_id: Option<String>,+ ) -> Result<SessionSnapshotDto> {+ let created = task_workspace::create_task_worktree(Path::new(source), base_branch, branch)?;+ let path = canonicalize_workspace_path(created.path.clone())?;+ let blank = |value: Option<&str>| {+ value+ .map(str::trim)+ .filter(|script| !script.is_empty())+ .map(ToOwned::to_owned)+ };+ let record = TaskWorkspaceRecord {+ path: path.clone(),+ branch: created.branch,+ base_branch: created.base_branch,+ base_commit: created.base_commit,+ setup_script: blank(setup_script),+ run_script: blank(run_script),+ teardown_script: blank(teardown_script),+ setup_ran: 0,+ setup_error: None,+ run_error: None,+ keep_reason: None,+ merged_back: 0,+ };+ self.projects.upsert_task_workspace(&record)?;+ self.projects.add_project(Path::new(&path))?;+ let setup_error = if let Some(script) = record.setup_script.as_deref() {+ let outcome = task_workspace::run_script(Path::new(&path), script);+ let error = (!outcome.ok).then_some(outcome.output);+ self.projects+ .set_task_setup_result(&path, error.as_deref())?;+ error+ } else {+ None+ };+ if let Some(conversation_id) = conversation_id {+ let mut state = self.state.lock().await;+ if let Some(conversation) = state.conversations.get_mut(&conversation_id) {+ conversation.workspace_path = path.clone();+ }+ set_active_workspace(&mut state, &path);+ state.active_conversation_id = Some(conversation_id.clone());+ state+ .selected_by_workspace+ .insert(path.clone(), conversation_id);+ drop(state);+ } else {+ self.open_workspace(PathBuf::from(&path)).await?;+ self.start_new_chat(path.clone()).await?;+ }+ let mut snapshot = self.snapshot().await?;+ if let Some(error) = setup_error {+ snapshot.ui_error = Some(format!(+ "worktree created, but the setup script failed:\n{error}"+ ));+ }+ Ok(snapshot)+ }++ async fn finish_task_workspace(+ &self,+ workspace_path: &str,+ discard: bool,+ delete_branch: bool,+ ) -> Result<SessionSnapshotDto> {+ let record = self+ .projects+ .get_task_workspace(Path::new(workspace_path))?+ .context("not a task workspace")?;+ let inspection = task_workspace::inspect(Path::new(&record.path), &record.base_commit);+ if !discard {+ if let Some(reason) = inspection.keep.text() {+ self.projects+ .set_task_keep_reason(&record.path, Some(reason))?;+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(format!("kept {} — {reason}", record.path));+ return Ok(snapshot);+ }+ }+ if let Some(script) = record+ .teardown_script+ .as_deref()+ .filter(|script| !script.trim().is_empty())+ {+ let outcome = task_workspace::run_script(Path::new(&record.path), script);+ if !outcome.ok && !discard {+ self.projects+ .set_task_keep_reason(&record.path, Some(task_workspace::KEEP_TEARDOWN))?;+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(format!(+ "kept {} — teardown hook failed\n{}",+ record.path, outcome.output+ ));+ return Ok(snapshot);+ }+ }+ let repo = task_workspace::repo_root(Path::new(&record.path));+ task_workspace::remove_checkout(Path::new(&record.path), discard)?;+ let branch_note = if task_workspace::branch_delete_allowed(+ task_workspace::worktree_exists(Path::new(&record.path)),+ record.merged_back == 1,+ delete_branch,+ ) {+ match task_workspace::delete_branch(&repo, &record.branch, true) {+ Ok(()) => None,+ Err(error) => Some(format!("checkout removed, branch kept — {error}")),+ }+ } else {+ None+ };+ self.projects.delete_task_workspace(&record.path)?;+ self.projects.archive_workspace(Path::new(&record.path))?;+ self.forget_workspace(&record.path).await;+ self.persist_conversations().await;+ let snapshot = self.snapshot().await?;+ if let Some(note) = branch_note {+ let mut snapshot = snapshot;+ snapshot.ui_error = Some(note);+ return Ok(snapshot);+ }+ Ok(snapshot)+ }++ async fn merge_task_workspace(+ &self,+ input: &TaskWorkspaceActionInput,+ ) -> Result<SessionSnapshotDto> {+ let path = input+ .workspace_path+ .as_deref()+ .context("workspace path required")?;+ let record = self+ .projects+ .get_task_workspace(Path::new(path))?+ .context("not a task workspace")?;+ let repo = task_workspace::repo_root(Path::new(&record.path));+ if let Err(error) = task_workspace::merge_back(&repo, &record.branch) {+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(error.to_string());+ return Ok(snapshot);+ }+ self.projects.set_task_merged_back(&record.path)?;+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(format!(+ "landed {} onto {} as one commit",+ record.branch, record.base_branch+ ));+ Ok(snapshot)+ }++ async fn update_task_workspace(+ &self,+ input: &TaskWorkspaceActionInput,+ ) -> Result<SessionSnapshotDto> {+ let path = input+ .workspace_path+ .as_deref()+ .context("workspace path required")?;+ let record = self+ .projects+ .get_task_workspace(Path::new(path))?+ .context("not a task workspace")?;+ if let Err(error) =+ task_workspace::update_from_base(Path::new(&record.path), &record.base_branch)+ {+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(error.to_string());+ return Ok(snapshot);+ }+ self.projects.set_task_keep_reason(&record.path, None)?;+ let mut snapshot = self.snapshot().await?;+ snapshot.ui_error = Some(format!("updated from {}", record.base_branch));+ Ok(snapshot)+ }++ pub(super) async fn auto_archive_merged_tasks(&self, include_remote: bool) {+ let records = self.projects.list_task_workspaces().unwrap_or_default();+ for record in records {+ let proof = if include_remote {+ task_workspace::proven_merged(+ Path::new(&record.path),+ &record.branch,+ &record.base_branch,+ )+ } else {+ task_workspace::proven_merged_local(+ Path::new(&record.path),+ &record.branch,+ &record.base_branch,+ )+ };+ if proof != task_workspace::MergeProof::Merged {+ continue;+ }+ let inspection = task_workspace::inspect(Path::new(&record.path), &record.base_commit);+ if let Some(reason) = inspection.keep.text() {+ let _ = self+ .projects+ .set_task_keep_reason(&record.path, Some(reason));+ continue;+ }+ if let Some(script) = record+ .teardown_script+ .as_deref()+ .filter(|script| !script.trim().is_empty())+ {+ let outcome = task_workspace::run_script(Path::new(&record.path), script);+ if !outcome.ok {+ let _ = self+ .projects+ .set_task_keep_reason(&record.path, Some(task_workspace::KEEP_TEARDOWN));+ continue;+ }+ }+ if task_workspace::remove_checkout(Path::new(&record.path), false).is_err() {+ let _ = self.projects.set_task_keep_reason(+ &record.path,+ Some(task_workspace::KEEP_UNVERIFIABLE),+ );+ continue;+ }+ let _ = self.projects.delete_task_workspace(&record.path);+ let _ = self.projects.archive_workspace(Path::new(&record.path));+ self.forget_workspace(&record.path).await;+ }+ }++ async fn forget_workspace(&self, workspace_path: &str) {+ let conversation_ids: Vec<String> = {+ let state = self.state.lock().await;+ state+ .conversations+ .values()+ .filter(|conversation| conversation.workspace_path == workspace_path)+ .map(|conversation| conversation.conversation_id.clone())+ .collect()+ };+ for conversation_id in &conversation_ids {+ self.drop_session(conversation_id).await;+ }+ let removed: HashSet<String> = conversation_ids.into_iter().collect();+ let mut state = self.state.lock().await;+ state.workspaces.retain(|path| path != workspace_path);+ state+ .conversations+ .retain(|_, conversation| conversation.workspace_path != workspace_path);+ state.selected_by_workspace.remove(workspace_path);+ state+ .selected_by_workspace+ .retain(|_, conversation_id| !removed.contains(conversation_id));+ if state.active_workspace_path.as_deref() == Some(workspace_path) {+ state.active_workspace_path = state.workspaces.first().cloned();+ state.active_conversation_id = state+ .active_workspace_path+ .clone()+ .and_then(|path| first_workspace_conversation_id(&state, &path));+ } else if state+ .active_conversation_id+ .as_ref()+ .is_some_and(|conversation_id| removed.contains(conversation_id))+ {+ state.active_conversation_id = state+ .active_workspace_path+ .clone()+ .and_then(|path| first_workspace_conversation_id(&state, &path));+ }+ }+}diff --git a/gui/src-tauri/src/task_workspace.rs b/gui/src-tauri/src/task_workspace.rsindex 689fed22..d0bd2745 100644--- a/gui/src-tauri/src/task_workspace.rs+++ b/gui/src-tauri/src/task_workspace.rs@@ -4,21 +4,20 @@//! surface: one branch per task checkout, a keep gate that will not drop//! dirty / unique / unverifiable trees, and merge-back that refuses to//! clobber uncommitted work on the base.-use std::fs;use std::io::Read;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::thread;use std::time::{Duration, Instant};-use anyhow::{Context, Result, bail};-+#[path = "task_workspace_git.rs"]+mod git_helpers;+use git_helpers::*;pub const KEEP_DIRTY: &str = "has uncommitted changes";pub const KEEP_UNIQUE: &str = "has commits nothing else references";pub const KEEP_UNVERIFIABLE: &str = "could not verify it is safe to remove";pub const KEEP_TEARDOWN: &str = "teardown hook failed";-#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum KeepReason {Removed,@@ -26,7 +25,6 @@ pub enum KeepReason {UniqueCommits,Unverifiable,}-impl KeepReason {pub fn text(self) -> Option<&'static str> {match self {@@ -594,318 +592,7 @@ fn main_worktree(path: &Path) -> Option<PathBuf> {Some(main.to_path_buf())}-fn gh_merged_pr(repo: &Path, branch: &str) -> Option<bool> {- let mut command = Command::new("gh");- command- .args([- "pr",- "list",- "--head",- branch,- "--state",- "merged",- "--json",- "number",- "--limit",- "1",- ])- .current_dir(repo)- .env("GH_PROMPT_DISABLED", "1")- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null());- let text = run_timeout(&mut command, Duration::from_secs(3))?;- if text.trim().is_empty() || text.trim() == "[]" {- return Some(false);- }- Some(text.contains("\"number\""))-}--fn run_timeout(command: &mut Command, timeout: Duration) -> Option<String> {- let mut child = command.spawn().ok()?;- let started = Instant::now();- loop {- match child.try_wait() {- Ok(Some(_)) => {- let mut text = String::new();- if let Some(mut stdout) = child.stdout.take() {- let _ = stdout.read_to_string(&mut text);- }- let _ = child.wait();- return Some(text);- }- Ok(None) if started.elapsed() > timeout => {- let _ = child.kill();- let _ = child.wait();- return None;- }- Ok(None) => thread::sleep(Duration::from_millis(40)),- Err(_) => return None,- }- }-}--fn resolve_dir(path: &Path) -> Result<PathBuf> {- fs::canonicalize(path).with_context(|| format!("workspace not found: {}", path.display()))-}--fn git(cwd: &Path, args: &[&str]) -> Result<std::process::Output> {- Command::new("git")- .args(args)- .current_dir(cwd)- .stdin(Stdio::null())- .output()- .with_context(|| format!("failed to run git {}", args.join(" ")))-}--fn git_stdout(cwd: &Path, args: &[&str]) -> Result<String> {- let output = git(cwd, args)?;- if !output.status.success() {- bail!("{}", stderr_text(&output).trim());- }- Ok(String::from_utf8_lossy(&output.stdout).into_owned())-}--fn stderr_text(output: &std::process::Output) -> String {- let mut text = String::from_utf8_lossy(&output.stderr).into_owned();- if text.trim().is_empty() {- text = String::from_utf8_lossy(&output.stdout).into_owned();- }- text-}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn keep_reason_requires_proof_on_every_axis() {- assert_eq!(- keep_reason(true, "", "abc", "abc", false),- KeepReason::Removed- );- assert_eq!(- keep_reason(true, "", "def", "abc", true),- KeepReason::Removed- );- assert_eq!(- keep_reason(true, " M src/a.rs\n", "abc", "abc", true),- KeepReason::Dirty- );- assert_eq!(- keep_reason(true, "?? new.rs\n", "abc", "abc", true),- KeepReason::Dirty- );- assert_eq!(- keep_reason(true, "", "def", "abc", false),- KeepReason::UniqueCommits- );- assert_eq!(- keep_reason(false, "", "abc", "abc", true),- KeepReason::Unverifiable- );- assert_eq!(- keep_reason(true, "", "", "abc", true),- KeepReason::Unverifiable- );- }-- #[test]- fn reap_keeps_main_release_session_and_dirty_agent_trees() {- assert_eq!(- reap_verdict(true, false, false, true, "/repo", "main", KeepReason::Removed),- ReapVerdict::KeepMain- );- assert_eq!(- reap_verdict(- false,- false,- true,- true,- "/repo/.graff/worktrees/rel",- "release/v1",- KeepReason::Removed- ),- ReapVerdict::KeepLocked- );- assert_eq!(- reap_verdict(- false,- false,- false,- false,- "/repo/.graff/worktrees/rel",- "hotfix/urgent",- KeepReason::Removed- ),- ReapVerdict::KeepRelease- );- assert_eq!(- reap_verdict(- false,- false,- false,- false,- "/repo/.graff/worktrees/session-1",- "worktree-session-1",- KeepReason::Removed- ),- ReapVerdict::KeepSession- );- assert_eq!(- reap_verdict(- false,- false,- false,- false,- "/repo/.graff/worktrees/agent-1",- "graff/agents/sa-1",- KeepReason::Dirty- ),- ReapVerdict::KeepDirty- );- assert_eq!(- reap_verdict(- false,- false,- false,- false,- "/repo/.graff/worktrees/agent-1",- "graff/agents/sa-1",- KeepReason::Removed- ),- ReapVerdict::Remove- );- assert_eq!(- reap_verdict(- false,- false,- false,- false,- "/repo/.worktrees/mine",- "feature/mine",- KeepReason::Removed- ),- ReapVerdict::KeepForeign- );- }-- #[test]- fn branch_is_not_deleted_while_its_worktree_exists() {- assert!(!branch_delete_allowed(true, true, true));- assert!(!branch_delete_allowed(false, false, false));- assert!(branch_delete_allowed(false, true, false));- assert!(branch_delete_allowed(false, false, true));- }-- #[test]- fn porcelain_parser_reads_locked_linked_trees() {- let entries = parse_worktree_porcelain(- "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\nworktree /repo/.graff/worktrees/a\nHEAD bbb\nbranch refs/heads/graff/agents/a\nlocked\n",- );- assert_eq!(entries.len(), 2);- assert_eq!(entries[1].branch, "refs/heads/graff/agents/a");- assert!(entries[1].locked);- assert!(!contained_elsewhere(- "refs/heads/graff/agents/a\n",- "refs/heads/graff/agents/a"- ));- assert!(contained_elsewhere(- "refs/heads/graff/agents/a\nrefs/heads/main\n",- "refs/heads/graff/agents/a"- ));- }-- #[test]- fn create_refuses_to_clobber_and_merge_back_refuses_a_dirty_base() {- let root = std::env::temp_dir().join(format!(- "codegraff-task-wt-{}",- uuid_nonce()- ));- fs::create_dir_all(&root).unwrap();- git_ok(&root, &["init", "-b", "main"]);- git_ok(&root, &["config", "user.email", "[email protected]"]);- git_ok(&root, &["config", "user.name", "test"]);- fs::write(root.join("readme.txt"), "base\n").unwrap();- git_ok(&root, &["add", "readme.txt"]);- git_ok(&root, &["commit", "-m", "base"]);-- let created = create_task_worktree(&root, Some("main"), "feature/task-one").unwrap();- assert!(created.path.join("readme.txt").is_file());- assert_eq!(created.base_branch, "main");- assert!(inspect(&created.path, &created.base_commit).keep == KeepReason::Removed);- update_from_base(&created.path, "main").unwrap();-- fs::write(created.path.join("task.txt"), "work\n").unwrap();- assert_eq!(- inspect(&created.path, &created.base_commit).keep,- KeepReason::Dirty- );- let failed = run_script(&created.path, "echo hi && false");- assert!(!failed.ok);- assert!(failed.output.contains("hi"));-- fs::write(root.join("readme.txt"), "dirty base\n").unwrap();- let merge_err = merge_back(&root, "feature/task-one").unwrap_err().to_string();- assert!(merge_err.contains("uncommitted"));- // The dirty base file is still the user's edit, not a reset.- assert_eq!(fs::read_to_string(root.join("readme.txt")).unwrap(), "dirty base\n");-- git_ok(&root, &["checkout", "--", "readme.txt"]);- git_ok(&created.path, &["add", "task.txt"]);- git_ok(&created.path, &["commit", "-m", "task"]);- assert_eq!(- inspect(&created.path, &created.base_commit).keep,- KeepReason::UniqueCommits- );- merge_back(&root, "feature/task-one").unwrap();- assert_eq!(- proven_merged_local(&root, "feature/task-one", "main"),- MergeProof::NotMerged,- "squash merge is not an ancestor; the branch itself is the proof of landing"- );- assert!(fs::read_to_string(root.join("task.txt")).unwrap().contains("work"));-- let review = review_diff(&created.path, "main").unwrap();- assert!(review.stat.contains("task.txt") || review.patch.contains("task"));-- assert!(branch_delete_allowed(true, true, true) == false);- remove_checkout(&created.path, false).unwrap();- assert!(branch_delete_allowed(false, true, false));- // Squash land is not `git branch -d` merged; confirmation uses -D.- assert!(delete_branch(&root, "feature/task-one", false).is_err());- delete_branch(&root, "feature/task-one", true).unwrap();- let _ = fs::remove_dir_all(&root);- }-- fn uuid_nonce() -> String {- use std::time::{SystemTime, UNIX_EPOCH};- format!(- "{}-{}",- std::process::id(),- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_nanos()- )- }-- fn git_ok(cwd: &Path, args: &[&str]) {- let output = git(cwd, args).unwrap();- assert!(- output.status.success(),- "git {args:?} failed: {}",- stderr_text(&output)- );- }-- #[test]- fn script_failure_is_visible() {- let root = std::env::temp_dir().join(format!("codegraff-task-script-{}", uuid_nonce()));- fs::create_dir_all(&root).unwrap();- let outcome = run_script(&root, "echo setup-failed >&2; exit 3");- assert!(!outcome.ok);- assert!(outcome.output.contains("setup-failed"));- let _ = fs::remove_dir_all(&root);- }-}+#[path = "task_workspace_tests.rs"]+mod tests;diff --git a/gui/src-tauri/src/task_workspace_git.rs b/gui/src-tauri/src/task_workspace_git.rsnew file mode 100644index 00000000..8c012640--- /dev/null+++ b/gui/src-tauri/src/task_workspace_git.rs@@ -0,0 +1,88 @@+use std::fs;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::thread;+use std::time::{Duration, Instant};++use anyhow::{Context, Result, bail};++pub(super) fn gh_merged_pr(repo: &Path, branch: &str) -> Option<bool> {+ let mut command = Command::new("gh");+ command+ .args([+ "pr",+ "list",+ "--head",+ branch,+ "--state",+ "merged",+ "--json",+ "number",+ "--limit",+ "1",+ ])+ .current_dir(repo)+ .env("GH_PROMPT_DISABLED", "1")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null());+ let text = run_timeout(&mut command, Duration::from_secs(3))?;+ if text.trim().is_empty() || text.trim() == "[]" {+ return Some(false);+ }+ Some(text.contains("\"number\""))+}++pub(super) fn run_timeout(command: &mut Command, timeout: Duration) -> Option<String> {+ let mut child = command.spawn().ok()?;+ let started = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(_)) => {+ let mut text = String::new();+ if let Some(mut stdout) = child.stdout.take() {+ let _ = stdout.read_to_string(&mut text);+ }+ let _ = child.wait();+ return Some(text);+ }+ Ok(None) if started.elapsed() > timeout => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ Ok(None) => thread::sleep(Duration::from_millis(40)),+ Err(_) => return None,+ }+ }+}++pub(super) fn resolve_dir(path: &Path) -> Result<PathBuf> {+ fs::canonicalize(path).with_context(|| format!("workspace not found: {}", path.display()))+}++pub(super) fn git(cwd: &Path, args: &[&str]) -> Result<std::process::Output> {+ Command::new("git")+ .args(args)+ .current_dir(cwd)+ .stdin(Stdio::null())+ .output()+ .with_context(|| format!("failed to run git {}", args.join(" ")))+}++pub(super) fn git_stdout(cwd: &Path, args: &[&str]) -> Result<String> {+ let output = git(cwd, args)?;+ if !output.status.success() {+ bail!("{}", stderr_text(&output).trim());+ }+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())+}++pub(super) fn stderr_text(output: &std::process::Output) -> String {+ let mut text = String::from_utf8_lossy(&output.stderr).into_owned();+ if text.trim().is_empty() {+ text = String::from_utf8_lossy(&output.stdout).into_owned();+ }+ text+}diff --git a/gui/src-tauri/src/task_workspace_tests.rs b/gui/src-tauri/src/task_workspace_tests.rsnew file mode 100644index 00000000..18ec6477--- /dev/null+++ b/gui/src-tauri/src/task_workspace_tests.rs@@ -0,0 +1,232 @@+ use super::*;++ #[test]+ fn keep_reason_requires_proof_on_every_axis() {+ assert_eq!(+ keep_reason(true, "", "abc", "abc", false),+ KeepReason::Removed+ );+ assert_eq!(+ keep_reason(true, "", "def", "abc", true),+ KeepReason::Removed+ );+ assert_eq!(+ keep_reason(true, " M src/a.rs\n", "abc", "abc", true),+ KeepReason::Dirty+ );+ assert_eq!(+ keep_reason(true, "?? new.rs\n", "abc", "abc", true),+ KeepReason::Dirty+ );+ assert_eq!(+ keep_reason(true, "", "def", "abc", false),+ KeepReason::UniqueCommits+ );+ assert_eq!(+ keep_reason(false, "", "abc", "abc", true),+ KeepReason::Unverifiable+ );+ assert_eq!(+ keep_reason(true, "", "", "abc", true),+ KeepReason::Unverifiable+ );+ }++ #[test]+ fn reap_keeps_main_release_session_and_dirty_agent_trees() {+ assert_eq!(+ reap_verdict(true, false, false, true, "/repo", "main", KeepReason::Removed),+ ReapVerdict::KeepMain+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ true,+ true,+ "/repo/.graff/worktrees/rel",+ "release/v1",+ KeepReason::Removed+ ),+ ReapVerdict::KeepLocked+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ false,+ false,+ "/repo/.graff/worktrees/rel",+ "hotfix/urgent",+ KeepReason::Removed+ ),+ ReapVerdict::KeepRelease+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ false,+ false,+ "/repo/.graff/worktrees/session-1",+ "worktree-session-1",+ KeepReason::Removed+ ),+ ReapVerdict::KeepSession+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ false,+ false,+ "/repo/.graff/worktrees/agent-1",+ "graff/agents/sa-1",+ KeepReason::Dirty+ ),+ ReapVerdict::KeepDirty+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ false,+ false,+ "/repo/.graff/worktrees/agent-1",+ "graff/agents/sa-1",+ KeepReason::Removed+ ),+ ReapVerdict::Remove+ );+ assert_eq!(+ reap_verdict(+ false,+ false,+ false,+ false,+ "/repo/.worktrees/mine",+ "feature/mine",+ KeepReason::Removed+ ),+ ReapVerdict::KeepForeign+ );+ }++ #[test]+ fn branch_is_not_deleted_while_its_worktree_exists() {+ assert!(!branch_delete_allowed(true, true, true));+ assert!(!branch_delete_allowed(false, false, false));+ assert!(branch_delete_allowed(false, true, false));+ assert!(branch_delete_allowed(false, false, true));+ }++ #[test]+ fn porcelain_parser_reads_locked_linked_trees() {+ let entries = parse_worktree_porcelain(+ "worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\nworktree /repo/.graff/worktrees/a\nHEAD bbb\nbranch refs/heads/graff/agents/a\nlocked\n",+ );+ assert_eq!(entries.len(), 2);+ assert_eq!(entries[1].branch, "refs/heads/graff/agents/a");+ assert!(entries[1].locked);+ assert!(!contained_elsewhere(+ "refs/heads/graff/agents/a\n",+ "refs/heads/graff/agents/a"+ ));+ assert!(contained_elsewhere(+ "refs/heads/graff/agents/a\nrefs/heads/main\n",+ "refs/heads/graff/agents/a"+ ));+ }++ #[test]+ fn create_refuses_to_clobber_and_merge_back_refuses_a_dirty_base() {+ let root = std::env::temp_dir().join(format!(+ "codegraff-task-wt-{}",+ uuid_nonce()+ ));+ fs::create_dir_all(&root).unwrap();+ git_ok(&root, &["init", "-b", "main"]);+ git_ok(&root, &["config", "user.email", "[email protected]"]);+ git_ok(&root, &["config", "user.name", "test"]);+ fs::write(root.join("readme.txt"), "base\n").unwrap();+ git_ok(&root, &["add", "readme.txt"]);+ git_ok(&root, &["commit", "-m", "base"]);++ let created = create_task_worktree(&root, Some("main"), "feature/task-one").unwrap();+ assert!(created.path.join("readme.txt").is_file());+ assert_eq!(created.base_branch, "main");+ assert!(inspect(&created.path, &created.base_commit).keep == KeepReason::Removed);+ update_from_base(&created.path, "main").unwrap();++ fs::write(created.path.join("task.txt"), "work\n").unwrap();+ assert_eq!(+ inspect(&created.path, &created.base_commit).keep,+ KeepReason::Dirty+ );+ let failed = run_script(&created.path, "echo hi && false");+ assert!(!failed.ok);+ assert!(failed.output.contains("hi"));++ fs::write(root.join("readme.txt"), "dirty base\n").unwrap();+ let merge_err = merge_back(&root, "feature/task-one").unwrap_err().to_string();+ assert!(merge_err.contains("uncommitted"));+ // The dirty base file is still the user's edit, not a reset.+ assert_eq!(fs::read_to_string(root.join("readme.txt")).unwrap(), "dirty base\n");++ git_ok(&root, &["checkout", "--", "readme.txt"]);+ git_ok(&created.path, &["add", "task.txt"]);+ git_ok(&created.path, &["commit", "-m", "task"]);+ assert_eq!(+ inspect(&created.path, &created.base_commit).keep,+ KeepReason::UniqueCommits+ );+ merge_back(&root, "feature/task-one").unwrap();+ assert_eq!(+ proven_merged_local(&root, "feature/task-one", "main"),+ MergeProof::NotMerged,+ "squash merge is not an ancestor; the branch itself is the proof of landing"+ );+ assert!(fs::read_to_string(root.join("task.txt")).unwrap().contains("work"));++ let review = review_diff(&created.path, "main").unwrap();+ assert!(review.stat.contains("task.txt") || review.patch.contains("task"));++ assert!(branch_delete_allowed(true, true, true) == false);+ remove_checkout(&created.path, false).unwrap();+ assert!(branch_delete_allowed(false, true, false));+ // Squash land is not `git branch -d` merged; confirmation uses -D.+ assert!(delete_branch(&root, "feature/task-one", false).is_err());+ delete_branch(&root, "feature/task-one", true).unwrap();+ let _ = fs::remove_dir_all(&root);+ }++ fn uuid_nonce() -> String {+ use std::time::{SystemTime, UNIX_EPOCH};+ format!(+ "{}-{}",+ std::process::id(),+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ )+ }++ fn git_ok(cwd: &Path, args: &[&str]) {+ let output = git(cwd, args).unwrap();+ assert!(+ output.status.success(),+ "git {args:?} failed: {}",+ stderr_text(&output)+ );+ }++ #[test]+ fn script_failure_is_visible() {+ let root = std::env::temp_dir().join(format!("codegraff-task-script-{}", uuid_nonce()));+ fs::create_dir_all(&root).unwrap();+ let outcome = run_script(&root, "echo setup-failed >&2; exit 3");+ assert!(!outcome.ok);+ assert!(outcome.output.contains("setup-failed"));+ let _ = fs::remove_dir_all(&root);+ }diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex abb85a86..7e1835d4 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -451,6 +451,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constextra_owned = extra.len > 0;} else {const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);+ @import("worktree_reap.zig").reapAfterTask(gpa, ctx.io);if (outcome.kept) {extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept ({s}) — path: {s}, branch: {s}; finish is not archive — do not spawn a cleanup child]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";extra_owned = extra.len > 0;diff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zigindex 493ddf16..081915b7 100644--- a/src/worktree_cmd.zig+++ b/src/worktree_cmd.zig@@ -246,6 +246,14 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [}if (std.mem.eql(u8, action, "prune")) {+ // `unused` is the explicit stale-checkout sweep (#1118). Bare prune+ // still only drops registrations unless an age window is named.+ if (args.len > 1 and std.mem.eql(u8, args[1], "unused")) {+ const n = @import("worktree_reap.zig").orphans(gpa, io, arena, ".");+ const m = @import("worktree_reap.zig").mergedPulls(gpa, io, arena, ".");+ try out.print("✓ swept unused worktrees — removed {d} idle session tree(s), {d} merged-PR tree(s)\n", .{ n, m });+ return;+ }// Drops git's registrations for worktrees whose dirs were deleted out of// band, and with `older-than <days>` the stale DIRECTORIES too (#112).return worktree_prune.pruneCommand(gpa, io, arena, out, args[1..]);@@ -256,4 +264,5 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [test { // split-out module: unreferenced, its tests silently never run_ = worktree_prune;+ _ = @import("worktree_reap.zig");}diff --git a/src/worktree_reap.zig b/src/worktree_reap.zigindex 853bb549..59953661 100644--- a/src/worktree_reap.zig+++ b/src/worktree_reap.zig@@ -82,6 +82,14 @@ pub fn orphans(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) usizereturn removed;}+/// After an agent task: drop stale registrations and dead session checkouts.+/// Named task workspaces stay; this does not archive them.+pub fn reapAfterTask(gpa: Allocator, io: Io) void {+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ _ = orphans(gpa, io, arena_state.allocator(), ".");+}+fn prMerged(gpa: Allocator, io: Io, cwd: []const u8, branch: []const u8) bool {const name = prune.shortBranch(branch);const r = process_runner.runCappedWithOptions(gpa, io, &.{ "gh", "pr", "view", name, "--json", "state", "-q", ".state" }, 4096, 4096, 20_000, .{ .cwd = .{ .path = cwd } }) catch return false;