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(git): preserve linked worktrees during automated PR merges
[._.]/ Adam Eivya796e1b09761
diff --git a/server/lib/execGit.js b/server/lib/execGit.jsindex 5216ade21f..1f9fc64ee0 100644--- a/server/lib/execGit.js+++ b/server/lib/execGit.js@@ -14,6 +14,7 @@ import { spawn } from './childProcess.js';* @param {number} [options.maxBuffer] - Max output buffer size in bytes (default 10 MB)* @param {number} [options.timeout] - Timeout in ms (default 30s)* @param {boolean} [options.ignoreExitCode] - Resolve instead of reject on non-zero exit+ * @param {object} [options.env] - Explicit child environment; omitted inherits normally* @returns {Promise<{stdout: string, stderr: string, exitCode: number|null, signal?: string, terminated?: boolean}>}*/export function execGit(args, cwd, options = {}) {@@ -33,7 +34,8 @@ export function execGit(args, cwd, options = {}) {// platforms (including Windows) without a shell wrapper.const child = spawn('git', args, {cwd,- shell: false+ shell: false,+ ...(options.env ? { env: options.env } : {})});let stdout = '';diff --git a/server/lib/execGit.test.js b/server/lib/execGit.test.jsindex 3db126650e..0bafac1f68 100644--- a/server/lib/execGit.test.js+++ b/server/lib/execGit.test.js@@ -32,10 +32,21 @@ describe('execGit', () => {const promise = execGit(['status'], '/repo');child.emit('close', 0);await promise;- expect(spawn).toHaveBeenCalledWith('git', ['status'], expect.objectContaining({+ expect(spawn).toHaveBeenCalledWith('git', ['status'], {cwd: '/repo',shell: false- }));+ });+ });++ it('forwards an explicit credential environment without merging ambient variables', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const env = { GH_TOKEN: 'selected-fixture-token', GIT_TERMINAL_PROMPT: '0' };+ const promise = execGit(['push'], '/repo', { env });+ child.emit('close', 0);+ await promise;+ expect(spawn).toHaveBeenCalledWith('git', ['push'], { cwd: '/repo', shell: false, env });+ expect(spawn.mock.calls[0][2].env).toBe(env);});it('resolves with stdout/stderr/exitCode on successful exit', async () => {diff --git a/server/services/appPullRequestMerge.js b/server/services/appPullRequestMerge.jsindex 30ae22fb68..ea96853c90 100644--- a/server/services/appPullRequestMerge.js+++ b/server/services/appPullRequestMerge.js@@ -71,10 +71,10 @@ async function mergeGithubCore({ cwd, env, repoSpec, number, method, deleteBranc// sweep's mode — no forge read needed to name the repo it is already in).if (repoSpec) args.push('--repo', repoSpec);args.push(`--${method}`);- // `--repo` mode: `--delete-branch` deletes the REMOTE branch only — it never- // runs a local checkout in the user's working tree. Local mode: it deletes- // the branch in `cwd`'s checkout, same as `gh pr merge` does unassisted.- if (deleteBranch) args.push('--delete-branch');+ // Checkout-mode deletion can remove linked worktrees, including ignored+ // contents. Only remote mode may delegate deletion to gh; mergePR owns its+ // separate exact-ref cleanup and never asks gh to touch local branches.+ if (deleteBranch && repoSpec) args.push('--delete-branch');if (expectedHeadSha) args.push('--match-head-commit', expectedHeadSha);const error = await execGh(args, timeoutMs, { cwd, env }).then(() => null, err => err);@@ -101,7 +101,7 @@ async function mergeGitlabCore({ cwd, env, number, method, deleteBranch, timeout* The one caller of `gh pr merge` / `glab mr merge`. Dir/target-shaped rather* than app-shaped, so both the direct-merge button (`--repo` remote mode,* whichever method the user picked) and the automated merge sweep (local- * checkout mode, gh only, hardcoded `--merge --delete-branch`) share the same+ * checkout mode, gh only, hardcoded `--merge`) share the same* argv construction and forge-failure classification (issue #7580).** `timeoutMs` is intentionally NOT defaulted here: `mergeAppPullRequest` passesdiff --git a/server/services/git.forgeTimeout.test.js b/server/services/git.forgeTimeout.test.jsindex 14530e8afb..e625d4d5da 100644--- a/server/services/git.forgeTimeout.test.js+++ b/server/services/git.forgeTimeout.test.js@@ -48,8 +48,8 @@ describe('bounded forge mutations', () => {it.each([['createPR', ['pr', 'create'], () => createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' })],- ['mergePR', ['pr', 'merge', '42', '--merge', '--delete-branch'], () => mergePR('/repo', 42)],- ['head-pinned mergePR', ['pr', 'merge', '42', '--merge', '--delete-branch', '--match-head-commit', 'a'.repeat(40)], () => mergePR('/repo', 42, { expectedHeadSha: 'a'.repeat(40) })],+ ['mergePR', ['pr', 'merge', '42', '--merge'], () => mergePR('/repo', 42)],+ ['head-pinned mergePR', ['pr', 'merge', '42', '--merge', '--match-head-commit', 'a'.repeat(40)], () => mergePR('/repo', 42, { expectedHeadSha: 'a'.repeat(40) })],['requestCopilotReview', ['api', 'repos/example-owner/repo/pulls/42/requested_reviewers'], () => requestCopilotReview('/repo', 'https://github.com/example-owner/repo/pull/42')],])('kills a stalled gh process and returns a structured timeout from %s', async (_name, expectedArgs, invoke) => {const child = hungChild();@@ -58,6 +58,8 @@ describe('bounded forge mutations', () => {const pending = invoke();await vi.dynamicImportSettled();await vi.advanceTimersByTimeAsync(60000);+ // A failed merge is read back once: a timeout is not proof it did not land.+ if (_name.includes('mergePR')) await vi.advanceTimersByTimeAsync(60000);await expect(pending).resolves.toMatchObject({success: false,@@ -69,6 +71,7 @@ describe('bounded forge mutations', () => {expect.arrayContaining(expectedArgs),expect.objectContaining({ cwd: '/repo', env: expect.objectContaining({ GH_TOKEN: 'test-owner-token', PWD: '/repo' }) }),);+ if (_name.includes('mergePR')) expect(mocks.spawn.mock.calls[0][1]).not.toContain('--delete-branch');});it.each(['gh', 'glab'])('creates drafts through %s without enabling merging', async cli => {diff --git a/server/services/git.js b/server/services/git.jsindex 693f7a68f9..154a72daf8 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -438,7 +438,7 @@ export async function createPR(dir, { title, body, base, head, draft = false })* The actual `gh pr merge` invocation is the shared core in* `appPullRequestMerge.js` (`runForgeMerge`), lazily imported like the other* forge CLIs below — this stays the only owner of that argv (#7580), and its- * `['pr', 'merge', prNumber, '--merge', '--delete-branch']` shape and 60s+ * `['pr', 'merge', prNumber, '--merge']` shape and 60s* default timeout are pinned by `git.forgeTimeout.test.js`.** @param {string} dir - Working directory for the target repository@@ -462,10 +462,81 @@ export async function mergePR(dir, prNumber, { forgeAccount = null, expectedHeadrepoSpec: null,number: prNumber,method: 'merge',- deleteBranch: true,+ deleteBranch: false,expectedHeadSha,});- return result.ok ? { success: true, ...meta } : { success: false, error: result.error, ...meta };+ if (result.code === 'invalid-head') return { success: false, error: result.error, ...meta };++ // A zero exit may mean queued, and a timeout/nonzero exit may follow a+ // completed merge. Read back before reporting success or deleting anything.+ const { execGh } = await import('./github.js');+ const merged = await execGh(['pr', 'view', String(prNumber), '--json',+ 'state,url,headRefName,headRefOid,baseRefName,isCrossRepository,headRepository'],+ undefined, { cwd: dir, env }).then(value => safeJSONParse(value, null), () => null);+ if (merged?.state !== 'MERGED') {+ return { success: false, error: result.error || 'Pull request merge is not yet verified',+ branchCleanup: { deleted: false, reason: 'merge-unverified' }, ...meta };+ }+ if (expectedHeadSha && (typeof merged.headRefOid !== 'string'+ || merged.headRefOid.toLowerCase() !== expectedHeadSha.toLowerCase())) {+ return { success: false, error: 'Merged pull request does not match the reviewed head',+ code: 'reviewed-head-changed', branchCleanup: { deleted: false, reason: 'reviewed-head-changed' }, ...meta };+ }+ const branchCleanup = await deleteVerifiedMergedHead(dir, merged, { expectedHeadSha, host, prNumber, env, account });+ return { success: true, mergedHeadSha: merged.headRefOid, branchCleanup, ...meta };+}++/** Remote cleanup is independent of merge success; local refs and worktrees+ * belong to the archive/ownership cleanup workflow, including ignored files. */+async function deleteVerifiedMergedHead(dir, merged, { expectedHeadSha, host, prNumber, env, account }) {+ const retain = reason => ({ deleted: false, reason });+ if (!expectedHeadSha) return retain('reviewed-head-unavailable');+ const target = parsePullRequestUrl(merged.url);+ if (!target || String(target.number) !== String(prNumber) || target.host.toLowerCase() !== String(host).toLowerCase()) {+ return retain('repository-unverified');+ }+ const fullName = `${target.owner}/${target.repo}`.toLowerCase();+ if (merged.isCrossRepository !== false || typeof merged.headRepository?.nameWithOwner !== 'string'+ || merged.headRepository.nameWithOwner.toLowerCase() !== fullName) {+ return retain('source-repository-unverified');+ }+ const branch = merged.headRefName;+ if (typeof branch !== 'string' || !branch || typeof merged.baseRefName !== 'string' || !merged.baseRefName+ || PROTECTED_BRANCHES.includes(branch) || branch === merged.baseRefName) {+ return retain('protected-or-unknown-source');+ }+ const { execGh } = await import('./github.js');+ const repository = await execGh(['repo', 'view', `${target.host}/${target.owner}/${target.repo}`, '--json', 'defaultBranchRef'],+ undefined, { cwd: dir, env }).then(value => safeJSONParse(value, null), () => null);+ const defaultBranch = repository?.defaultBranchRef?.name;+ if (typeof defaultBranch !== 'string' || !defaultBranch) return retain('default-branch-unverified');+ if (branch === defaultBranch) return retain('protected-default-source');+ // forgeAuth only mints a new environment for a successfully resolved+ // github.com account. A matched account plus ambient GH_TOKEN is not proof.+ if (host !== 'github.com' || !account || env === process.env || !env?.GH_TOKEN) {+ return retain('account-bound-push-unavailable');+ }+ const ref = `refs/heads/${branch}`;+ const valid = await execGitSafe(['check-ref-format', ref], dir);+ if (valid.exitCode !== 0) return retain('invalid-source-ref');+ const urls = await execGitSafe(['remote', 'get-url', '--push', '--all', 'origin'], dir);+ const pushUrls = urls.stdout.trim().split('\n').filter(Boolean);+ if (urls.exitCode !== 0 || pushUrls.length !== 1) return retain('push-target-ambiguous');+ const { parseGitRemoteUrl } = await import('../lib/gitRemote.js');+ const remote = parseGitRemoteUrl(pushUrls[0]);+ if (!remote || remote.host.toLowerCase() !== target.host.toLowerCase()+ || `${remote.owner}/${remote.repo}`.toLowerCase() !== fullName) return retain('push-target-mismatch');+ // SSH keys and embedded credentials can select a different identity from+ // the merge token. Keep those sources for explicit owner cleanup.+ if (!/^https:\/\/[^@/]+\//i.test(pushUrls[0])) return retain('account-bound-push-unavailable');++ // Capture the URL rather than re-resolving a remote name at write time. The+ // lease compares the server's actual ref, never a stale tracking branch.+ const deletion = await execGitSafe(['-c', 'credential.helper=', '-c', 'credential.helper=!gh auth git-credential',+ '-c', 'core.askPass=', 'push', `--force-with-lease=${ref}:${expectedHeadSha}`, '--', pushUrls[0], `:${ref}`], dir,+ { env: { ...env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GH_PROMPT_DISABLED: '1' } });+ if (deletion.exitCode !== 0) return retain('remote-delete-failed-or-uncertain');+ return { deleted: true, branch };}/**diff --git a/server/services/git.mergePR.test.js b/server/services/git.mergePR.test.jsnew file mode 100644index 0000000000..56424c4a2e--- /dev/null+++ b/server/services/git.mergePR.test.js@@ -0,0 +1,199 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { readFile, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { execGit } from '../lib/execGit.js';+import { makeGitSandbox, destroyGitSandbox } from '../lib/gitTestRepo.js';++const fixture = vi.hoisted(() => ({ remote: null, view: null, mergeError: false, viewError: false, queued: false, moveHead: false, defaultBranch: 'main', ambientAuth: false, pushes: [] }));+vi.mock('./forgeAuth.js', () => ({+ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh', env: fixture.ambientAuth ? process.env : { ...process.env, GH_TOKEN: 'fixture-token' }, host: 'github.com', owner: 'fixture', account: 'fixture' })),+ resolveForgeTokenEnv: vi.fn(),+}));+vi.mock('./github.js', () => ({ execGh: vi.fn() }));+vi.mock('./gitlab.js', () => ({ execGlab: vi.fn() }));+// Replace only the synthetic HTTPS transport; Git still applies the real+// exact-ref lease to a private bare repository. No command reaches GitHub.+vi.mock('../lib/childProcess.js', async importOriginal => {+ const original = await importOriginal();+ return { ...original, spawn: (command, args, options) => {+ if (command === 'git' && args.includes('push') && args.includes('https://github.com/fixture/app.git')) {+ fixture.pushes.push({ args: [...args], env: options.env });+ return original.spawn(command, args.map(arg => arg === 'https://github.com/fixture/app.git' ? fixture.remote : arg), options);+ }+ return original.spawn(command, args, options);+ } };+});++import { execGh } from './github.js';+import { mergePR } from './git.js';+import { runForgeMerge } from './appPullRequestMerge.js';++let sandbox, worktree, head;+const git = async (args, cwd = sandbox.repo) => (await execGit(args, cwd)).stdout.trim();+const remoteHead = () => git(['rev-parse', '--verify', 'refs/heads/topic'], sandbox.origin);++beforeEach(async () => {+ vi.clearAllMocks();+ sandbox = await makeGitSandbox({ origin: true, prefix: 'portos-merge-pr-' });+ fixture.remote = sandbox.origin;+ fixture.mergeError = fixture.viewError = fixture.queued = fixture.moveHead = fixture.ambientAuth = false;+ fixture.defaultBranch = 'main';+ fixture.pushes = [];+ worktree = join(sandbox.scratch, 'linked');+ await git(['worktree', 'add', '-b', 'topic', worktree]);+ await writeFile(join(worktree, '.gitignore'), 'ignored-evidence.txt\n');+ await writeFile(join(worktree, 'change.txt'), 'reviewed work\n');+ await git(['add', '.'], worktree);+ await git(['commit', '-m', 'reviewed change'], worktree);+ head = await git(['rev-parse', 'HEAD'], worktree);+ await git(['push', 'origin', 'topic']);+ await git(['remote', 'set-url', '--push', 'origin', 'https://github.com/fixture/app.git']);+ await writeFile(join(worktree, 'ignored-evidence.txt'), 'unique ignored evidence\n');+ fixture.view = { state: 'MERGED', url: 'https://github.com/fixture/app/pull/42', headRefName: 'topic',+ headRefOid: head, baseRefName: 'main', isCrossRepository: false, headRepository: { nameWithOwner: 'fixture/app' } };+ execGh.mockImplementation(async args => {+ if (args[0] === 'repo') return JSON.stringify({ defaultBranchRef: fixture.defaultBranch ? { name: fixture.defaultBranch } : null });+ if (args[1] === 'view') {+ if (fixture.viewError) throw new Error('readback unavailable');+ return JSON.stringify(fixture.view);+ }+ expect(args.slice(0, 3)).toEqual(['pr', 'merge', '42']);+ if (!fixture.queued) {+ await git(['merge', '--no-ff', 'topic', '-m', 'merge reviewed PR']);+ await git(['push', sandbox.origin, 'main']);+ }+ // Model gh's destructive checkout-mode behavior ONLY inside this sandbox.+ // The regression must protect the actual ignored file, not just mock argv.+ if (args.includes('--delete-branch') && !args.includes('--repo')) {+ await git(['worktree', 'remove', '--force', worktree]);+ await git(['branch', '-D', 'topic']);+ await git(['push', sandbox.origin, '--delete', 'topic']);+ }+ if (fixture.moveHead) {+ const tree = await git(['rev-parse', `${head}^{tree}`]);+ const moved = await git(['commit-tree', tree, '-p', head, '-m', 'new source work']);+ await git(['push', sandbox.origin, `${moved}:refs/heads/topic`]);+ }+ if (fixture.mergeError) throw new Error('merge command timed out');+ return '';+ });+});++afterEach(async () => { await destroyGitSandbox(sandbox?.scratch); });++async function expectLocalEvidence() {+ expect(await readFile(join(worktree, 'ignored-evidence.txt'), 'utf8')).toBe('unique ignored evidence\n');+ expect(await git(['rev-parse', 'refs/heads/topic'])).toBe(head);+ expect(await git(['worktree', 'list', '--porcelain'])).toContain('branch refs/heads/topic');+}++describe('mergePR remote cleanup without checkout destruction', () => {+ it('preserves linked worktree and ignored evidence while deleting only the verified merged remote head', async () => {+ const result = await mergePR(sandbox.repo, 42, { expectedHeadSha: head });+ await expectLocalEvidence();+ expect(result).toMatchObject({ success: true, branchCleanup: { deleted: true, branch: 'topic' } });+ expect(await git(['ls-remote', 'origin', 'refs/heads/topic'])).toBe('');+ expect(await git(['merge-base', '--is-ancestor', head, 'main'])).toBe('');+ expect(execGh.mock.calls[0][0]).not.toContain('--delete-branch');+ expect(fixture.pushes).toHaveLength(1);+ expect(fixture.pushes[0].env).toMatchObject({ GH_TOKEN: 'fixture-token', GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '' });+ expect(fixture.pushes[0].args).toEqual(expect.arrayContaining(['credential.helper=', 'credential.helper=!gh auth git-credential', `--force-with-lease=refs/heads/topic:${head}`]));+ });++ it('retains new remote work when its head moves after the merged snapshot', async () => {+ fixture.moveHead = true;+ const result = await mergePR(sandbox.repo, 42, { expectedHeadSha: head });+ expect(result).toMatchObject({ success: true, branchCleanup: { deleted: false, reason: 'remote-delete-failed-or-uncertain' } });+ expect(await remoteHead()).not.toBe(head);+ await expectLocalEvidence();+ });++ it.each([+ ['fork source', { isCrossRepository: true, headRepository: { nameWithOwner: 'fork/app' } }, 'source-repository-unverified'],+ ['inconsistent source identity', { headRepository: { nameWithOwner: 'other/app' } }, 'source-repository-unverified'],+ ['base/source name collision', { baseRefName: 'topic' }, 'protected-or-unknown-source'],+ ['protected source', { headRefName: 'main' }, 'protected-or-unknown-source'],+ ])('retains refs for %s with an explicit reason', async (_name, override, reason) => {+ Object.assign(fixture.view, override);+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: true, branchCleanup: { deleted: false, reason },+ });+ expect(await remoteHead()).toBe(head);+ });++ it('does not report the reviewed change shipped when another head was merged', async () => {+ fixture.view.headRefOid = 'a'.repeat(40);+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: false, code: 'reviewed-head-changed', branchCleanup: { deleted: false, reason: 'reviewed-head-changed' },+ });+ expect(await remoteHead()).toBe(head);+ await expectLocalEvidence();+ });++ it('keeps unpinned legacy callers compatible without assuming deletion authority', async () => {+ expect(await mergePR(sandbox.repo, 42)).toMatchObject({ success: true,+ branchCleanup: { deleted: false, reason: 'reviewed-head-unavailable' } });+ expect(await remoteHead()).toBe(head);+ });++ it('does not target a different push repository or multiple push URLs', async () => {+ // Prevent the mock merge from pushing main through these deliberately+ // unsuitable destinations: the forge readback already reports MERGED.+ fixture.queued = true;+ await git(['remote', 'set-url', '--push', 'origin', 'https://github.test/other/app.git']);+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: true, branchCleanup: { deleted: false, reason: 'push-target-mismatch' },+ });+ await git(['remote', 'set-url', '--add', '--push', 'origin', sandbox.origin]);+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: true, branchCleanup: { deleted: false, reason: 'push-target-ambiguous' },+ });+ expect(await remoteHead()).toBe(head);+ });++ it('retains a custom default source even when the PR targets a different base', async () => {+ await git(['branch', 'trunk', 'topic']);+ await git(['push', sandbox.origin, 'trunk']);+ await git(['symbolic-ref', 'HEAD', 'refs/heads/trunk'], sandbox.origin);+ fixture.view.headRefName = fixture.defaultBranch = 'trunk';+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: true, branchCleanup: { deleted: false, reason: 'protected-default-source' },+ });+ expect(await git(['rev-parse', 'refs/heads/trunk'], sandbox.origin)).toBe(head);+ expect(fixture.pushes).toHaveLength(0);+ });++ it.each(['default-unavailable', 'ambient-token'])('retains the source when %s cannot establish cleanup authority', async mode => {+ if (mode === 'default-unavailable') fixture.defaultBranch = null;+ else fixture.ambientAuth = true;+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({+ success: true, branchCleanup: { deleted: false, reason: mode === 'default-unavailable' ? 'default-branch-unverified' : 'account-bound-push-unavailable' },+ });+ expect(await remoteHead()).toBe(head);+ expect(fixture.pushes).toHaveLength(0);+ });++ it('recognizes an already completed merge after a command error without retrying the merge', async () => {+ fixture.mergeError = true;+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({ success: true, branchCleanup: { deleted: true } });+ expect(execGh.mock.calls.filter(([args]) => args[1] === 'merge')).toHaveLength(1);+ await expectLocalEvidence();+ });++ it.each(['queued', 'unreadable'])('does not claim a %s merge succeeded or delete its source', async mode => {+ fixture.queued = true;+ fixture.view.state = 'OPEN';+ fixture.viewError = mode === 'unreadable';+ expect(await mergePR(sandbox.repo, 42, { expectedHeadSha: head })).toMatchObject({ success: false,+ branchCleanup: { deleted: false, reason: 'merge-unverified' } });+ expect(await remoteHead()).toBe(head);+ await expectLocalEvidence();+ });++ it('guards the shared core even if a checkout-mode caller requests deletion', async () => {+ await runForgeMerge({ cwd: sandbox.repo, forge: 'github', number: 42, deleteBranch: true, expectedHeadSha: head });+ await expectLocalEvidence();+ expect(await remoteHead()).toBe(head);+ expect(execGh.mock.calls[0][0]).not.toContain('--delete-branch');+ });+});