Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: prevent worktree cleanup from discarding uncommitted agent work

Adam Eivyac0ef97c6048
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 84d66b8c37..a4c492bb7f 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -14,7 +14,11 @@ import {
ThumbsDown,
MessageSquare,
ExternalLink,
- Send
+ Send,
+ GitBranch,
+ GitPullRequest,
+ Sparkles,
+ RefreshCw
} from 'lucide-react';
import * as api from '../../../services/api';
import OutputBlocks from '../OutputBlocks';
@@ -461,6 +465,48 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</div>
)}
+ {/* Agent configuration badges */}
+ {(agent.metadata?.configUseWorktree || agent.metadata?.configOpenPR || agent.metadata?.configSimplify || agent.metadata?.configReviewLoop || agent.metadata?.configCodingOnMain) && (
+ <div className="flex items-center gap-1.5 flex-wrap mb-2">
+ {agent.metadata.configUseWorktree && (
+ <span className={`flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded ${
+ agent.metadata.configWorktreeAutoDetected ? 'bg-orange-500/15 text-orange-400' : 'bg-teal-500/15 text-teal-400'
+ }`} title={`Worktree: ${agent.metadata.worktreeBranch || 'unknown'}${agent.metadata.configWorktreeAutoDetected ? ' (auto-detected conflict)' : ''}`}>
+ <GitBranch size={10} aria-hidden="true" />
+ {agent.metadata.configWorktreeAutoDetected ? 'Auto-WT' : 'Worktree'}
+ </span>
+ )}
+ {agent.metadata.configCodingOnMain && !agent.metadata.configUseWorktree && (
+ <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-yellow-500/15 text-yellow-500"
+ title="Agent is coding directly on main branch">
+ <GitBranch size={10} aria-hidden="true" />
+ main
+ </span>
+ )}
+ {agent.metadata.configOpenPR && (
+ <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-purple-500/15 text-purple-400"
+ title="Will open a PR when done">
+ <GitPullRequest size={10} aria-hidden="true" />
+ PR
+ </span>
+ )}
+ {agent.metadata.configSimplify && (
+ <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-emerald-500/15 text-emerald-400"
+ title="Will run /simplify before committing">
+ <Sparkles size={10} aria-hidden="true" />
+ Simplify
+ </span>
+ )}
+ {agent.metadata.configReviewLoop && (
+ <span className="flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded bg-indigo-500/15 text-indigo-400"
+ title="Review loop enabled — agent will iterate on PR feedback">
+ <RefreshCw size={10} aria-hidden="true" />
+ Review
+ </span>
+ )}
+ </div>
+ )}
+
{/* Live activity feed for running agents */}
{!completed && recentActivity.length > 0 && (
<div className="text-xs font-mono bg-port-bg/50 px-2 py-1.5 rounded space-y-0.5">
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 9b33e01fda..418233a1e3 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -1638,7 +1638,14 @@ export async function spawnAgentForTask(task) {
jiraTicketUrl: task.metadata?.jiraTicketUrl || null,
jiraBranch: task.metadata?.jiraBranch || null,
jiraInstanceId: task.metadata?.jiraInstanceId || null,
- jiraCreatePR: task.metadata?.jiraCreatePR ?? null
+ jiraCreatePR: task.metadata?.jiraCreatePR ?? null,
+ // Agent configuration flags (visible in UI)
+ configOpenPR: isTruthyMeta(task.metadata?.openPR),
+ configSimplify: isTruthyMeta(task.metadata?.simplify),
+ configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),
+ configUseWorktree: !!worktreeInfo,
+ configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,
+ configCodingOnMain: !worktreeInfo && !jiraBranchName
});
emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 8b7b7b0a01..069bbad1ce 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -109,7 +109,26 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
if (!existsSync(worktreePath)) {
console.log(`🌳 Worktree already removed for ${agentId}`);
- return { merged: false, removed: true };
+ return { merged: false, removed: true, uncommittedSaved: false };
+ }
+
+ // Safety check: detect uncommitted changes before removing the worktree
+ let uncommittedSaved = false;
+ const dirtyFiles = (await execGit(['status', '--porcelain'], worktreePath).catch(() => '')).trim();
+ if (dirtyFiles) {
+ console.log(`🌳 Worktree for ${agentId} has uncommitted changes — committing before cleanup`);
+ await execGit(['add', '-A'], worktreePath).catch(err => {
+ console.log(`⚠️ git add failed in worktree ${agentId}: ${err.message}`);
+ });
+ await execGit(
+ ['commit', '-m', `chore: save uncommitted agent work (auto-committed during worktree cleanup)\n\nAgent ${agentId} had uncommitted changes that would have been lost during worktree removal.`],
+ worktreePath
+ ).then(() => {
+ uncommittedSaved = true;
+ console.log(`🌳 Auto-committed uncommitted changes for ${agentId}`);
+ }).catch(err => {
+ console.log(`⚠️ Auto-commit failed for worktree ${agentId}: ${err.message}`);
+ });
}
let merged = false;
@@ -155,9 +174,9 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
console.log(`⚠️ Branch delete failed for ${branchName}: ${err.message}`);
});
- console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
+ console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}${uncommittedSaved ? ' (auto-committed)' : ''}`);
- return { merged, removed: true };
+ return { merged, removed: true, uncommittedSaved };
}
/**
@@ -295,7 +314,7 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
const agentId = wt.path.split('/').pop();
if (!activeAgentIds.has(agentId)) {
const branchName = wt.branch?.replace('refs/heads/', '') || '';
- await removeWorktree(agentId, sourceWorkspace, branchName, { merge: false })
+ await removeWorktree(agentId, sourceWorkspace, branchName, { merge: true })
.catch(err => {
console.log(`⚠️ Failed to clean orphaned worktree ${agentId}: ${err.message}`);
});
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index bcf5a1a5e1..526bd17699 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -138,6 +138,37 @@ describe('Persistent Worktree Path Construction', () => {
});
});
+describe('Uncommitted Changes Detection', () => {
+ // Mirrors the dirty-file detection logic in removeWorktree
+ function hasDirtyFiles(porcelainOutput) {
+ return porcelainOutput.trim().length > 0;
+ }
+
+ it('should detect modified files as dirty', () => {
+ expect(hasDirtyFiles(' M src/index.js')).toBe(true);
+ });
+
+ it('should detect untracked files as dirty', () => {
+ expect(hasDirtyFiles('?? newfile.js')).toBe(true);
+ });
+
+ it('should detect staged files as dirty', () => {
+ expect(hasDirtyFiles('A newfile.js')).toBe(true);
+ });
+
+ it('should detect multiple dirty files', () => {
+ expect(hasDirtyFiles(' M src/a.js\n M src/b.js\n?? src/c.js')).toBe(true);
+ });
+
+ it('should return false for clean worktree', () => {
+ expect(hasDirtyFiles('')).toBe(false);
+ });
+
+ it('should return false for whitespace-only output', () => {
+ expect(hasDirtyFiles(' \n ')).toBe(false);
+ });
+});
+
describe('Orphaned Worktree Detection', () => {
function findOrphanedWorktrees(worktrees, worktreesDir, activeAgentIds) {
return worktrees.filter(wt => {