Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix: run git preflight at the project-setup boundary (#2230)

Nick Gomez85ee4b2be59a
diff --git a/.changeset/git-preflight-project-setup-boundary.md b/.changeset/git-preflight-project-setup-boundary.md
new file mode 100644
index 000000000..5229a277e
--- /dev/null
+++ b/.changeset/git-preflight-project-setup-boundary.md
@@ -0,0 +1,10 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-server": patch
+---
+
+Run the git preflight at the project-setup boundary so a broken or PATH-invisible git surfaces recoverable install/upgrade guidance instead of a raw error.
+
+Creating a project, opening a folder, cloning from GitHub, and `ok init` now verify git is usable before invoking it, and run against the exact git the preflight validated (the resolved path for in-process git, or an enriched PATH for the spawned clone). When git is missing or unusable they report platform-specific install guidance; `ok init` exits 78 (EX_CONFIG) on a git-preflight failure, matching `ok start`.
+
+These setup paths now require git 2.31 or newer — the same floor `ok start` and the desktop app already enforce at launch.
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index f6cc06717..032acc02d 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -3,6 +3,7 @@ import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import type { Config } from '@inkeep/open-knowledge-server';
import type { TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import {
@@ -17,6 +18,7 @@ import {
isBranchNotFoundError,
resolveClonePrincipal,
resolveCloneUrl,
+ runClone,
shouldSkipAuthForPublicRepo,
} from './clone.ts';
@@ -749,3 +751,31 @@ describe('emitCloneFailure', () => {
expect(c1.stderr.join('')).toBe(c2.stderr.join(''));
});
});
+
+describe('runClone git preflight', () => {
+ it('git unusable everywhere → runClone surfaces the recoverable GitNotAvailableError', async () => {
+ const originalPath = process.env.PATH;
+ const originalPlatform = process.platform;
+ process.env.PATH = '/nonexistent';
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform === 'win32' ? 'linux' : 'win32',
+ configurable: true,
+ });
+ try {
+ const { GitNotAvailableError } = await import('@inkeep/open-knowledge-server');
+ const cwd = join(
+ tmpdir(),
+ `ok-clone-preflight-${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ );
+ await expect(
+ runClone('inkeep/playbooks', { json: true }, {} as unknown as Config, cwd),
+ ).rejects.toBeInstanceOf(GitNotAvailableError);
+ } finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
+ process.env.PATH = originalPath;
+ }
+ });
+});
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index c88e7e9e1..6a01e584a 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -7,7 +7,12 @@ import {
isLoginFixableGitAuthError,
shellSingleQuote,
} from '@inkeep/open-knowledge-core';
-import type { Config } from '@inkeep/open-knowledge-server';
+import {
+ assertGitAvailable,
+ type Config,
+ GitNotAvailableError,
+ GitTooOldError,
+} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
import { resolveAuth } from '../auth/resolve-auth.ts';
@@ -125,7 +130,7 @@ export function resolveCloneUrl(
return isShorthand ? `https://${parsed.hostname}/${ownerRepo}` : rawUrl;
}
-async function runClone(
+export async function runClone(
url: string,
opts: CloneOptions,
_config: Config,
@@ -146,6 +151,8 @@ async function runClone(
}
}
+ assertGitAvailable();
+
const tokenStore = makeLazyTokenStore();
const shouldProbe = parsed.protocol === 'https' && parsed.hostname === 'github.com';
@@ -373,6 +380,15 @@ export function cloneCommand(getConfig: () => Config): Command {
await startCmd.parseAsync([], { from: 'user' });
}
} catch (err) {
+ if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ if (opts.json) {
+ emit(true, { type: 'error', message: err.message });
+ } else {
+ process.stderr.write(`${err.message}\n`);
+ }
+ process.exitCode = 78;
+ return;
+ }
await handleCloneFailure({
error: err,
url,
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index da2b2a3eb..c31801b7c 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -1204,15 +1204,24 @@ describe('runInit', () => {
expect(readFileSync(sentinel, 'utf-8')).toBe('do-not-clobber');
});
- it('git-missing environment → runInit throws ProjectGitInitError (no content scaffolded)', async () => {
+ it('git unusable everywhere → runInit surfaces the recoverable GitNotAvailableError (no content scaffolded)', async () => {
const originalPath = process.env.PATH;
+ const originalPlatform = process.platform;
process.env.PATH = '/nonexistent';
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform === 'win32' ? 'linux' : 'win32',
+ configurable: true,
+ });
try {
- const { ProjectGitInitError } = await import('@inkeep/open-knowledge-server');
+ const { GitNotAvailableError } = await import('@inkeep/open-knowledge-server');
await expect(runInitForTest({ editors: ['claude'] })).rejects.toBeInstanceOf(
- ProjectGitInitError,
+ GitNotAvailableError,
);
} finally {
+ Object.defineProperty(process, 'platform', {
+ value: originalPlatform,
+ configurable: true,
+ });
process.env.PATH = originalPath;
}
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 5453dc425..b72c336bc 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -7,6 +7,8 @@ import type {
} from '@inkeep/open-knowledge-server';
import {
ensureProjectGit,
+ GitNotAvailableError,
+ GitTooOldError,
initContent,
installUserSkill,
MCP_SERVER_NAME,
@@ -1136,9 +1138,14 @@ export function initCommand(): Command {
sharing,
});
} catch (err) {
+ if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ process.stderr.write(`${err.message}\n`);
+ process.exitCode = 78;
+ return;
+ }
if (err instanceof ProjectGitInitError) {
process.stderr.write(
- "open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.\n",
+ "open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.\n",
);
if (err.stderr) process.stderr.write(`${err.stderr.trim()}\n`);
process.exitCode = 1;
diff --git a/packages/server/src/git-preflight.ts b/packages/server/src/git-preflight.ts
index ae23c077f..b1aa3936c 100644
--- a/packages/server/src/git-preflight.ts
+++ b/packages/server/src/git-preflight.ts
@@ -163,6 +163,10 @@ export function __resetResolveOnPathCacheForTests(): void {
resolveOnPathCache.clear();
}
+export function __seedResolveOnPathCacheForTests(name: string, resolvedPath: string): void {
+ resolveOnPathCache.set(name, resolvedPath);
+}
+
export function resolveOnPath(name: string): string | null {
if (!SAFE_COMMAND_NAME_RE.test(name)) return null;
const cached = resolveOnPathCache.get(name);
diff --git a/packages/server/src/git-unusable-setup.test-helper.ts b/packages/server/src/git-unusable-setup.test-helper.ts
new file mode 100644
index 000000000..e219aefe5
--- /dev/null
+++ b/packages/server/src/git-unusable-setup.test-helper.ts
@@ -0,0 +1,76 @@
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const BROKEN_GIT_STDERR =
+ "xcrun: error: unable to load libxcrun (dlopen(/Applications/Xcode.app/Contents/Developer/usr/lib/libxcrun.dylib, 0x0005): tried: '/Applications/Xcode.app/Contents/Developer/usr/lib/libxcrun.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'arm64e')), '/System/Volumes/Preboot/Cryptexes/OS/Applications/Xcode.app/Contents/Developer/usr/lib/libxcrun.dylib' (no such file)).";
+
+function makeBrokenGitDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'ok356-brokengit-'));
+ const gitPath = join(dir, 'git');
+ writeFileSync(
+ gitPath,
+ `#!/bin/sh\n# Present-but-broken git stub — catch-all: every subcommand fails identically.\necho ${JSON.stringify(BROKEN_GIT_STDERR)} >&2\nexit 1\n`,
+ 'utf-8',
+ );
+ chmodSync(gitPath, 0o755);
+ return dir;
+}
+
+async function withBrokenGitDir(fn: (dir: string) => Promise<void>): Promise<void> {
+ const dir = makeBrokenGitDir();
+ try {
+ await fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function setPlatform(value: NodeJS.Platform): void {
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+}
+
+export async function withBrokenBareGitOnly(fn: () => Promise<void>): Promise<void> {
+ await withBrokenGitDir(async (dir) => {
+ const origPath = process.env.PATH;
+ process.env.PATH = dir;
+ try {
+ await fn();
+ } finally {
+ if (origPath === undefined) delete process.env.PATH;
+ else process.env.PATH = origPath;
+ }
+ });
+}
+
+export async function withUnusableGitEverywhere(fn: () => Promise<void>): Promise<void> {
+ await withBrokenGitDir(async (dir) => {
+ const origPath = process.env.PATH;
+ const origPlatform = process.platform;
+ process.env.PATH = dir;
+ setPlatform(origPlatform === 'win32' ? 'linux' : 'win32');
+ try {
+ await fn();
+ } finally {
+ setPlatform(origPlatform);
+ if (origPath === undefined) delete process.env.PATH;
+ else process.env.PATH = origPath;
+ }
+ });
+}
+
+export function isRecoverableGitSignal(value: unknown): boolean {
+ if (value == null) return false;
+ const code = (value as { code?: unknown }).code;
+ if (code === 'GIT_NOT_AVAILABLE' || code === 'GIT_TOO_OLD') return true;
+ const name = (value as { name?: unknown }).name;
+ if (name === 'GitNotAvailableError' || name === 'GitTooOldError') return true;
+ const msg = value instanceof Error ? value.message : typeof value === 'string' ? value : '';
+ return (
+ msg.includes('GIT_NOT_AVAILABLE') ||
+ msg.includes('GIT_TOO_OLD') ||
+ msg.includes('OpenKnowledge needs Git') ||
+ msg.includes('OpenKnowledge requires Git') ||
+ msg.includes('ok diagnose health')
+ );
+}
diff --git a/packages/server/src/local-ops/clone-flow.preflight.test.ts b/packages/server/src/local-ops/clone-flow.preflight.test.ts
new file mode 100644
index 000000000..da3340a59
--- /dev/null
+++ b/packages/server/src/local-ops/clone-flow.preflight.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, isAbsolute, join } from 'node:path';
+import {
+ __resetResolveOnPathCacheForTests,
+ __seedResolveOnPathCacheForTests,
+} from '../git-preflight.ts';
+import {
+ isRecoverableGitSignal,
+ withBrokenBareGitOnly,
+ withUnusableGitEverywhere,
+} from '../git-unusable-setup.test-helper.ts';
+import { type RawCloneEvent, runCloneSubprocess } from './clone-flow.ts';
+
+/** A fake "CLI" (matching clone-flow.test.ts) that, IF the clone op reaches the
+ * spawn, fails the way a broken host git does — a raw clone error with no
+ * recoverable git-preflight signal. The fixed code must preflight BEFORE this
+ * ever runs. */
+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];
+const RAW_GIT_FAILURE_CLI = fixtureCli(
+ `process.stderr.write("xcrun: error: unable to load libxcrun (... incompatible architecture (have 'arm64', need 'arm64e')) ...\\n"); process.exit(128);`,
+);
+
+type CloneOutcome = string;
+
+function classifyCloneOutcome(
+ syncThrow: unknown,
+ doneErr: unknown,
+ events: readonly RawCloneEvent[],
+): CloneOutcome {
+ if (isRecoverableGitSignal(syncThrow)) return 'recoverable-git-preflight-signal';
+ if (isRecoverableGitSignal(doneErr)) return 'recoverable-git-preflight-signal';
+ if (events.some((e) => e.type === 'error' && isRecoverableGitSignal(e.message))) {
+ return 'recoverable-git-preflight-signal';
+ }
+ const errEvent = events.find(
+ (e): e is Extract<RawCloneEvent, { type: 'error' }> => e.type === 'error',
+ );
+ if (errEvent) return `raw-clone-error: ${errEvent.message}`;
+ if (events.some((e) => e.type === 'complete')) return 'completed-as-if-success';
+ if (doneErr) return `done-rejected: ${doneErr instanceof Error ? doneErr.name : String(doneErr)}`;
+ if (syncThrow) return `threw: ${syncThrow instanceof Error ? syncThrow.name : String(syncThrow)}`;
+ return 'no-signal';
+}
+
+describe('runCloneSubprocess — git-preflight at the clone-setup boundary (#356)', () => {
+ test('surfaces the recoverable git-preflight signal (not a raw clone error) when git is unusable', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok356-clone-'));
+ const events: RawCloneEvent[] = [];
+ let syncThrow: unknown;
+ let doneErr: unknown;
+ try {
+ await withUnusableGitEverywhere(async () => {
+ let controller: ReturnType<typeof runCloneSubprocess> | undefined;
+ try {
+ controller = runCloneSubprocess({
+ cliArgs: RAW_GIT_FAILURE_CLI,
+ url: 'https://github.com/octocat/hello.git',
+ dir,
+ timeoutMs: 30_000,
+ onEvent: (e) => events.push(e),
+ });
+ } catch (err) {
+ syncThrow = err;
+ return;
+ }
+ try {
+ await controller.done;
+ } catch (err) {
+ doneErr = err;
+ }
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+
+ const outcome = classifyCloneOutcome(syncThrow, doneErr, events);
+ expect(outcome).toBe('recoverable-git-preflight-signal');
+ });
+});
+
+/** A fake CLI that records the PATH it was spawned with (so the test can assert
+ * how `runCloneSubprocess` enriched the clone child's PATH) then emits a
+ * terminal `complete` so the controller resolves. */
+function pathCapturingCli(pathFile: string, dir: string): readonly string[] {
+ return [
+ process.execPath,
+ '-e',
+ `require('node:fs').writeFileSync(${JSON.stringify(pathFile)}, process.env.PATH ?? ''); console.log(JSON.stringify({ type: 'complete', dir: ${JSON.stringify(dir)} }));`,
+ ];
+}
+
+describe('runCloneSubprocess — clone-child PATH binding (#356)', () => {
+ test('enriches the clone child PATH with the absolute dir of the validated fallback git', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok356-clonebind-'));
+ const pathFile = join(dir, 'observed-path.txt');
+ try {
+ await withBrokenBareGitOnly(async () => {
+ const controller = runCloneSubprocess({
+ cliArgs: pathCapturingCli(pathFile, dir),
+ url: 'https://github.com/octocat/hello.git',
+ dir,
+ timeoutMs: 30_000,
+ onEvent: () => {},
+ });
+ await controller.done;
+ });
+
+ const observed = readFileSync(pathFile, 'utf-8');
+ const firstSegment = observed.split(delimiter)[0];
+ expect(isAbsolute(firstSegment)).toBe(true);
+ expect(existsSync(join(firstSegment, 'git'))).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('does not prepend a relative "." to the clone child PATH when the resolved git path is the bare name', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok356-clonepath-'));
+ const pathFile = join(dir, 'observed-path.txt');
+ __resetResolveOnPathCacheForTests();
+ __seedResolveOnPathCacheForTests('git', 'git');
+ try {
+ const controller = runCloneSubprocess({
+ cliArgs: pathCapturingCli(pathFile, dir),
+ url: 'https://github.com/octocat/hello.git',
+ dir,
+ timeoutMs: 30_000,
+ onEvent: () => {},
+ });
+ await controller.done;
+
+ const observed = readFileSync(pathFile, 'utf-8');
+ const firstSegment = observed.split(delimiter)[0];
+ expect(firstSegment).not.toBe('.');
+ } finally {
+ __resetResolveOnPathCacheForTests();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.ts
index 5158e1cbd..11d88404c 100644
--- a/packages/server/src/local-ops/clone-flow.ts
+++ b/packages/server/src/local-ops/clone-flow.ts
@@ -1,6 +1,17 @@
+import { dirname, isAbsolute } from 'node:path';
+import {
+ assertGitAvailable,
+ type GitDetected,
+ GitNotAvailableError,
+ GitTooOldError,
+} from '../git-preflight.ts';
+import { emitPreflightFailureSpan } from '../git-preflight-telemetry.ts';
import { expandTilde, isAllowedGitUrl, isSafeLocalPath } from '../local-op-security.ts';
+import { getLogger } from '../logger.ts';
import { runSubprocess } from './subprocess.ts';
+const log = getLogger('clone-flow');
+
export type RawCloneEvent =
| { type: 'progress'; phase: string; pct: number }
| { type: 'complete'; dir: string }
@@ -64,6 +75,39 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {
const targetDir = expandTilde(opts.dir);
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ let detected: GitDetected;
+ try {
+ detected = assertGitAvailable();
+ } catch (err) {
+ if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ emitPreflightFailureSpan(err);
+ log.warn(
+ {
+ event: 'git_preflight_fail',
+ platform: err.platform,
+ reason: err instanceof GitTooOldError ? 'too_old' : 'not_available',
+ detectedVersion: err instanceof GitTooOldError ? err.detected : '',
+ },
+ err instanceof GitTooOldError ? 'git binary too old' : 'git binary not found',
+ );
+ } else {
+ log.error(
+ {
+ event: 'clone_preflight_unexpected_error',
+ err,
+ },
+ 'unexpected error during clone preflight',
+ );
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ const done = Promise.resolve().then(() => {
+ opts.onEvent({ type: 'error', message });
+ });
+ return { done, cancel: () => {} };
+ }
+
+ const extraPathDirs = isAbsolute(detected.resolvedPath) ? [dirname(detected.resolvedPath)] : [];
+
let sawTerminal = false;
const branchArgs =
@@ -71,6 +115,7 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {
const proc = runSubprocess({
cliArgs: opts.cliArgs,
trailingArgs: ['clone', '--json', ...branchArgs, opts.url, targetDir],
+ extraPathDirs,
timeoutMs,
onLine: ({ parsed }) => {
if (!parsed) return;
diff --git a/packages/server/src/local-ops/subprocess.test.ts b/packages/server/src/local-ops/subprocess.test.ts
index ff6e49ca3..97aa59715 100644
--- a/packages/server/src/local-ops/subprocess.test.ts
+++ b/packages/server/src/local-ops/subprocess.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, test } from 'bun:test';
+import { delimiter as PATH_DELIMITER } from 'node:path';
import { runSubprocess } from './subprocess.ts';
const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];
@@ -146,4 +147,49 @@ describe('runSubprocess', () => {
await proc.done;
expect(lines.map((l) => l.raw)).toEqual(['keep']);
});
+
+ const echoPathCli = fixtureCli(`console.log(JSON.stringify({ path: process.env.PATH }))`);
+ const childPathFrom = (lines: { parsed: Record<string, unknown> | null }[]): string =>
+ String(lines[0]?.parsed?.path ?? '');
+
+ test('extraPathDirs prepends to the child PATH in order, ahead of the inherited PATH', async () => {
+ const lines: { parsed: Record<string, unknown> | null }[] = [];
+ const proc = runSubprocess({
+ cliArgs: echoPathCli,
+ trailingArgs: [],
+ extraPathDirs: ['/opt/one', '/opt/two'],
+ timeoutMs: 5000,
+ onLine: (line) => lines.push(line),
+ });
+ await proc.done;
+ const childPath = childPathFrom(lines);
+ expect(childPath.startsWith(`/opt/one${PATH_DELIMITER}/opt/two${PATH_DELIMITER}`)).toBe(true);
+ expect(childPath.endsWith(process.env.PATH ?? '')).toBe(true);
+ });
+
+ test('absent extraPathDirs leaves the child PATH untouched', async () => {
+ const lines: { parsed: Record<string, unknown> | null }[] = [];
+ const proc = runSubprocess({
+ cliArgs: echoPathCli,
+ trailingArgs: [],
+ timeoutMs: 5000,
+ onLine: (line) => lines.push(line),
+ });
+ await proc.done;
+ expect(childPathFrom(lines)).toBe(process.env.PATH ?? '');
+ });
+
+ test('extraPathDirs drops empty segments when composing the child PATH', async () => {
+ const lines: { parsed: Record<string, unknown> | null }[] = [];
+ const proc = runSubprocess({
+ cliArgs: echoPathCli,
+ trailingArgs: [],
+ extraPathDirs: ['', '/opt/only'],
+ timeoutMs: 5000,
+ onLine: (line) => lines.push(line),
+ });
+ await proc.done;
+ const childPath = childPathFrom(lines);
+ expect(childPath.split(PATH_DELIMITER)[0]).toBe('/opt/only');
+ });
});
diff --git a/packages/server/src/local-ops/subprocess.ts b/packages/server/src/local-ops/subprocess.ts
index 63e075ada..186937613 100644
--- a/packages/server/src/local-ops/subprocess.ts
+++ b/packages/server/src/local-ops/subprocess.ts
@@ -1,4 +1,5 @@
import { spawn } from 'node:child_process';
+import { delimiter as PATH_DELIMITER } from 'node:path';
interface ParsedLine {
raw: string;
@@ -9,6 +10,7 @@ interface SubprocessRunOptions {
cliArgs: readonly string[];
trailingArgs: readonly string[];
cwd?: string;
+ extraPathDirs?: readonly string[];
timeoutMs: number;
onLine: (line: ParsedLine) => void;
onStderr?: (chunk: Buffer) => void;
@@ -46,10 +48,17 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessController
let stdoutBuffer = '';
const stderrChunks: Buffer[] = [];
+ const childEnv: NodeJS.ProcessEnv = { ...process.env };
+ if (opts.extraPathDirs && opts.extraPathDirs.length > 0) {
+ childEnv.PATH = [...opts.extraPathDirs, process.env.PATH ?? '']
+ .filter(Boolean)
+ .join(PATH_DELIMITER);
+ }
+
const child = spawn(cmd, argv, {
cwd: opts.cwd,
stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env },
+ env: childEnv,
});
const killTimer = setTimeout(() => {
diff --git a/packages/server/src/project-git.preflight.test.ts b/packages/server/src/project-git.preflight.test.ts
new file mode 100644
index 000000000..e0a41a3fc
--- /dev/null
+++ b/packages/server/src/project-git.preflight.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, test } from 'bun:test';
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ __resetResolveOnPathCacheForTests,
+ __seedResolveOnPathCacheForTests,
+ GitTooOldError,
+} from './git-preflight.ts';
+import {
+ isRecoverableGitSignal,
+ withBrokenBareGitOnly,
+ withUnusableGitEverywhere,
+} from './git-unusable-setup.test-helper.ts';
+import { ensureProjectGit, ProjectGitInitError } from './project-git.ts';
+
+type SetupOutcome =
+ | 'succeeded'
+ | 'recoverable-git-not-available'
+ | 'raw-ProjectGitInitError'
+ | `other:${string}`;
+
+async function runEnsureProjectGit(projectRoot: string): Promise<SetupOutcome> {
+ try {
+ await ensureProjectGit(projectRoot);
+ return 'succeeded';
+ } catch (err) {
+ if (isRecoverableGitSignal(err)) return 'recoverable-git-not-available';
+ if (err instanceof ProjectGitInitError) return 'raw-ProjectGitInitError';
+ return `other:${err instanceof Error ? err.name : String(err)}`;
+ }
+}
+
+function freshProjectDir(): string {
+ return mkdtempSync(join(tmpdir(), 'ok356-project-'));
+}
+
+describe('ensureProjectGit — git-preflight at the project-setup boundary (#356)', () => {
+ test('surfaces the recoverable GitNotAvailableError (not raw ProjectGitInitError) when git is unusable', async () => {
+ const project = freshProjectDir();
+ let outcome = 'unset';
+ try {
+ await withUnusableGitEverywhere(async () => {
+ outcome = await runEnsureProjectGit(project);
+ });
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ }
+
+ expect(outcome).toBe('recoverable-git-not-available');
+ });
+
+ test('does not fail with a raw ProjectGitInitError under the check/use binding divergence', async () => {
+ const project = freshProjectDir();
+ let outcome = 'unset';
+ try {
+ await withBrokenBareGitOnly(async () => {
+ outcome = await runEnsureProjectGit(project);
+ });
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ }
+
+ expect(['succeeded', 'recoverable-git-not-available']).toContain(outcome);
+ });
+
+ test('surfaces the recoverable GitTooOldError (not raw ProjectGitInitError) when git is below MIN_GIT_VERSION', async () => {
+ const project = freshProjectDir();
+ const fakeBin = mkdtempSync(join(tmpdir(), 'ok356-oldgit-'));
+ const fakeGit = join(fakeBin, 'git');
+ writeFileSync(
+ fakeGit,
+ '#!/bin/sh\ncase "$1" in\n --version) echo "git version 2.10.0"; exit 0 ;;\n *) exit 0 ;;\nesac\n',
+ 'utf-8',
+ );
+ chmodSync(fakeGit, 0o755);
+
+ __resetResolveOnPathCacheForTests();
+ __seedResolveOnPathCacheForTests('git', fakeGit);
+ const originalPath = process.env.PATH;
+ process.env.PATH = `${fakeBin}:${originalPath ?? ''}`;
+ let caught: unknown;
+ try {
+ await ensureProjectGit(project);
+ } catch (err) {
+ caught = err;
+ } finally {
+ process.env.PATH = originalPath;
+ __resetResolveOnPathCacheForTests();
+ rmSync(fakeBin, { recursive: true, force: true });
+ rmSync(project, { recursive: true, force: true });
+ }
+
+ expect(caught).toBeInstanceOf(GitTooOldError);
+ expect(isRecoverableGitSignal(caught)).toBe(true);
+ expect(caught).not.toBeInstanceOf(ProjectGitInitError);
+ });
+});
diff --git a/packages/server/src/project-git.test.ts b/packages/server/src/project-git.test.ts
index 9711406ff..ee7922860 100644
--- a/packages/server/src/project-git.test.ts
+++ b/packages/server/src/project-git.test.ts
@@ -5,6 +5,10 @@ import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
+import {
+ __resetResolveOnPathCacheForTests,
+ __seedResolveOnPathCacheForTests,
+} from './git-preflight.ts';
import { ensureProjectGit, ProjectGitInitError } from './project-git.ts';
const execFileAsync = promisify(execFile);
@@ -101,19 +105,20 @@ describe('ensureProjectGit', () => {
expect(head).toBe('ref: refs/heads/main\n');
});
- test('throws ProjectGitInitError when the git binary is missing', async () => {
+ test('falls back to a usable git when bare git is unavailable on PATH', async () => {
const projectRoot = resolve(tmpDir, 'no-git-binary');
mkdirSync(projectRoot, { recursive: true });
const originalPath = process.env.PATH;
process.env.PATH = '/nonexistent-path';
try {
- await expect(ensureProjectGit(projectRoot)).rejects.toBeInstanceOf(ProjectGitInitError);
+ const result = await ensureProjectGit(projectRoot);
+ expect(result.didInit).toBe(true);
} finally {
process.env.PATH = originalPath;
}
- expect(existsSync(resolve(projectRoot, '.git'))).toBe(false);
+ expect(existsSync(resolve(projectRoot, '.git/HEAD'))).toBe(true);
});
test('throws ProjectGitInitError when git init succeeds but .git/HEAD is absent (partial init)', async () => {
@@ -125,17 +130,20 @@ describe('ensureProjectGit', () => {
const fakeGit = resolve(fakeBin, 'git');
writeFileSync(
fakeGit,
- `#!/bin/sh\n# args: init --initial-branch=main <path>\ntarget="$3"\nmkdir -p "$target/.git"\n# intentionally do not create HEAD\nexit 0\n`,
+ `#!/bin/sh\ncase "$1" in\n --version) echo "git version 2.45.0"; exit 0 ;;\n init)\n # args: init --initial-branch=main <path>\n mkdir -p "$3/.git"\n # intentionally do not create HEAD\n exit 0 ;;\n *) exit 0 ;;\nesac\n`,
'utf-8',
);
await execFileAsync('chmod', ['+x', fakeGit]);
+ __resetResolveOnPathCacheForTests();
+ __seedResolveOnPathCacheForTests('git', fakeGit);
const originalPath = process.env.PATH;
process.env.PATH = `${fakeBin}:${originalPath ?? ''}`;
try {
await expect(ensureProjectGit(projectRoot)).rejects.toBeInstanceOf(ProjectGitInitError);
} finally {
process.env.PATH = originalPath;
+ __resetResolveOnPathCacheForTests();
}
});
});
diff --git a/packages/server/src/project-git.ts b/packages/server/src/project-git.ts
index f84aa351f..21b5ea6e8 100644
--- a/packages/server/src/project-git.ts
+++ b/packages/server/src/project-git.ts
@@ -2,6 +2,13 @@ import { execFile } from 'node:child_process';
import { existsSync, statSync } from 'node:fs';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
+import {
+ assertGitAvailable,
+ type GitDetected,
+ GitNotAvailableError,
+ GitTooOldError,
+} from './git-preflight.ts';
+import { emitPreflightFailureSpan } from './git-preflight-telemetry.ts';
import { getLogger } from './logger.ts';
const execFileAsync = promisify(execFile);
@@ -21,9 +28,9 @@ export interface EnsureProjectGitResult {
repaired?: boolean;
}
-async function isInsideExistingWorkTree(cwd: string): Promise<boolean> {
+async function isInsideExistingWorkTree(gitBin: string, cwd: string): Promise<boolean> {
try {
- const { stdout } = await execFileAsync('git', ['rev-parse', '--is-inside-work-tree'], {
+ const { stdout } = await execFileAsync(gitBin, ['rev-parse', '--is-inside-work-tree'], {
cwd,
});
return stdout.trim() === 'true';
@@ -47,13 +54,43 @@ export async function ensureProjectGit(projectRoot: string): Promise<EnsureProje
}
log.info({}, 'detected partial .git/ — running git init to repair');
needsRepair = true;
- } else if (await isInsideExistingWorkTree(abs)) {
+ }
+
+ let detected: GitDetected;
+ try {
+ detected = assertGitAvailable();
+ } catch (err) {
+ if (err instanceof GitNotAvailableError || err instanceof GitTooOldError) {
+ emitPreflightFailureSpan(err);
+ log.warn(
+ {
+ event: 'git_preflight_fail',
+ platform: err.platform,
+ reason: err instanceof GitTooOldError ? 'too_old' : 'not_available',
+ detectedVersion: err instanceof GitTooOldError ? err.detected : '',
+ },
+ err instanceof GitTooOldError ? 'git binary too old' : 'git binary not found',
+ );
+ } else {
+ log.warn(
+ {
+ event: 'git_preflight_unexpected_error',
+ message: err instanceof Error ? err.message : String(err),
+ },
+ 'unexpected error during git preflight',
+ );
+ }
+ throw err;
+ }
+ const gitBin = detected.resolvedPath;
+
+ if (!needsRepair && (await isInsideExistingWorkTree(gitBin, abs))) {
return { didInit: false };
}
let stderr = '';
try {
- const result = await execFileAsync('git', ['init', '--initial-branch=main', abs]);
+ const result = await execFileAsync(gitBin, ['init', '--initial-branch=main', abs]);
stderr = result.stderr ?? '';
} catch (err) {
const capturedStderr =