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

feat(cos): add pre-task git pull to ensure agents work on latest code

Adam Eivy706b7a91a88c
diff --git a/.changelog/v1.18.x.md b/.changelog/v1.18.x.md
index 14fd66eb08..9d2030fcb2 100644
--- a/.changelog/v1.18.x.md
+++ b/.changelog/v1.18.x.md
@@ -10,3 +10,4 @@ UX and autonomy improvements for CoS dashboard and autonomous jobs.
- **GSD tab info section** — added explanatory note to the GSD dashboard describing what it monitors and how to use GSD commands
- **Moltworld script-based execution** — converted moltworld exploration job from AI agent to standalone script handler, reducing resource usage and removing unnecessary agent spawning
+- **Pre-task git pull** — agents now automatically pull the latest code from origin before starting work on any project, ensuring they always work on the most recent version. If a merge conflict is detected, a high-priority conflict resolution task is created for an agent to handle before the original task retries
diff --git a/server/services/git.js b/server/services/git.js
index c3407f5915..2d01de1299 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -454,6 +454,104 @@ export function hasChangelogDir(dir) {
return existsSync(join(dir, '.changelog'));
}
+/**
+ * Ensure workspace has the latest code from origin before agent work begins.
+ * Scripted pull: fetch + fast-forward merge on the dev/default branch.
+ * If the working tree is dirty, stashes changes first and restores after.
+ * Returns conflict info if the pull can't be completed cleanly.
+ *
+ * @param {string} dir - Git repository directory
+ * @returns {{ success: boolean, branch: string, stashed: boolean, conflict: boolean, error: string|null }}
+ */
+export async function ensureLatest(dir) {
+ const gitCheck = await isRepo(dir).catch(() => false);
+ if (!gitCheck) return { success: true, branch: null, stashed: false, conflict: false, error: null, skipped: 'not-a-repo' };
+
+ const currentBranch = await getBranch(dir).catch(() => null);
+ if (!currentBranch) return { success: true, branch: null, stashed: false, conflict: false, error: null, skipped: 'no-branch' };
+
+ // Check for remote — no remote means nothing to pull
+ const remote = await getRemote(dir).catch(() => null);
+ if (!remote?.origin) return { success: true, branch: currentBranch, stashed: false, conflict: false, error: null, skipped: 'no-remote' };
+
+ // Fetch latest refs from origin
+ const fetchResult = await execGit(['fetch', 'origin'], dir, { ignoreExitCode: true });
+ if (fetchResult.stderr?.includes('fatal')) {
+ return { success: false, branch: currentBranch, stashed: false, conflict: false, error: `fetch failed: ${fetchResult.stderr}` };
+ }
+
+ // Check if remote tracking branch exists
+ const remoteRef = await execGit(['rev-parse', `origin/${currentBranch}`], dir, { ignoreExitCode: true });
+ if (remoteRef.stderr?.includes('unknown revision')) {
+ return { success: true, branch: currentBranch, stashed: false, conflict: false, error: null, skipped: 'no-remote-tracking' };
+ }
+
+ // Check if already up to date
+ const localHead = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();
+ const remoteHead = remoteRef.stdout.trim();
+ if (localHead === remoteHead) {
+ return { success: true, branch: currentBranch, stashed: false, conflict: false, error: null, upToDate: true };
+ }
+
+ // Stash dirty working tree if needed
+ const status = await getStatus(dir).catch(() => ({ clean: true }));
+ let stashed = false;
+ if (!status.clean) {
+ await execGit(['stash', 'push', '-m', 'cos-pre-task-autostash'], dir);
+ stashed = true;
+ }
+
+ // Try fast-forward merge first (safest — no rewrite)
+ const mergeResult = await execGit(['merge', '--ff-only', `origin/${currentBranch}`], dir, { ignoreExitCode: true });
+ const mergeOk = !mergeResult.stderr?.includes('fatal') && !mergeResult.stderr?.includes('Not possible to fast-forward');
+
+ if (mergeOk) {
+ // Fast-forward succeeded
+ if (stashed) {
+ const popResult = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ const popOk = !popResult.stderr?.includes('CONFLICT');
+ if (!popOk) {
+ // Stash pop conflict — abort and report
+ await execGit(['checkout', '--', '.'], dir, { ignoreExitCode: true });
+ await execGit(['stash', 'drop'], dir, { ignoreExitCode: true });
+ return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after fast-forward: ${popResult.stderr}` };
+ }
+ }
+ return { success: true, branch: currentBranch, stashed, conflict: false, error: null };
+ }
+
+ // Fast-forward failed — local branch has diverged. Try rebase.
+ const rebaseResult = await execGit(['rebase', `origin/${currentBranch}`], dir, { ignoreExitCode: true });
+ const rebaseOk = !rebaseResult.stderr?.includes('CONFLICT') && !rebaseResult.stderr?.includes('error:');
+
+ if (!rebaseOk) {
+ // Rebase failed — abort and report conflict
+ await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true });
+ if (stashed) {
+ await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ }
+ return {
+ success: false,
+ branch: currentBranch,
+ stashed,
+ conflict: true,
+ error: `branch ${currentBranch} has diverged from origin and rebase has conflicts: ${rebaseResult.stderr}`
+ };
+ }
+
+ // Rebase succeeded
+ if (stashed) {
+ const popResult = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ if (popResult.stderr?.includes('CONFLICT')) {
+ await execGit(['checkout', '--', '.'], dir, { ignoreExitCode: true });
+ await execGit(['stash', 'drop'], dir, { ignoreExitCode: true });
+ return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after rebase: ${popResult.stderr}` };
+ }
+ }
+
+ return { success: true, branch: currentBranch, stashed, conflict: false, error: null };
+}
+
/**
* Get comprehensive git info
*/
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 63855001e1..147da993a7 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -1365,6 +1365,51 @@ export async function spawnAgentForTask(task) {
? (await getAppById(task.metadata.app).catch(() => null))?.name || null
: null;
+ // Pull latest from git before starting work (scripted — no LLM needed)
+ const pullResult = await git.ensureLatest(workspacePath).catch(err => {
+ emitLog('warning', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });
+ return { success: false, error: err.message };
+ });
+
+ if (pullResult.skipped) {
+ emitLog('debug', `Pre-task git pull skipped: ${pullResult.skipped}`, { taskId: task.id, workspace: workspacePath });
+ } else if (pullResult.conflict) {
+ // Git conflict detected — create a high-priority task for an agent to resolve it,
+ // then defer the original task so it retries after the conflict is fixed.
+ emitLog('warning', `🔀 Git conflict in ${workspacePath} (branch: ${pullResult.branch}): ${pullResult.error}`, {
+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch
+ });
+
+ const appId = task.metadata?.app || null;
+ const conflictDesc = `Resolve git conflict in ${resolvedAppName || workspacePath} on branch ${pullResult.branch}. `
+ + `The branch has diverged from origin and automatic rebase failed. `
+ + `Error: ${pullResult.error}`;
+
+ await addTask({
+ description: conflictDesc,
+ priority: 'HIGH',
+ app: appId,
+ context: `This conflict is blocking task ${task.id}: "${task.description}". `
+ + `Resolve the conflict, commit, and push so the blocked task can proceed.`,
+ position: 'top'
+ }, 'internal').catch(err => {
+ emitLog('warning', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });
+ });
+
+ // Return the original task to pending so it retries after the conflict is resolved
+ await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});
+ cleanupOnError(`Git conflict blocks task — conflict resolution task created`);
+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'git-conflict', branch: pullResult.branch });
+ return null;
+ } else if (pullResult.success && !pullResult.upToDate && !pullResult.skipped) {
+ emitLog('info', `📥 Pulled latest for ${resolvedAppName || 'workspace'} (branch: ${pullResult.branch})`, {
+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch, stashed: pullResult.stashed
+ });
+ } else if (!pullResult.success) {
+ // Non-conflict failure (network error, etc.) — log warning but proceed
+ emitLog('warning', `⚠️ Pre-task git pull error: ${pullResult.error}`, { taskId: task.id, workspace: workspacePath });
+ }
+
// JIRA integration: create ticket + feature branch if app has JIRA enabled and task opted in
let jiraTicket = null;
let jiraBranchName = null;