From fd1050d97761eb3ef760afc6a1c591570e2b4acc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 31 Aug 2026 12:56:14 +0000 Subject: [PATCH 1/2] fix(repoSync): advance the bare clone's branch on fetch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `git clone --bare` creates no `remote.origin.fetch` refspec, so the sync's `git fetch --prune origin` had nothing to apply: it downloaded objects, wrote FETCH_HEAD, and left `refs/heads/` pointing wherever the original clone left it. Sync reported success on every cycle while the clone never moved, so every run worktreed the repository as it stood when it was first added. Fetch an explicit forced refspec for the repo's default branch, which is what actually advances the branch. No `--prune`: with an explicit refspec it would delete the clone's only branch as soon as that branch disappears upstream, leaving nothing to worktree from. The credential now travels as the fetch URL rather than being written to the clone's config first. That write was the only reason a routine sync touched `/config`, and it is the step that breaks first when the data volume fills — git rewrites the whole file through `config.lock`, so a failed write aborted the sync before git had even tried to fetch. The stored URL is still refreshed for `git lfs fetch`, but best-effort and only when it changed. Co-authored-by: Doug Rathbone --- src/server/gitOps.test.ts | 60 +++++++++++++++++++++++-- src/server/gitOps.ts | 75 +++++++++++++++++++++++++++++--- src/server/repoSync.auth.test.ts | 27 +++++++++++- src/server/repoSync.ts | 2 +- 4 files changed, 154 insertions(+), 10 deletions(-) diff --git a/src/server/gitOps.test.ts b/src/server/gitOps.test.ts index fb86944..163fa68 100644 --- a/src/server/gitOps.test.ts +++ b/src/server/gitOps.test.ts @@ -5,6 +5,10 @@ import { EventEmitter } from 'events' // child fails `git worktree add` with an out-of-disk stderr dump and succeeds // any other subcommand (e.g. the `worktree remove` cleanup). const spawnCalls: string[][] = [] +/** What `git config --get remote.origin.url` reports; undefined ⇒ key unset. */ +let storedOriginUrl: string | undefined +/** When true, `git remote set-url` fails (e.g. a full data volume). */ +let setUrlFails = false vi.mock('child_process', () => ({ spawn: vi.fn((_cmd: string, args: string[]) => { spawnCalls.push(args) @@ -18,6 +22,16 @@ vi.mock('child_process', () => ({ Buffer.from('Updating files: 67% (19493/29094)\nerror: unable to create file x: No space left on device\n') ) child.emit('close', 128) + } else if (args[0] === 'config' && args[1] === '--get') { + if (storedOriginUrl === undefined) return child.emit('close', 1) + child.stdout.emit('data', Buffer.from(`${storedOriginUrl}\n`)) + child.emit('close', 0) + } else if (setUrlFails && args[0] === 'remote' && args[1] === 'set-url') { + child.stderr.emit( + 'data', + Buffer.from('error: failed to write new configuration file /clone/config.lock\n') + ) + child.emit('close', 128) } else { child.emit('close', 0) } @@ -26,7 +40,13 @@ vi.mock('child_process', () => ({ }), })) -import { redactCredentials, buildAuthUrl, isDiskFullError, createWorktree } from './gitOps' +import { redactCredentials, buildAuthUrl, isDiskFullError, createWorktree, fetchRepo } from './gitOps' + +beforeEach(() => { + spawnCalls.length = 0 + storedOriginUrl = undefined + setUrlFails = false +}) describe('redactCredentials', () => { it('redacts an embedded token in an https URL', () => { @@ -54,9 +74,43 @@ describe('isDiskFullError', () => { }) }) -describe('createWorktree', () => { - beforeEach(() => { spawnCalls.length = 0 }) +describe('fetchRepo', () => { + it('fetches an explicit refspec so the bare clone\'s branch actually advances', async () => { + await fetchRepo('/clone', 'https://github.com/acme/widgets.git', 'main', 'ghs_token') + + const fetch = spawnCalls.find((a) => a[0] === 'fetch')! + expect(fetch).toContain('+refs/heads/main:refs/heads/main') + }) + + it('fetches the credentialed URL directly rather than relying on the stored remote', async () => { + storedOriginUrl = 'https://x-access-token:ghs_expired@github.com/acme/widgets.git' + await fetchRepo('/clone', 'https://github.com/acme/widgets.git', 'main', 'ghs_token') + const fetch = spawnCalls.find((a) => a[0] === 'fetch')! + expect(fetch[1]).toBe('https://x-access-token:ghs_token@github.com/acme/widgets.git') + }) + + it('rewrites the stored origin only when the credential changed', async () => { + storedOriginUrl = 'https://x-access-token:ghs_token@github.com/acme/widgets.git' + await fetchRepo('/clone', 'https://github.com/acme/widgets.git', 'main', 'ghs_token') + + expect(spawnCalls.some((a) => a[0] === 'remote' && a[1] === 'set-url')).toBe(false) + + spawnCalls.length = 0 + await fetchRepo('/clone', 'https://github.com/acme/widgets.git', 'main', 'ghs_rotated') + expect(spawnCalls.some((a) => a[0] === 'remote' && a[1] === 'set-url')).toBe(true) + }) + + it('still fetches when the stored origin cannot be rewritten', async () => { + setUrlFails = true + await expect( + fetchRepo('/clone', 'https://github.com/acme/widgets.git', 'main', 'ghs_token') + ).resolves.toBeUndefined() + expect(spawnCalls.some((a) => a[0] === 'fetch')).toBe(true) + }) +}) + +describe('createWorktree', () => { it('tears down the partial worktree and reports out-of-space when the checkout runs out of disk', async () => { await expect(createWorktree('/clone', '/clone/worktrees-run/r1', 'master')).rejects.toThrow(/disk space/i) diff --git a/src/server/gitOps.ts b/src/server/gitOps.ts index 3ec667e..7c6c455 100644 --- a/src/server/gitOps.ts +++ b/src/server/gitOps.ts @@ -162,13 +162,78 @@ export async function cloneRepo( } /** - * Fetch latest changes into a bare clone. + * The refspec a bare-clone sync has to fetch with, for one branch. + * + * `git clone --bare` copies the remote's heads straight to local heads and, as + * its own documentation states, creates "neither remote-tracking branches nor + * the related configuration variables" — there is no `remote.origin.fetch`. A + * plain `git fetch origin` in such a clone therefore has no refspec to apply: it + * downloads objects, writes FETCH_HEAD, and leaves `refs/heads/` exactly + * where the original clone left it. Sync reported success on every cycle while + * the clone never moved, so every run worktreed the repository as it stood when + * it was first added. Naming the destination explicitly is what actually + * advances the branch; `+` keeps an upstream force-push from failing the sync. + * Run worktrees are detached (see {@link createWorktree}), so this branch is + * never checked out anywhere and updating it is always allowed. + */ +export function branchFetchRefspec(branch: string): string { + return `+refs/heads/${branch}:refs/heads/${branch}` +} + +/** + * Point the stored `remote.origin.url` at the current credential — best-effort, + * and only when it actually differs. + * + * The sync no longer depends on this (see {@link fetchRepo}), but other paths + * read the stored remote: `git lfs fetch` inside a run's worktree resolves + * `origin` from this same config, so a private LFS repo needs a usable token + * there. It must never fail the sync, though, because rewriting `config` is the + * step that breaks first when the data volume fills: git rewrites the whole file + * through `config.lock`, so a failed write aborted the sync before git had even + * tried to fetch — and an already-up-to-date repo needs no space at all. + */ +async function refreshStoredOriginUrl(clonePath: string, authUrl: string): Promise { + // `git config --get` exits non-zero when the key is unset; that's "differs". + const stored = await runGit(['config', '--get', 'remote.origin.url'], { cwd: clonePath }).catch( + () => undefined + ) + if (stored === authUrl) return + try { + await runGit(['remote', 'set-url', 'origin', authUrl], { cwd: clonePath }) + } catch (err) { + console.warn( + `[gitOps] could not update the stored origin URL for ${clonePath}: ` + + `${err instanceof Error ? err.message : String(err)}` + ) + } +} + +/** + * Fetch latest changes for `branch` into a bare clone. + * + * The credential goes straight to the fetch as a URL instead of being written to + * the clone's config first. Persisting it was the only reason a routine sync + * wrote to `/config`, and that write also contends with the per-run + * {@link configureWorktreeGit} calls, which land in the very same shared config + * file; naming the URL per-invocation makes the fetch independent of both. (A + * `-c remote.origin.url=…` override does *not* substitute here: `url` is a + * multi-valued remote key, so a command-line value is appended to the stored + * list rather than replacing it, and git still dials the stored URL first.) */ -export async function fetchRepo(clonePath: string, url: string, pat?: string): Promise { +export async function fetchRepo( + clonePath: string, + url: string, + branch: string, + pat?: string +): Promise { const authUrl = buildAuthUrl(url, pat) - // Set the remote URL in case the PAT changed, then fetch - await runGit(['remote', 'set-url', 'origin', authUrl], { cwd: clonePath }) - await runGit(['fetch', '--prune', 'origin'], { cwd: clonePath }) + await refreshStoredOriginUrl(clonePath, authUrl) + // No `--prune`: with an explicit refspec it would delete the clone's only + // branch the moment the branch disappears upstream, leaving a clone nothing + // can be worktreed from. Without it that case fails loudly ("couldn't find + // remote ref") and the last good ref survives. A single-branch bare clone has + // no other refs to prune anyway. + await runGit(['fetch', authUrl, branchFetchRefspec(branch)], { cwd: clonePath }) } /** True when a git error indicates the filesystem is out of space (ENOSPC). */ diff --git a/src/server/repoSync.auth.test.ts b/src/server/repoSync.auth.test.ts index bbc4179..38b5abb 100644 --- a/src/server/repoSync.auth.test.ts +++ b/src/server/repoSync.auth.test.ts @@ -1,4 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' +import * as fs from 'fs' +import * as os from 'os' +import * as path from 'path' import type { Repository } from '../shared/types' // Stub the impure dependencies (persistence, git, auth, reporter) so importing @@ -23,7 +26,7 @@ import { RepoSyncService } from './repoSync' import { reporter } from './observability' import { getRepository, updateRepository } from '../main/db/queries/repositories' import { resolveRepoToken } from './githubApp' -import { cloneRepo } from './gitOps' +import { cloneRepo, fetchRepo } from './gitOps' const PAT_REPO: Repository = { id: 'repo-1', @@ -104,4 +107,26 @@ describe('RepoSyncService credential failures', () => { expect.objectContaining({ tags: expect.objectContaining({ op: 'clone' }) }) ) }) + + // The clone can only be fetched for a branch it is told to fetch — see + // branchFetchRefspec — so the repo's default branch has to reach fetchRepo. + it('syncs an existing clone against the repo default branch', async () => { + const clonePath = fs.mkdtempSync(path.join(os.tmpdir(), 'conduit-repo-sync-')) + vi.mocked(getRepository).mockResolvedValue({ ...PAT_REPO, syncStatus: 'ready', clonePath }) + vi.mocked(resolveRepoToken).mockResolvedValue('ghs_token') + + try { + await new RepoSyncService(vi.fn()).syncRepo(PAT_REPO.id) + } finally { + fs.rmSync(clonePath, { recursive: true, force: true }) + } + + expect(cloneRepo).not.toHaveBeenCalled() + expect(fetchRepo).toHaveBeenCalledWith( + clonePath, + PAT_REPO.url, + PAT_REPO.defaultBranch, + 'ghs_token' + ) + }) }) diff --git a/src/server/repoSync.ts b/src/server/repoSync.ts index 3b7d8d9..d966c8d 100644 --- a/src/server/repoSync.ts +++ b/src/server/repoSync.ts @@ -146,7 +146,7 @@ export class RepoSyncService { // Repo exists on disk — do a fetch await this.updateStatus(repoId, 'syncing') try { - await fetchRepo(repo.clonePath, repo.url, token) + await fetchRepo(repo.clonePath, repo.url, repo.defaultBranch, token) await this.recordSyncSuccess(repoId) } catch (err) { await this.recordSyncFailure(repoId, err, 'fetch') From d49298db12e170ccad3529a51feac8f4fa1c34e7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 31 Aug 2026 12:56:32 +0000 Subject: [PATCH 2/2] fix(repoSync): report an out-of-space git failure as one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git's config writer reports a failed write through `write_error()`, which formats with `error()` rather than `error_errno()`. The errno is dropped, so an out-of-space config write arrives with no "No space left on device" for `isDiskFullError` to match, and the repository owner saw the raw dump instead: git remote failed (exit 128): error: failed to write new configuration file /data/repos//config.lock fatal: could not set 'remote.origin.url' to 'https://***@github.com/…' That message is only reachable after git created and opened the lock file, so it is neither a permission problem nor a stale lock (both fail earlier, with "could not lock config file") — the write itself failed, which in practice means the volume is full or over quota. Recognise it, and translate a disk-full clone/fetch failure into the actionable message the worktree path already used, so the repositories UI says what to do. Such failures report as a message rather than an exception: the raw text embeds the clone path, which splintered one operational problem into a separate issue per repository. Co-authored-by: Doug Rathbone --- src/server/gitOps.test.ts | 13 ++++++++++++ src/server/gitOps.ts | 36 +++++++++++++++++++++++++------- src/server/repoSync.auth.test.ts | 29 ++++++++++++++++++++++++- src/server/repoSync.ts | 18 ++++++++++++++-- 4 files changed, 86 insertions(+), 10 deletions(-) diff --git a/src/server/gitOps.test.ts b/src/server/gitOps.test.ts index 163fa68..c47ba39 100644 --- a/src/server/gitOps.test.ts +++ b/src/server/gitOps.test.ts @@ -68,9 +68,22 @@ describe('isDiskFullError', () => { expect(isDiskFullError('error: ... No space left on device')).toBe(true) expect(isDiskFullError('spawn git ENOSPC')).toBe(true) }) + // git's config writer drops the errno, so this out-of-space failure arrives + // with no "No space left on device" to match on. + it('detects a config write that ran out of space', () => { + expect( + isDiskFullError( + 'git remote failed (exit 128): error: failed to write new configuration file ' + + "/data/repos/9f7404af-a623-4d35-9a59-267aeb88389f/config.lock\n" + + "fatal: could not set 'remote.origin.url' to 'https://***@github.com/acme/widgets.git'" + ) + ).toBe(true) + }) it('is false for unrelated failures', () => { expect(isDiskFullError("fatal: 'master' is already checked out")).toBe(false) expect(isDiskFullError('fatal: repository not found')).toBe(false) + // A lock that could not be *taken* is contention or permissions, not space. + expect(isDiskFullError('error: could not lock config file config: File exists')).toBe(false) }) }) diff --git a/src/server/gitOps.ts b/src/server/gitOps.ts index 7c6c455..4315b83 100644 --- a/src/server/gitOps.ts +++ b/src/server/gitOps.ts @@ -236,9 +236,35 @@ export async function fetchRepo( await runGit(['fetch', authUrl, branchFetchRefspec(branch)], { cwd: clonePath }) } -/** True when a git error indicates the filesystem is out of space (ENOSPC). */ +/** + * True when a git error indicates the filesystem is out of space. + * + * Most such failures carry an errno string ("No space left on device"), but + * git's config writer does not: a failed write is reported through its + * `write_error()` helper, which formats with `error()` rather than + * `error_errno()`, so the errno is dropped and all the operator sees is + * + * error: failed to write new configuration file /data/repos//config.lock + * fatal: could not set 'remote.origin.url' to 'https://***@github.com/…' + * + * That message is only reachable *after* git created and opened the lock file, + * so it is neither a permission problem nor a stale lock — both of those fail + * earlier with "could not lock config file". The write itself failed, which in + * practice means the volume is full or over quota. + */ export function isDiskFullError(message: string): boolean { - return /no space left on device|\bENOSPC\b/i.test(message) + return ( + /no space left on device|\bENOSPC\b/i.test(message) || + /failed to write new configuration file/i.test(message) + ) +} + +/** Actionable operator-facing replacement for a raw git out-of-space dump. */ +export function diskFullMessage(action: string): string { + return ( + `Not enough disk space to ${action}. ` + + 'Free space on the Conduit server or increase its data volume, then retry.' + ) } /** True when a git error is `git gc` refusing to run because another gc holds @@ -281,11 +307,7 @@ export async function createWorktree( await removeWorktree(clonePath, worktreePath).catch(() => {}) const message = err instanceof Error ? err.message : String(err) if (isDiskFullError(message)) { - throw new Error( - 'Not enough disk space to create a worktree for this repository. ' + - 'Free space on the Conduit server or increase its data volume, then retry.', - { cause: err } - ) + throw new Error(diskFullMessage('create a worktree for this repository'), { cause: err }) } throw err instanceof Error ? err : new Error(message) } diff --git a/src/server/repoSync.auth.test.ts b/src/server/repoSync.auth.test.ts index 38b5abb..bcf1e19 100644 --- a/src/server/repoSync.auth.test.ts +++ b/src/server/repoSync.auth.test.ts @@ -17,7 +17,8 @@ vi.mock('../main/db/queries/repositories', () => ({ vi.mock('./githubApp', () => ({ resolveRepoToken: vi.fn(), })) -vi.mock('./gitOps', () => ({ +vi.mock('./gitOps', async (importOriginal) => ({ + ...(await importOriginal()), cloneRepo: vi.fn(), fetchRepo: vi.fn(), })) @@ -108,6 +109,32 @@ describe('RepoSyncService credential failures', () => { ) }) + // A full data volume used to reach the owner as a raw git dump naming an + // internal lock file, which says nothing about what to do next. + it('replaces an out-of-space git failure with an actionable syncError', async () => { + vi.mocked(resolveRepoToken).mockResolvedValue('ghs_token') + vi.mocked(cloneRepo).mockRejectedValue( + new Error( + 'git remote failed (exit 128): error: failed to write new configuration file ' + + '/data/repos/repo-1/config.lock' + ) + ) + + await new RepoSyncService(vi.fn()).syncRepo(PAT_REPO.id) + + expect(updateRepository).toHaveBeenCalledWith(PAT_REPO.id, { + syncStatus: 'error', + syncError: expect.stringMatching(/not enough disk space to clone this repository/i), + }) + // Reported as a message so every repo's out-of-space failure groups as one + // issue, with the raw git text kept as context. + expect(reporter.captureException).not.toHaveBeenCalled() + const [message, level, ctx] = vi.mocked(reporter.captureMessage).mock.calls[0] + expect(message).toMatch(/disk space/i) + expect(level).toBe('error') + expect(ctx?.extra?.gitError).toMatch(/failed to write new configuration file/) + }) + // The clone can only be fetched for a branch it is told to fetch — see // branchFetchRefspec — so the repo's default branch has to reach fetchRepo. it('syncs an existing clone against the repo default branch', async () => { diff --git a/src/server/repoSync.ts b/src/server/repoSync.ts index d966c8d..b80f3ef 100644 --- a/src/server/repoSync.ts +++ b/src/server/repoSync.ts @@ -1,6 +1,6 @@ import * as fs from 'fs' import { listRepositories, getRepository, updateRepository } from '../main/db/queries/repositories' -import { cloneRepo, fetchRepo } from './gitOps' +import { cloneRepo, fetchRepo, isDiskFullError, diskFullMessage } from './gitOps' import { resolveRepoToken } from './githubApp' import { DEV_CONTEXT } from './auth/config' import { reporter } from './observability' @@ -36,6 +36,11 @@ export function isInSyncBackoff(state: SyncFailureState | undefined, now: number return state !== undefined && now < state.nextAttemptAt } +/** How to describe the failed sync step in an operator-facing message. */ +function syncAction(op: string): string { + return op === 'clone' ? 'clone this repository' : 'sync this repository' +} + /** * Background service that keeps repository clones up-to-date. */ @@ -176,6 +181,11 @@ export class RepoSyncService { * `expected` failures are user-fixable misconfigurations (e.g. a PAT-auth repo * with no global PAT configured): the owner sees them via `syncError`, so they * go out as a warning-level message instead of an error-level exception. + * + * An out-of-space failure is reported as a message rather than an exception: + * the raw git text embeds the clone's path, which splinters one operational + * problem into a separate Sentry issue per repository. The raw text is kept as + * context. */ private async recordSyncFailure( repoId: string, @@ -185,11 +195,15 @@ export class RepoSyncService { ): Promise { const prev = this.failures.get(repoId) this.failures.set(repoId, nextSyncBackoff(prev, Date.now())) - const message = err instanceof Error ? err.message : String(err) + const raw = err instanceof Error ? err.message : String(err) + const diskFull = isDiskFullError(raw) + const message = diskFull ? diskFullMessage(syncAction(op)) : raw if (!prev) { const tags = { component: 'repoSync', repoId, op } if (opts?.expected) { reporter.captureMessage(message, 'warning', { tags }) + } else if (diskFull) { + reporter.captureMessage(message, 'error', { tags, extra: { gitError: raw } }) } else { reporter.captureException(err, { tags }) }