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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(cos): detect remote default branch instead of assuming main (#207)
[._.]/ Adam Eivy6d49e2aa247c
diff --git a/server/routes/git.js b/server/routes/git.jsindex 7b51875143..16b0681465 100644--- a/server/routes/git.js+++ b/server/routes/git.js@@ -151,7 +151,8 @@ router.post('/branch-comparison', asyncHandler(async (req, res) => {throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });}- const result = await git.getBranchComparison(path, base || 'main', head || 'dev');+ const baseBranch = base || await git.getDefaultBranch(path, { allowRemote: false }).catch(() => null) || 'main';+ const result = await git.getBranchComparison(path, baseBranch, head || 'dev');res.json(result);}));diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex aa4bcae597..1c133cdcdf 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1154,9 +1154,13 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r]);if (pushResult) {- const targetBranch = branchInfo.baseBranch || 'main';+ let targetBranch = branchInfo.baseBranch;+ if (!targetBranch) {+ targetBranch = await git.getDefaultBranch(sourceWorkspace, { allowRemote: false }).catch(() => null) || 'main';+ }const taskDesc = description || 'CoS automated task';- const prTitle = taskDesc.replace(/[\r\n]+/g, ' ').trim().substring(0, 100);+ const firstLine = taskDesc.split(/[\r\n]/).find(l => l.trim()) || taskDesc;+ const prTitle = firstLine.trim().substring(0, 100) || 'CoS automated task';const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput);@@ -1265,15 +1269,16 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appconst appId = task?.metadata?.app;if (isMergeFail) {+ const defaultBr = await git.getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';addTask({description: `${RECOVERY_TASK_PREFIX} Resolve merge conflict and clean up stale branch ${staleBranch} in ${appName}`,priority: 'HIGH',app: appId,isRecovery: true,- context: `An agent failed to auto-merge branch "${staleBranch}" back to main in ${sourceWorkspace}. `- + `Resolve this by: (1) checking if the branch's changes are already on main (superseded by other commits), `+ context: `An agent failed to auto-merge branch "${staleBranch}" back to ${defaultBr} in ${sourceWorkspace}. `+ + `Resolve this by: (1) checking if the branch's changes are already on ${defaultBr} (superseded by other commits), `+ `and if so, delete the branch with "git branch -D ${staleBranch}"; `- + `(2) if the changes are NOT on main, attempt "git merge ${staleBranch} --no-edit" from main, resolve any conflicts, and commit; `+ + `(2) if the changes are NOT on ${defaultBr}, attempt "git merge ${staleBranch} --no-edit" from ${defaultBr}, resolve any conflicts, and commit; `+ `(3) after merging or determining the branch is stale, delete it with "git branch -D ${staleBranch}". `+ `Original agent: ${agentId}, original task: ${task?.description || 'unknown'}.`,useWorktree: false,@@ -1285,15 +1290,19 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, app// PR/MR creation failed — spawn an agent to investigate and retry. Pick gh vs// glab based on the repo's forge so the recovery agent gets commands that// actually work against this remote.- const { cli } = await git.resolveForgeForRepo(sourceWorkspace).catch(() => ({ cli: 'gh' }));+ const [{ cli }, detectedBase] = await Promise.all([+ git.resolveForgeForRepo(sourceWorkspace).catch(() => ({ cli: 'gh' })),+ git.getDefaultBranch(sourceWorkspace).catch(() => null)+ ]);+ const targetBase = detectedBase || 'main';const isGitLab = cli === 'glab';const reqWord = isGitLab ? 'MR' : 'PR';const listCmd = isGitLab? `glab mr list --source-branch ${staleBranch}`: `gh pr list --head ${staleBranch}`;const createCmd = isGitLab- ? `glab mr create --source-branch ${staleBranch} --target-branch main --title '...' --description '...'`- : `gh pr create --head ${staleBranch} --base main --title '...' --body '...'`;+ ? `glab mr create --source-branch ${staleBranch} --target-branch ${targetBase} --title '...' --description '...'`+ : `gh pr create --head ${staleBranch} --base ${targetBase} --title '...' --body '...'`;addTask({description: `${RECOVERY_TASK_PREFIX} Investigate and retry failed ${reqWord} for branch ${staleBranch} in ${appName}`,@@ -1303,7 +1312,7 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appcontext: `An agent pushed branch "${staleBranch}" to ${sourceWorkspace} but automated ${reqWord} creation failed. `+ `Investigate by: (1) checking if a ${reqWord} already exists for this branch: "${listCmd}"; `+ `(2) if no ${reqWord} exists, review the branch changes and create one: "${createCmd}"; `- + `(3) if the branch is stale or changes are already on main, delete the remote branch: "git push origin --delete ${staleBranch}". `+ + `(3) if the branch is stale or changes are already on ${targetBase}, delete the remote branch: "git push origin --delete ${staleBranch}". `+ `Original agent: ${agentId}, original task: ${task?.description || 'unknown'}.`,useWorktree: false,}, 'user').catch(err => {diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 2fe5f89358..c0f5e58840 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -156,6 +156,7 @@ vi.mock('./jira.js', () => ({vi.mock('./git.js', () => ({push: vi.fn(),getRepoBranches: vi.fn(),+ getDefaultBranch: vi.fn().mockResolvedValue('main'),createPR: vi.fn(),generatePRDescription: vi.fn(),deleteBranch: vi.fn().mockResolvedValue(undefined),@@ -337,6 +338,18 @@ describe('cleanupAgentWorktree - openPR path', () => {}));});+ it('should use only first line of multiline description for PR title', async () => {+ const multilineDesc = '[Improvement: grace] Error Handling\n\nAnalyze the codebase:\n\nRepository: /Users/foo/grace';+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/7' });++ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: multilineDesc });++ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({+ title: '[Improvement: grace] Error Handling'+ }));+ });+it('should use default description when none provided', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/6' });diff --git a/server/services/getDefaultBranch.test.js b/server/services/getDefaultBranch.test.jsnew file mode 100644index 0000000000..0677965f8b--- /dev/null+++ b/server/services/getDefaultBranch.test.js@@ -0,0 +1,145 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../lib/execGit.js', () => ({+ execGit: vi.fn()+}));++describe('getDefaultBranch', () => {+ let getDefaultBranch;+ let execGit;++ beforeEach(async () => {+ const execGitModule = await import('../lib/execGit.js');+ execGit = execGitModule.execGit;+ const gitModule = await import('./git.js');+ getDefaultBranch = gitModule.getDefaultBranch;+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('returns branch from origin/HEAD when available', async () => {+ execGit.mockImplementation((args) => {+ if (args[0] === 'symbolic-ref' && args.includes('refs/remotes/origin/HEAD')) {+ return Promise.resolve({ stdout: 'origin/main', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'rev-parse' && args.includes('--verify')) {+ return Promise.resolve({ stdout: 'abc123', stderr: '', exitCode: 0 });+ }+ return Promise.reject(new Error('unexpected'));+ });++ const result = await getDefaultBranch('/fake/dir');+ expect(result).toBe('main');+ });++ it('strips origin/ prefix from various branch names', async () => {+ execGit.mockImplementation((args) => {+ if (args[0] === 'symbolic-ref') {+ return Promise.resolve({ stdout: 'origin/develop', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'rev-parse' && args.includes('--verify')) {+ return Promise.resolve({ stdout: 'abc123', stderr: '', exitCode: 0 });+ }+ return Promise.reject(new Error('unexpected'));+ });++ const result = await getDefaultBranch('/fake/dir');+ expect(result).toBe('develop');+ });++ it('skips remote detection when allowRemote=false', async () => {+ const calls = [];+ execGit.mockImplementation((args) => {+ calls.push(args.join(' '));+ if (args[0] === 'symbolic-ref') {+ return Promise.reject(new Error('not set'));+ }+ if (args[0] === 'branch') {+ return Promise.resolve({ stdout: ' main\n dev\n', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'rev-parse') {+ return Promise.resolve({ stdout: 'main', stderr: '', exitCode: 0 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });++ const result = await getDefaultBranch('/fake/dir', { allowRemote: false });+ expect(result).toBe('main');+ expect(calls.some(c => c.includes('set-head'))).toBe(false);+ });++ it('attempts remote set-head when allowRemote=true and origin/HEAD unset', async () => {+ const calls = [];+ execGit.mockImplementation((args) => {+ calls.push(args.join(' '));+ if (args[0] === 'symbolic-ref') {+ // First call fails, second succeeds after set-head+ if (calls.filter(c => c.startsWith('symbolic-ref')).length === 1) {+ return Promise.reject(new Error('not set'));+ }+ return Promise.resolve({ stdout: 'origin/main', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'remote' && args.includes('set-head')) {+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });++ const result = await getDefaultBranch('/fake/dir', { allowRemote: true });+ expect(result).toBe('main');+ expect(calls.some(c => c.includes('set-head'))).toBe(true);+ });++ it('falls back to master when main not in branch list', async () => {+ execGit.mockImplementation((args) => {+ if (args[0] === 'symbolic-ref') {+ return Promise.reject(new Error('not set'));+ }+ if (args[0] === 'branch') {+ return Promise.resolve({ stdout: ' master\n feature/x\n', stderr: '', exitCode: 0 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });++ const result = await getDefaultBranch('/fake/dir', { allowRemote: false });+ expect(result).toBe('master');+ });++ it('falls back to current HEAD when no standard branches exist', async () => {+ execGit.mockImplementation((args) => {+ if (args[0] === 'symbolic-ref') {+ return Promise.reject(new Error('not set'));+ }+ if (args[0] === 'branch') {+ return Promise.resolve({ stdout: ' develop\n feature/x\n', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) {+ return Promise.resolve({ stdout: 'develop', stderr: '', exitCode: 0 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });++ const result = await getDefaultBranch('/fake/dir', { allowRemote: false });+ expect(result).toBe('develop');+ });++ it('returns null when all detection methods fail', async () => {+ execGit.mockImplementation((args) => {+ if (args[0] === 'symbolic-ref') {+ return Promise.reject(new Error('not set'));+ }+ if (args[0] === 'branch') {+ return Promise.resolve({ stdout: ' feature/x\n feature/y\n', stderr: '', exitCode: 0 });+ }+ if (args[0] === 'rev-parse') {+ return Promise.resolve({ stdout: 'HEAD', stderr: '', exitCode: 0 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });++ const result = await getDefaultBranch('/fake/dir', { allowRemote: false });+ expect(result).toBeNull();+ });+});diff --git a/server/services/git.js b/server/services/git.jsindex bb60bf79d0..c3275a1345 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -678,15 +678,71 @@ export function extractAgentSummary(output) {return summary;}+export async function getDefaultBranch(dir, { allowRemote = true } = {}) {+ const symRef = await execGitSafe(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], dir);+ if (symRef.stdout?.trim()) {+ const branch = symRef.stdout.trim().replace(/^origin\//, '');+ // Verify the ref actually exists (origin/HEAD could be stale)+ const verify = await execGitSafe(['rev-parse', '--verify', `refs/remotes/origin/${branch}`], dir);+ if (verify.exitCode === 0 || verify.stdout?.trim()) return branch;+ }++ // origin/HEAD not set locally — ask the remote (best-effort, short timeout)+ if (allowRemote) {+ await execGitSafe(['remote', 'set-head', 'origin', '--auto'], dir, { timeout: 5000 });+ const symRef2 = await execGitSafe(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], dir);+ if (symRef2.stdout?.trim()) {+ const branch2 = symRef2.stdout.trim().replace(/^origin\//, '');+ const verify2 = await execGitSafe(['rev-parse', '--verify', `refs/remotes/origin/${branch2}`], dir);+ if (verify2.exitCode === 0 || verify2.stdout?.trim()) return branch2;+ }+ }++ // Fall back to local branch detection+ const result = await execGitSafe(['branch', '--list'], dir);+ const branches = (result.stdout || '').trim().split('\n').map(b => b.replace(/^\*?\s+/, '')).filter(Boolean);+ if (branches.includes('main')) return 'main';+ if (branches.includes('master')) return 'master';++ // Last resort: use the currently checked-out branch+ const head = await execGitSafe(['rev-parse', '--abbrev-ref', 'HEAD'], dir);+ if (head.stdout?.trim() && head.stdout.trim() !== 'HEAD') {+ return head.stdout.trim();+ }++ return null;+}+/**- * Detect base and dev branches from local branch list+ * Detect base and dev branches from local refs (origin/HEAD, local branch list).+ * Does not contact the remote — safe for latency-sensitive request paths.+ * Computes the branch list once and reuses it for both base and dev detection.* @returns {{ baseBranch: string|null, devBranch: string|null }}*/export async function getRepoBranches(dir) {- const result = await execGit(['branch', '--list'], dir, { ignoreExitCode: true });- const branches = result.stdout.trim().split('\n').map(b => b.replace(/^\*?\s+/, ''));+ // Check origin/HEAD first (fast, local-only)+ const symRef = await execGitSafe(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], dir);+ let baseBranch = null;+ if (symRef.stdout?.trim()) {+ const candidate = symRef.stdout.trim().replace(/^origin\//, '');+ // Verify the ref actually exists (origin/HEAD could be stale)+ const verify = await execGitSafe(['rev-parse', '--verify', `refs/remotes/origin/${candidate}`], dir);+ if (verify.exitCode === 0 || verify.stdout?.trim()) {+ baseBranch = candidate;+ }+ }++ // Get local branches once — reused for both base fallback and dev detection+ const result = await execGitSafe(['branch', '--list'], dir);+ const branches = (result.stdout || '').trim().split('\n').map(b => b.replace(/^\*?\s+/, '')).filter(Boolean);++ if (!baseBranch) {+ if (branches.includes('main')) baseBranch = 'main';+ else if (branches.includes('master')) baseBranch = 'master';+ }+return {- baseBranch: branches.includes('main') ? 'main' : branches.includes('master') ? 'master' : null,+ baseBranch,devBranch: branches.includes('dev') ? 'dev' : branches.includes('develop') ? 'develop' : null};}diff --git a/server/services/git.test.js b/server/services/git.test.jsindex 29a6c82f26..f771844a23 100644--- a/server/services/git.test.js+++ b/server/services/git.test.js@@ -233,3 +233,4 @@ describe('extractAgentSummary', () => {expect(summary).not.toContain('🔧');});});+diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 304c3809e1..2092f625e2 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -44,18 +44,21 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =const worktreePath = join(WORKTREES_DIR, agentId);// 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}`);- });+ const fetchSucceeded = await execGit(['fetch', 'origin'], sourceWorkspace)+ .then(() => true)+ .catch(err => {+ console.log(`⚠️ Worktree fetch failed (will use local refs): ${err.message}`);+ return false;+ });- // Determine the base: explicit option > detected default branch > current HEAD+ // Determine the base: explicit option > remote default branch > current HEADlet baseBranch = options.baseBranch;if (!baseBranch) {- const mainExists = (await execGit(['branch', '--list', 'main'], sourceWorkspace)).stdout.trim();- const masterExists = (await execGit(['branch', '--list', 'master'], sourceWorkspace)).stdout.trim();- if (mainExists) baseBranch = 'main';- else if (masterExists) baseBranch = 'master';- else baseBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace)).stdout.trim();+ const { getDefaultBranch } = await import('./git.js');+ baseBranch = await getDefaultBranch(sourceWorkspace, { allowRemote: fetchSucceeded }).catch(() => null);+ if (!baseBranch) {+ baseBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace)).stdout.trim();+ }}// Prefer the remote ref (freshest state) if available@@ -206,18 +209,45 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio* Create a persistent worktree for a feature agent.* Unlike regular worktrees, these persist across runs.*/-export async function createPersistentWorktree(featureAgentId, sourceWorkspace, branchName, baseBranch = 'main') {+export async function createPersistentWorktree(featureAgentId, sourceWorkspace, branchName, baseBranch) {const FA_WORKTREES = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');await ensureDir(join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId));- await execGit(['fetch', 'origin'], sourceWorkspace).catch(err => {- console.log(`⚠️ Persistent worktree fetch failed: ${err.message}`);- });+ const fetchOk = await execGit(['fetch', 'origin'], sourceWorkspace)+ .then(() => true)+ .catch(err => {+ console.log(`⚠️ Persistent worktree fetch failed: ${err.message}`);+ return false;+ });+ if (!baseBranch) {+ const { getDefaultBranch } = await import('./git.js');+ baseBranch = await getDefaultBranch(sourceWorkspace, { allowRemote: fetchOk }).catch(() => null) || 'main';+ }++ // Verify the base branch exists locally or on the remote; re-detect if staleconst baseRef = await execGit(['rev-parse', `origin/${baseBranch}`], sourceWorkspace).then(() => `origin/${baseBranch}`)- .catch(() => baseBranch);+ .catch(async () => {+ const localExists = (await execGit(['branch', '--list', baseBranch], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();+ if (localExists) return baseBranch;+ // Provided baseBranch doesn't exist — re-detect the actual default+ const { getDefaultBranch } = await import('./git.js');+ const detected = await getDefaultBranch(sourceWorkspace, { allowRemote: false }).catch(() => null);+ if (detected && detected !== baseBranch) {+ baseBranch = detected;+ const remoteOk = await execGit(['rev-parse', `origin/${detected}`], sourceWorkspace, { ignoreExitCode: true })+ .then(r => r.exitCode === 0).catch(() => false);+ if (remoteOk) return `origin/${detected}`;+ const localOk = (await execGit(['branch', '--list', detected], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();+ if (localOk) return detected;+ }+ // All detection failed — use HEAD and update baseBranch to reflect reality+ const headBranch = (await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();+ baseBranch = headBranch && headBranch !== 'HEAD' ? headBranch : baseBranch;+ return 'HEAD';+ });// Check if branch already exists (local or remote)const localBranchExists = (await execGit(['branch', '--list', branchName], sourceWorkspace)).stdout.trim();@@ -267,13 +297,39 @@ export async function removePersistentWorktree(featureAgentId, sourceWorkspace,/*** Merge base branch into a persistent feature agent worktree before a run*/-export async function mergeBaseIntoFeatureWorktree(featureAgentId, baseBranch = 'main') {+export async function mergeBaseIntoFeatureWorktree(featureAgentId, baseBranch) {const worktreePath = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');if (!existsSync(worktreePath)) return { merged: false, reason: 'worktree-missing' };- await execGit(['fetch', 'origin'], worktreePath).catch(err => {- console.log(`⚠️ Fetch failed for feature agent ${featureAgentId}: ${err.message}`);- });+ const fetchOk = await execGit(['fetch', 'origin'], worktreePath)+ .then(() => true)+ .catch(err => {+ console.log(`⚠️ Fetch failed for feature agent ${featureAgentId}: ${err.message}`);+ return false;+ });++ if (!baseBranch) {+ const { getDefaultBranch } = await import('./git.js');+ baseBranch = await getDefaultBranch(worktreePath, { allowRemote: fetchOk }).catch(() => null) || 'main';+ }+ // Verify origin/<baseBranch> exists; if not, re-detect before giving up+ let remoteBranchValid = await execGit(['rev-parse', `origin/${baseBranch}`], worktreePath, { ignoreExitCode: true })+ .then(r => r.exitCode === 0)+ .catch(() => false);+ if (!remoteBranchValid) {+ const { getDefaultBranch } = await import('./git.js');+ const detected = await getDefaultBranch(worktreePath, { allowRemote: false }).catch(() => null);+ if (detected && detected !== baseBranch) {+ remoteBranchValid = await execGit(['rev-parse', `origin/${detected}`], worktreePath, { ignoreExitCode: true })+ .then(r => r.exitCode === 0).catch(() => false);+ if (remoteBranchValid) {+ baseBranch = detected;+ }+ }+ if (!remoteBranchValid) {+ return { merged: false, reason: `origin/${baseBranch} not found` };+ }+ }const result = await execGit(['merge', `origin/${baseBranch}`, '--no-edit'], worktreePath).then(() => ({ merged: true })).catch(async (err) => {