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(update): rebase with --autostash instead of refusing a dirty checkout
Adam Eivy10759b9272f5
diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex 8c6ad246d9..bfb32cd23f 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -23,6 +23,58 @@ function runCommand(cmd, args, cwd) {return bufferedSpawnOrThrow(cmd, args, { cwd, timeoutMs: CMD_TIMEOUT_MS });}+/**+ * End the update at a git conflict the pull step could not resolve, handing the+ * checkout to a CoS agent.+ *+ * `updateDefaultBranch` already tried a fast-forward and then a+ * `pull --rebase --autostash`; reaching here means the checkout needs judgement+ * no scripted pull can supply, so nothing downstream may run on it — it may be+ * mid-rebase or carrying conflict markers. The task's first line is stable per+ * repo path so `addTask`'s description+app dedup collapses repeated failed+ * update attempts onto the one open task rather than queueing an agent per click.+ *+ * The CoS task store is imported lazily: this module is reached by every app+ * operation, while the conflict branch is rare, and a static import would pull+ * the whole CoS state graph into that closure (see "Import scoping" in+ * server/AGENTS.md).+ *+ * @returns {Promise<{success: false, steps: object[]}>} the update's own result+ * shape. Never rejects — a failed enqueue must not mask the conflict message.+ */+async function failWithGitConflict({ app, repoPath, pullResult, stepId, emit, steps }) {+ const message = `Could not update ${repoPath}: ${pullResult.error}. `+ + `A CoS agent has been queued to resolve it.`;+ emit(stepId, 'error', message);+ steps.push({ step: stepId, success: false, message });+ const label = app?.name || repoPath;+ const branch = pullResult.branch || 'the default branch';+ const task = {+ description: `Resolve git conflict in ${label} at ${repoPath}`,+ priority: 'HIGH',+ app: app?.id || null,+ context: `Updating ${label} failed: the checkout could not be brought onto origin/${branch}. `+ + `A fast-forward and then a rebase with --autostash were both attempted. `+ + `Error: ${pullResult.error || 'unknown'}\n\n`+ + `Resolve the conflict in ${repoPath} (finish or abort any in-progress rebase, reconcile the `+ + `working tree, commit or restore the stashed work), then leave the checkout clean on `+ + `origin/${branch} so the update can be re-run.`,+ position: 'top'+ };+ const created = await import('./cosTaskStore.js')+ .then(({ addTask }) => addTask(task, 'internal'))+ .catch((err) => {+ console.error(`❌ Failed to queue conflict-resolution task for ${label}: ${err.message}`);+ return null;+ });+ if (created?.duplicate) {+ console.log(`⚠️ Conflict-resolution task already open for ${label} (${created.id})`);+ } else if (created) {+ console.log(`🔀 Queued conflict-resolution task ${created.id} for ${label} on ${branch}`);+ }+ return { success: false, steps };+}+// Per-app lock to prevent concurrent updatesconst updatingApps = new Set();const DASHBOARD_OPEN_SCRIPT = 'scripts/open-ui-in-browser.js';@@ -167,6 +219,9 @@ async function _doUpdate(app, emit, {emit('git-pull', 'running', 'Updating from origin default branch...');const pullResult = await gitService.updateDefaultBranch(dir);+ if (pullResult.conflict) {+ return failWithGitConflict({ app, repoPath: dir, pullResult, stepId: 'git-pull', emit, steps });+ }const pullMsg = pullResult.output?.trim() || `${pullResult.branch} is up to date`;emit('git-pull', 'done', pullMsg);steps.push({ step: 'git-pull', success: true, message: pullMsg });@@ -179,6 +234,9 @@ async function _doUpdate(app, emit, {const stepId = `git-pull:companion-${index + 1}`;emit(stepId, 'running', `Pulling companion repository ${index + 1}/${companionRepoPaths.length}...`);const companionPull = await gitService.updateDefaultBranch(companionPath);+ if (companionPull.conflict) {+ return failWithGitConflict({ app, repoPath: companionPath, pullResult: companionPull, stepId, emit, steps });+ }const companionMessage = companionPull.output?.trim() || `${companionPull.branch} is up to date`;emit(stepId, 'done', companionMessage);steps.push({ step: stepId, success: true, message: companionMessage });diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.jsindex 1425a6ad65..eede9471ec 100644--- a/server/services/appUpdater.test.js+++ b/server/services/appUpdater.test.js@@ -9,6 +9,7 @@ const mock = vi.hoisted(() => ({// per-test temp repo instead.paths: { root: '' },updateDefaultBranch: vi.fn(),+ addTask: vi.fn(),spawn: vi.fn(),startPortosSelfUpdate: vi.fn(),dashboardOpen: vi.fn(),@@ -34,6 +35,7 @@ vi.mock('../lib/detachedSpawn.js', () => ({spawnDetached: mock.dashboardOpen,}));vi.mock('./managedAppRepositories.js', () => ({ syncManagedAppFork: mock.syncFork }));+vi.mock('./cosTaskStore.js', () => ({ addTask: mock.addTask }));import { updateApp } from './appUpdater.js';@@ -53,6 +55,7 @@ describe('managed app updates', () => {mock.dashboardRunning.mockResolvedValue(false);mock.dashboardOpen.mockResolvedValue(mock.dashboardHandle);mock.restart.mockResolvedValue({ success: true });+ mock.addTask.mockResolvedValue({ id: 'sys-conflict' });mock.syncFork.mockResolvedValue({alreadyUpToDate: false,fullName: 'example-owner/example-app',@@ -91,6 +94,65 @@ describe('managed app updates', () => {expect(emit).toHaveBeenCalledWith('app-update', 'done', 'App update routine complete');});+ it('queues a CoS agent and stops the update when the pull hits a conflict', async () => {+ mock.updateDefaultBranch.mockResolvedValueOnce({+ success: false,+ branch: 'main',+ conflict: true,+ error: 'CONFLICT (content): Merge conflict in server/index.js',+ });+ const emit = vi.fn();++ const result = await updateApp({+ id: 'example-app',+ name: 'Example App',+ type: 'express',+ repoPath: repo,+ pm2ProcessNames: ['example-app'],+ }, emit);++ expect(result.success).toBe(false);+ expect(result.steps).toEqual([expect.objectContaining({ step: 'git-pull', success: false })]);+ expect(emit).toHaveBeenCalledWith('git-pull', 'error', expect.stringContaining('CoS agent'));+ expect(mock.addTask).toHaveBeenCalledWith(+ expect.objectContaining({+ description: `Resolve git conflict in Example App at ${repo}`,+ app: 'example-app',+ priority: 'HIGH',+ }),+ 'internal',+ );+ // The conflict is upstream of every mutating step — nothing may run on a+ // checkout that is mid-rebase or carrying conflict markers.+ expect(mock.spawn).not.toHaveBeenCalled();+ expect(mock.restart).not.toHaveBeenCalled();+ });++ it('queues a CoS agent for a companion repository conflict', async () => {+ const companionRepo = join(repo, '..', 'example-companion');+ mock.updateDefaultBranch+ .mockResolvedValueOnce({ branch: 'main', output: 'Already up to date' })+ .mockResolvedValueOnce({ success: false, branch: 'main', conflict: true, error: 'CONFLICT (content): x' });+ const emit = vi.fn();++ const result = await updateApp({+ id: 'example-app',+ name: 'Example App',+ type: 'express',+ repoPath: repo,+ companionRepoPaths: [companionRepo],+ pm2ProcessNames: ['example-app'],+ }, emit);++ expect(result.success).toBe(false);+ expect(emit).toHaveBeenCalledWith('git-pull:companion-1', 'error', expect.stringContaining('CoS agent'));+ expect(mock.addTask).toHaveBeenCalledWith(+ expect.objectContaining({ description: `Resolve git conflict in Example App at ${companionRepo}` }),+ 'internal',+ );+ expect(mock.restart).not.toHaveBeenCalled();+ });+it('syncs a detected fork before pulling when the managed update requests it', async () => {const emit = vi.fn();const managed = { name: 'Example App', type: 'express', repoPath: repo, pm2ProcessNames: [] };diff --git a/server/services/git.js b/server/services/git.jsindex cf6256a51c..236bf04724 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -821,34 +821,66 @@ export async function pull(dir) {/*** Move a managed application's primary checkout onto origin's default branch- * and fast-forward it. This is intentionally non-destructive: unlike the- * Git-tab reset escape hatch it neither stashes nor discards local work.+ * and bring it up to date. Non-destructive: nothing is discarded, and local+ * work is preserved either by carrying it across the checkout or by git's own+ * `--autostash` (which re-applies it after the rebase).+ *+ * Order of attempts:+ * 1. `pull --ff-only` — the common case, no rewrite, no stash.+ * 2. `pull --rebase --autostash` — the checkout is dirty and/or the local+ * branch has diverged from origin. This is what "Update App" used to+ * refuse outright with DIRTY_WORKTREE.+ * 3. On conflict, abort any in-progress rebase and report `conflict: true`+ * rather than throwing, so the caller can hand the mess to a CoS agent.+ *+ * `rebase --abort` is best-effort: a conflict raised while `--autostash`+ * re-applies the stash happens AFTER the rebase completed, so there is no+ * rebase to abort and the working tree keeps its conflict markers. That is+ * still `conflict: true` — a human or an agent has to finish it.** @param {string} dir- * @returns {Promise<{success: boolean, branch: string, output: string}>}+ * @returns {Promise<{success: boolean, branch: string, output: string, conflict: boolean, rebased?: boolean, error?: string}>}*/export async function updateDefaultBranch(dir) {await execGit(['fetch', 'origin'], dir);const branch = await getDefaultBranch(dir, { strict: true });if (!branch) throw new ServerError('could not determine origin default branch', { status: 400, code: 'NO_DEFAULT_BRANCH' });- const status = await getStatus(dir);- if (!status.clean) {- throw new ServerError('checkout has local changes; commit or stash them before updating', {- status: 409,- code: 'DIRTY_WORKTREE'- });- }-const currentBranch = await getBranch(dir);let output = '';if (currentBranch !== branch) {- const checkout = await execGit(['checkout', branch], dir);+ // Uncommitted changes ride along when they don't collide with the target+ // branch; when they do, git refuses and we route that to the conflict path+ // instead of throwing an unactionable error at the UI.+ const checkout = await execGit(['checkout', branch], dir, { ignoreExitCode: true });output += checkout.stdout + checkout.stderr;+ if (checkout.exitCode !== 0) {+ return {+ success: false,+ branch,+ output,+ conflict: true,+ error: (checkout.stderr || `could not check out ${branch}`).trim()+ };+ }}- const pull = await execGit(['pull', '--ff-only', 'origin', branch], dir);- output += pull.stdout + pull.stderr;- return { success: true, branch, output };++ const fastForward = await execGit(['pull', '--ff-only', 'origin', branch], dir, { ignoreExitCode: true });+ output += fastForward.stdout + fastForward.stderr;+ if (fastForward.exitCode === 0) return { success: true, branch, output, conflict: false };++ const rebase = await execGit(['pull', '--rebase', '--autostash', 'origin', branch], dir, { ignoreExitCode: true });+ output += rebase.stdout + rebase.stderr;+ if (rebase.exitCode === 0) return { success: true, branch, output, conflict: false, rebased: true };++ await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true });+ return {+ success: false,+ branch,+ output,+ conflict: true,+ error: (rebase.stderr || rebase.stdout || `rebase onto origin/${branch} failed`).trim()+ };}/**diff --git a/server/services/git.updateDefaultBranch.test.js b/server/services/git.updateDefaultBranch.test.jsindex 7298fba245..b50323d8de 100644--- a/server/services/git.updateDefaultBranch.test.js+++ b/server/services/git.updateDefaultBranch.test.js@@ -7,43 +7,78 @@ vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock }));import { updateDefaultBranch } from './git.js';const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });+const fail = (stderr = '', exitCode = 1) => ({ stdout: '', stderr, exitCode });const key = (args) => args.join(' ');+const commands = () => execGitMock.mock.calls.map(([args]) => key(args));++const base = {+ 'fetch origin': ok(),+ 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),+ 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),+ 'status --porcelain': ok(),+ 'rev-parse --abbrev-ref HEAD': ok('feature/work'),+ 'checkout main': ok('Switched to branch main'),+ 'pull --ff-only origin main': ok('Already up to date')+};++const withGit = (overrides = {}) => {+ const table = { ...base, ...overrides };+ execGitMock.mockImplementation((args) => Promise.resolve(table[key(args)] ?? ok()));+};beforeEach(() => {execGitMock.mockReset();- execGitMock.mockImplementation((args) => Promise.resolve({- 'fetch origin': ok(),- 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),- 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),- 'status --porcelain': ok(),- 'rev-parse --abbrev-ref HEAD': ok('feature/work'),- 'checkout main': ok('Switched to branch main'),- 'pull --ff-only origin main': ok('Already up to date')- }[key(args)] ?? ok()));+ withGit();});describe('updateDefaultBranch', () => {it('checks out origin default branch and fast-forwards it without a rebase', async () => {const result = await updateDefaultBranch('/repo');- expect(result).toMatchObject({ success: true, branch: 'main' });- expect(execGitMock.mock.calls.map(([args]) => key(args))).toEqual(expect.arrayContaining([+ expect(result).toMatchObject({ success: true, branch: 'main', conflict: false });+ expect(commands()).toEqual(expect.arrayContaining(['fetch origin','checkout main','pull --ff-only origin main']));- expect(execGitMock.mock.calls.map(([args]) => key(args)).some(command => command.includes('rebase'))).toBe(false);+ expect(commands().some(command => command.includes('rebase'))).toBe(false);+ });++ it('rebases with --autostash when the checkout is dirty or diverged', async () => {+ withGit({+ 'status --porcelain': ok(' M package-lock.json'),+ 'pull --ff-only origin main': fail('fatal: Not possible to fast-forward, aborting.')+ });++ const result = await updateDefaultBranch('/repo');++ expect(result).toMatchObject({ success: true, branch: 'main', conflict: false, rebased: true });+ expect(commands()).toContain('pull --rebase --autostash origin main');+ expect(commands()).not.toContain('rebase --abort');});- it('refuses to switch branches while the checkout has local changes', async () => {- execGitMock.mockImplementation((args) => Promise.resolve({- 'fetch origin': ok(),- 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),- 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),- 'status --porcelain': ok(' M package-lock.json')- }[key(args)] ?? ok()));+ it('reports a conflict and aborts the rebase when --autostash cannot reconcile', async () => {+ withGit({+ 'pull --ff-only origin main': fail('fatal: Not possible to fast-forward, aborting.'),+ 'pull --rebase --autostash origin main': fail('CONFLICT (content): Merge conflict in server/index.js')+ });++ const result = await updateDefaultBranch('/repo');++ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });+ expect(result.error).toMatch(/CONFLICT/);+ expect(commands()).toContain('rebase --abort');+ });++ it('reports a conflict when local changes block the branch switch', async () => {+ withGit({+ 'checkout main': fail('error: Your local changes to the following files would be overwritten by checkout')+ });++ const result = await updateDefaultBranch('/repo');- await expect(updateDefaultBranch('/repo')).rejects.toThrow(/local changes/);- expect(execGitMock.mock.calls.map(([args]) => key(args))).not.toContain('checkout main');+ expect(result).toMatchObject({ success: false, branch: 'main', conflict: true });+ expect(result.error).toMatch(/local changes/);+ expect(commands()).not.toContain('pull --ff-only origin main');});});