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: isolate CoS agents on managed apps from cross-agent git contamination

Adam Eivy8518679c41aa
diff --git a/.changelog/v0.17.x.md b/.changelog/v0.17.x.md
index c0f07ff6a6..5466db798a 100644
--- a/.changelog/v0.17.x.md
+++ b/.changelog/v0.17.x.md
@@ -19,6 +19,12 @@ JIRA integration improvements and token lifecycle management.
- **`--delete`** deletes a ticket directly from the CLI
- **`getTransitions()` and `deleteTicket()`** added to the JIRA service and routes for programmatic use
+### CoS agent git isolation for managed apps
+- **Managed app tasks always get an isolated worktree** based on the latest `origin/main` (or `origin/master`) — prevents cross-agent contamination from dirty state, stale branches, or other agents' uncommitted changes
+- **Worktrees now fetch + base off the remote default branch** instead of whatever `HEAD` happens to be locally — agents start from a known-clean state
+- **JIRA feature branches** also start from the latest default branch when working on managed apps
+- **Agent prompt includes explicit git hygiene rules** — verify clean working tree before starting, stage only specific files (never `git add .`), and refuse to commit or PR unrelated changes
+
## Improvements
### CityHud scan line: CSS animation instead of setInterval
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 9054418507..a39627a178 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -1292,6 +1292,17 @@ export async function spawnAgentForTask(task) {
.substring(0, 40);
jiraBranchName = `feature/${jiraTicket.ticketId}-${slug}`;
+ // For managed apps, ensure we start from the latest default branch
+ if (task.metadata?.app) {
+ await git.fetchOrigin(workspacePath).catch(() => {});
+ const { baseBranch: defaultBranch } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
+ if (defaultBranch) {
+ await git.checkout(workspacePath, defaultBranch).catch(() => {});
+ // Fast-forward to latest origin
+ try { execSync(`git merge --ff-only origin/${defaultBranch}`, { cwd: workspacePath, stdio: 'ignore' }); } catch {};
+ }
+ }
+
await git.createBranch(workspacePath, jiraBranchName).catch(err => {
emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });
jiraBranchName = null;
@@ -1313,10 +1324,34 @@ export async function spawnAgentForTask(task) {
}
}
- // Check for conflicts with active agents and decide on worktree usage
- // Skip worktree conflict detection if we already created a JIRA feature branch (agent is isolated)
+ // Ensure clean workspace for managed apps before agent starts.
+ // For managed apps, always use a worktree based on the latest default branch
+ // to prevent cross-agent contamination (dirty state, stale branches, other agents' commits).
let worktreeInfo = null;
- if (!jiraBranchName) {
+ const isManagedApp = !!task.metadata?.app;
+
+ if (isManagedApp && !jiraBranchName) {
+ // Managed apps always get an isolated worktree based on the latest default branch
+ const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
+ emitLog('info', `🌳 Managed app task ${task.id} — creating isolated worktree from ${detectedBase || 'default branch'}`, {
+ taskId: task.id, app: task.metadata.app, baseBranch: detectedBase
+ });
+
+ worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {
+ baseBranch: detectedBase || undefined
+ }).catch(err => {
+ emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
+ return null;
+ });
+
+ if (worktreeInfo) {
+ workspacePath = worktreeInfo.worktreePath;
+ emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName} (base: ${worktreeInfo.baseBranch})`, {
+ agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch
+ });
+ }
+ } else if (!jiraBranchName) {
+ // Non-managed (PortOS) tasks: use worktree only when conflict is detected
const { getAgents } = await import('./cos.js');
const allAgents = await getAgents();
const runningAgents = allAgents.filter(a => a.status === 'running');
@@ -2308,6 +2343,7 @@ async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null)
You are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.
- **Branch**: \`${worktreeInfo.branchName}\`
- **Worktree Path**: \`${worktreeInfo.worktreePath}\`
+${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}
**Important**: Commit your changes to this branch. Your commits will be automatically merged back to the main development branch when your task completes. Do NOT manually switch branches or modify the worktree configuration.
` : '';
@@ -2387,6 +2423,12 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}
- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only
${task.metadata?.app ? `- **When done, create a pull request to the repo's default branch** (main/master) instead of committing directly to dev. Use the /pr skill or gh CLI to open the PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}
+## Git Hygiene (CRITICAL)
+- **Before starting work**, run \`git status\` to verify a clean working tree. If there are uncommitted changes from a previous agent or manual work, **stash or discard them** before proceeding — do NOT commit someone else's changes.
+- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.
+- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.
+- If the working tree is dirty with changes unrelated to your task, run \`git stash\` to set them aside before starting.
+
## Working Directory
You are working in the project directory. Use the available tools to explore, modify, and test code.
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index d770029847..fad01092d8 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -46,12 +46,17 @@ function execGit(args, cwd) {
* Creates a new branch and worktree directory that the agent can work in
* without disturbing the main workspace.
*
+ * For managed apps, the worktree is based on the latest remote default branch
+ * (main/master) to ensure a clean starting point free from other agents' changes.
+ *
* @param {string} agentId - The agent identifier (used for branch/directory naming)
* @param {string} sourceWorkspace - The original git repository path
* @param {string} taskId - Task identifier (included in branch name for traceability)
- * @returns {{ worktreePath: string, branchName: string }} paths for the new worktree
+ * @param {object} options - Optional configuration
+ * @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)
+ * @returns {{ worktreePath: string, branchName: string, baseBranch: string }} paths for the new worktree
*/
-export async function createWorktree(agentId, sourceWorkspace, taskId) {
+export async function createWorktree(agentId, sourceWorkspace, taskId, options = {}) {
if (!existsSync(WORKTREES_DIR)) {
await mkdir(WORKTREES_DIR, { recursive: true });
}
@@ -59,18 +64,34 @@ export async function createWorktree(agentId, sourceWorkspace, taskId) {
const branchName = `cos/${taskId}/${agentId}`;
const worktreePath = join(WORKTREES_DIR, agentId);
- // Get the current branch to base the worktree on
- const currentBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace)).trim();
+ // Fetch latest from origin so we base off up-to-date refs
+ await execGit(['fetch', 'origin'], sourceWorkspace).catch(err => {
+ console.log(`⚠️ Worktree fetch failed (will use local refs): ${err.message}`);
+ });
+
+ // Determine the base: explicit option > detected default branch > current HEAD
+ let baseBranch = options.baseBranch;
+ if (!baseBranch) {
+ const branches = (await execGit(['branch', '--list'], sourceWorkspace)).trim();
+ if (branches.includes('main')) baseBranch = 'main';
+ else if (branches.includes('master')) baseBranch = 'master';
+ else baseBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace)).trim();
+ }
+
+ // Prefer the remote ref (freshest state) if available
+ const baseRef = await execGit(['rev-parse', `origin/${baseBranch}`], sourceWorkspace)
+ .then(() => `origin/${baseBranch}`)
+ .catch(() => baseBranch);
- // Create worktree with a new branch based on current HEAD
+ // Create worktree with a new branch based on the latest default branch
await execGit(
- ['worktree', 'add', '-b', branchName, worktreePath, currentBranch],
+ ['worktree', 'add', '-b', branchName, worktreePath, baseRef],
sourceWorkspace
);
- console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName})`);
+ console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);
- return { worktreePath, branchName };
+ return { worktreePath, branchName, baseBranch };
}
/**