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: stop the pre-task git pull from looping on a diverged shared checkout
Adam Eivyf89d1c1e3952
diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.jsindex c6cbf494d9..4b49ec0a59 100644--- a/server/lib/taskBlockCategories.js+++ b/server/lib/taskBlockCategories.js@@ -41,7 +41,8 @@ export const PROVIDER_CONFIG_BLOCKED_CATEGORY = 'provider-config';*/export const TIMED_COOLDOWN_BLOCKED_CATEGORIES = new Set(['orphan-cooldown', // the orphan sweep's retry backoff- 'worktree-busy' // the branch is checked out in another worktree+ 'worktree-busy', // the branch is checked out in another worktree+ 'git-conflict-wait' // the shared checkout won't pull; a resolver task is fixing it]);/**diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex b40c179099..fddfa590d4 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -17,7 +17,7 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';* `cleanupOnError` + the matching `agent:deferred` / `agent:error` event:** { outcome: 'ready', workspacePath, resolvedApp, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree }- * { outcome: 'deferred', reason, deferReason, branch } // git conflict — task re-queued+ * { outcome: 'deferred', reason, deferReason, branch } // git conflict — task paused on a `git-conflict-wait` cooldown* { outcome: 'blocked', reason } // explicit worktree requested but creation failed* // (`worktree-busy` blocks are a TIMED pause and revive themselves)*@@ -80,6 +80,8 @@ async function blockTask(task, reason, blockedCategory, extraMetadata = {}) {// task takes the ordinary `worktree-failed` block and the orphaned-PR notifier// raises its card.const WORKTREE_BUSY_COOLDOWN_MS = 2 * 60 * 1000;+// How long a task blocked by an unpullable shared checkout waits before retrying.+const GIT_CONFLICT_COOLDOWN_MS = 5 * 60 * 1000;const WORKTREE_BUSY_MAX_ATTEMPTS = 5;// Compatibility export for callers that reached for the accessor from this@@ -426,7 +428,11 @@ export async function prepareAgentWorkspace({ agentId, task }) {if (!isReadOnly && !claimWorkspace) {// Isolated tasks fetch their base in createWorktree; never rebase the// shared checkout as a side effect of preparing a separate workspace.- const pullResult = wantsWorktree ? { skipped: 'isolated-task' } : await git.ensureLatest(workspacePath).catch(err => {+ // The conflict-resolution task works on the very checkout that won't pull;+ // gating it on a clean pull would defer it forever.+ const pullResult = wantsWorktree ? { skipped: 'isolated-task' }+ : isTruthyMeta(task.metadata?.gitConflictResolution) ? { skipped: 'git-conflict-resolver' }+ : await git.ensureLatest(workspacePath).catch(err => {emitLog('warn', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });return { success: false, error: err.message };});@@ -439,22 +445,30 @@ export async function prepareAgentWorkspace({ agentId, task }) {});const appId = task.metadata?.app || null;+ // The description's first line is the duplicate key, so it stays stable+ // across retries; the (varying) git error goes in the context.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}`;+ + `The branch has diverged from origin and automatic rebase failed.`;await addTask({description: conflictDesc,priority: 'HIGH',app: appId,- context: `This conflict is blocking task ${task.id}: "${task.description}". `+ metadata: { gitConflictResolution: true },+ context: `Error: ${pullResult.error}\n`+ + `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('warn', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });});- await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});+ // A timed pause, not `pending`: a pending task is re-dequeued within+ // seconds and re-runs the same failing rebase in a hot loop until the+ // resolver lands. The cooldown sweeper revives it.+ await blockTask(task, `Git conflict in ${resolvedAppName || workspacePath} (branch ${pullResult.branch}); waiting for the resolver task`, 'git-conflict-wait', {+ cooldownUntil: new Date(Date.now() + GIT_CONFLICT_COOLDOWN_MS).toISOString(),+ });return {outcome: 'deferred',reason: 'Git conflict blocks task — conflict resolution task created',diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex bd58668347..9a173f757e 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -66,7 +66,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';import { claimContinuationWorkspace } from '../lib/claimContinuation.js';-import { updateTask, getAgents } from './cos.js';+import { updateTask, addTask, getAgents } from './cos.js';import { ensureLatest } from './git.js';import { execGit } from '../lib/execGit.js';import { detectConflicts } from './taskConflict.js';@@ -241,6 +241,20 @@ describe('prepareAgentWorkspace', () => {expect(r.outcome).toBe('deferred');expect(r.deferReason).toBe('git-conflict');expect(r.branch).toBe('feature/x');+ // A timed pause, not `pending` — pending was re-dequeued every few seconds.+ const [, patch] = updateTask.mock.calls.find(([id]) => id === 't-conflict');+ expect(patch.status).toBe('blocked');+ expect(patch.metadata.blockedCategory).toBe('git-conflict-wait');+ expect(Date.parse(patch.metadata.cooldownUntil)).toBeGreaterThan(Date.now());+ expect(addTask.mock.calls[0][0].metadata).toEqual({ gitConflictResolution: true });+ });++ it('lets the conflict-resolver task skip the pull it exists to fix', async () => {+ ensureLatest.mockResolvedValue({ conflict: true, branch: 'main', error: 'rebase failed' });+ const task = { id: 't-resolver', taskType: 'internal', metadata: { gitConflictResolution: true } };+ const r = await prepareAgentWorkspace({ agentId: 'agent-r', task });+ expect(r.outcome).toBe('ready');+ expect(ensureLatest).not.toHaveBeenCalled();});it('proceeds in the shared workspace when the pull is clean and no conflict is detected', async () => {diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.jsindex df5cf756b6..6f14f59094 100644--- a/server/services/appQualitySnapshotFile.js+++ b/server/services/appQualitySnapshotFile.js@@ -25,11 +25,12 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises';import { atomicWrite } from '../lib/fileCore.js';import {APP_QUALITY_LEGACY_SNAPSHOT_FILENAME,+ APP_QUALITY_SNAPSHOT_FILENAME,classifyQualitySnapshot,qualityFileFromWireSnapshot,} from './appQualitySnapshotFormat.js';-export const APP_QUALITY_SNAPSHOT_FILENAME = '.quality.json';+export { APP_QUALITY_SNAPSHOT_FILENAME };export const APP_QUALITY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;export const QUALITY_SNAPSHOT_BRANCH = 'portos/quality-snapshot';diff --git a/server/services/appQualitySnapshotFormat.js b/server/services/appQualitySnapshotFormat.jsindex 38bf61a940..43fd91dd5b 100644--- a/server/services/appQualitySnapshotFormat.js+++ b/server/services/appQualitySnapshotFormat.js@@ -20,6 +20,7 @@ import { auditQualityReportSchema } from '../lib/auditQuality.js';export const APP_QUALITY_FILE_SCHEMA_VERSION = 2;export const APP_QUALITY_REPORT_VERSION = 1;+export const APP_QUALITY_SNAPSHOT_FILENAME = '.quality.json';export const APP_QUALITY_LEGACY_SNAPSHOT_FILENAME = 'quality-snapshot.json';export const QUALITY_COVERAGE_VALUES = Object.freeze(['broad', 'partial', 'unavailable', 'not-applicable']);export const QUALITY_CONFIDENCE_VALUES = Object.freeze(['low', 'medium', 'high']);diff --git a/server/services/git.ensureLatest.test.js b/server/services/git.ensureLatest.test.jsnew file mode 100644index 0000000000..7a8f8c2e0d--- /dev/null+++ b/server/services/git.ensureLatest.test.js@@ -0,0 +1,79 @@+import { describe, it, expect, afterEach } from 'vitest';+import { writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { execGit } from '../lib/execGit.js';+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import { ensureLatest } from './git.js';++// Real git: the regressions here are git's own on-disk rebase state+// (`.git/rebase-merge`) and what `reset`/`rebase --abort` do to it.+describe.skipIf(SKIP_HEAVY_INTEGRATION)('ensureLatest on a diverged checkout', () => {+ let sandbox;+ afterEach(async () => { if (sandbox) await destroyGitSandbox(sandbox.scratch); sandbox = null; });++ const commitFile = async (repo, file, body, msg) => {+ await writeFile(join(repo, file), body);+ await execGit(['add', file], repo);+ await execGit(['commit', '-m', msg], repo);+ };++ // origin and the local checkout each commit a different body to `file`.+ const diverge = async (file) => {+ sandbox = await makeGitSandbox({ origin: true });+ const { scratch, repo, origin } = sandbox;+ await execGit(['push', '-u', 'origin', 'main'], repo, { ignoreExitCode: true });+ const other = join(scratch, 'other');+ await execGit(['clone', origin, other], scratch);+ await execGit(['config', 'user.email', '[email protected]'], other);+ await execGit(['config', 'user.name', 'Example Agent'], other);+ await commitFile(other, file, '{"from":"origin"}\n', 'origin change');+ await execGit(['push', 'origin', 'HEAD:main'], other);+ await commitFile(repo, file, '{"from":"local"}\n', 'local change');+ return repo;+ };++ const rebaseDirExists = (repo) => existsSync(join(repo, '.git', 'rebase-merge'));++ it('serializes concurrent pulls so neither trips over (or aborts) the other\'s rebase', async () => {+ const repo = await diverge('notes.txt');+ const results = await Promise.all([ensureLatest(repo), ensureLatest(repo), ensureLatest(repo)]);+ for (const r of results) {+ expect(r.conflict).toBe(true);+ expect(r.error).not.toMatch(/rebase-merge directory/);+ expect(r.error).not.toMatch(/hint:/);+ expect(r.error).toMatch(/CONFLICT|could not apply/);+ }+ expect(rebaseDirExists(repo)).toBe(false);+ });++ it('drops local commits that only touch PortOS-owned .quality.json and lands on origin', async () => {+ const repo = await diverge('.quality.json');+ const r = await ensureLatest(repo);+ expect(r).toMatchObject({ success: true, conflict: false });+ expect(r.droppedLocalCommits).toHaveLength(1);+ const head = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();+ const upstream = (await execGit(['rev-parse', 'origin/main'], repo)).stdout.trim();+ expect(head).toBe(upstream);+ });++ it('keeps local commits that touch anything besides PortOS-owned files', async () => {+ const repo = await diverge('.quality.json');+ await commitFile(repo, 'src.txt', 'user work\n', 'user work');+ const before = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();+ const r = await ensureLatest(repo);+ expect(r.conflict).toBe(true);+ expect((await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim()).toBe(before);+ });++ it('leaves someone else\'s in-progress rebase alone', async () => {+ const repo = await diverge('notes.txt');+ await execGit(['fetch', 'origin'], repo);+ await execGit(['rebase', 'origin/main'], repo, { ignoreExitCode: true });+ expect(rebaseDirExists(repo)).toBe(true);+ const r = await ensureLatest(repo);+ expect(r.conflict).toBe(true);+ expect(r.error).toMatch(/already in progress/);+ expect(rebaseDirExists(repo)).toBe(true);+ });+});diff --git a/server/services/git.js b/server/services/git.jsindex f86d83b429..8fdec544c3 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -997,10 +997,83 @@ export function hasChangelogDir(dir) {* @returns {{ success: boolean, branch: string, conflict: boolean, error: string|null }}*/-export async function ensureLatest(dir) {+// One pre-task pull per checkout at a time. Several agents for the same app+// prep concurrently; without this the second one's `rebase` hits the first's+// `.git/rebase-merge` and its failure-path `rebase --abort` then tears down the+// FIRST agent's in-flight rebase.+const ensureLatestTails = new Map();++export function ensureLatest(dir) {+ const key = resolve(dir);+ const prev = ensureLatestTails.get(key) || Promise.resolve();+ const run = prev.catch(() => {}).then(() => ensureLatestUnserialized(dir));+ const tail = run.catch(() => {});+ ensureLatestTails.set(key, tail);+ tail.then(() => { if (ensureLatestTails.get(key) === tail) ensureLatestTails.delete(key); });+ return run;+}++// Files PortOS itself owns in a managed app's checkout. The quality publisher+// lands them through a PR, so origin is authoritative; a local commit that only+// touches them is a stale leftover (an older publisher committed on the live+// checkout) and is safe to drop when it blocks the pull. Imported lazily: only+// a conflicting pull needs it, and git.js is reached by hundreds of suites.+async function portosOwnedCheckoutFiles() {+ const { APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME } = await import('./appQualitySnapshotFormat.js');+ return new Set([APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]);+}++async function rebaseInProgress(dir) {+ for (const name of ['rebase-merge', 'rebase-apply']) {+ const res = await execGit(['rev-parse', '--git-path', name], dir, { ignoreExitCode: true });+ const gitPath = res.stdout?.trim();+ if (gitPath && existsSync(resolve(dir, gitPath))) return true;+ }+ return false;+}++// When the only thing the local branch adds over origin is PortOS-owned files,+// move the branch to origin (`reset --keep` refuses rather than clobbering+// anything uncommitted). Returns the dropped commit subjects, or null when the+// local side carries anything else.+async function dropPortosOwnedLocalCommits(dir, branch) {+ const upstream = `origin/${branch}`;+ const changed = await execGit(['diff', '--name-only', `${upstream}...HEAD`], dir, { ignoreExitCode: true });+ if (changed.exitCode !== 0) return null;+ const files = changed.stdout.split('\n').map(f => f.trim()).filter(Boolean);+ const owned = await portosOwnedCheckoutFiles();+ if (!files.length || !files.every(f => owned.has(f))) return null;+ const log = await execGit(['log', '--format=%h %s', `${upstream}..HEAD`], dir, { ignoreExitCode: true });+ const reset = await execGit(['reset', '--keep', upstream], dir, { ignoreExitCode: true });+ if (reset.exitCode !== 0) return null;+ return log.stdout.split('\n').map(l => l.trim()).filter(Boolean);+}++// git's rebase failure output is a multi-line block of `hint:` advice with a+// `\r`-overwritten progress line glued in front — the part worth logging is+// the error plus the CONFLICT lines naming the files.+function summarizeRebaseConflict({ stdout = '', stderr = '' } = {}) {+ const lines = `${stdout}\n${stderr}`.split(/[\r\n]+/).map(l => l.trim()).filter(Boolean);+ const keep = lines.filter(l => /^(CONFLICT|error:|fatal:)/.test(l));+ return (keep.length ? keep : lines.filter(l => !l.startsWith('hint:')).slice(0, 3)).join('; ') || 'rebase failed';+}++async function ensureLatestUnserialized(dir) {const gitCheck = await isRepo(dir).catch(() => false);if (!gitCheck) return { success: true, branch: null, conflict: false, error: null, skipped: 'not-a-repo' };+ // A rebase left in progress is someone's (a person's, or an agent resolving a+ // conflict) — never start a second one on top of it, and never abort it.+ if (await rebaseInProgress(dir)) {+ const branch = await getBranch(dir).catch(() => null);+ return {+ success: false,+ branch,+ conflict: true,+ error: 'a rebase is already in progress in this checkout; finish it (git rebase --continue) or abort it (git rebase --abort)'+ };+ }+const currentBranch = await getBranch(dir).catch(() => null);if (!currentBranch) return { success: true, branch: null, conflict: false, error: null, skipped: 'no-branch' };@@ -1083,11 +1156,16 @@ export async function ensureLatest(dir) {error: `Cleared an abandoned git lock (${rebaseLock}) left by a killed git process. The rebase onto origin/${currentBranch} did not complete — retry now that the lock is clear.`};}+ const dropped = await dropPortosOwnedLocalCommits(dir, currentBranch);+ if (dropped) {+ console.warn(`⚠️ Dropped ${dropped.length} stale local PortOS-owned commit(s) on ${currentBranch} in ${dir} to match origin: ${dropped.join('; ')}`);+ return { success: true, branch: currentBranch, conflict: false, error: null, droppedLocalCommits: dropped };+ }return {success: false,branch: currentBranch,conflict: true,- error: `branch ${currentBranch} has diverged from origin and rebase has conflicts: ${rebaseResult.stderr}`+ error: `branch ${currentBranch} has diverged from origin and rebase has conflicts: ${summarizeRebaseConflict(rebaseResult)}`};}