Merge #779 fix(macos): never run Apple's placeholder git, which opens the developer tools window

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-11-08 04:05:49 +01:00
commit e6c79c8e8c
10 files changed
+371 -1

No files matched your search

+20 -1
View File
@@ -54,6 +54,7 @@ import { lstat, readdir, rename, rm } from 'node:fs/promises';
import { basename, dirname, join } from 'node:path';
import { EXEC_TIMEOUT_MS } from './config/exec-timeout.js';
import { probePathKind } from './utils/bounded-path-probe.js';
import { gitMissingError, gitSpawnAllowed } from './utils/git-availability.js';
// ─── Tunables ────────────────────────────────────────────────────────────────
@@ -728,6 +729,17 @@ interface GitRun {
* signal is used rather than `child.kill()`.
*/
async function runGit(args: string[], timeoutMs: number, maxStdoutBytes: number): Promise<GitRun> {
// Never Apple's placeholder git on a Mac without developer tools: answered as a missing git.
if (!gitSpawnAllowed()) {
return {
stdout: '',
stderr: '',
code: null,
timedOut: false,
started: false,
spawnError: String(gitMissingError()),
};
}
// The queue wait spends the SAME deadline as the operation: `timeoutMs` is a
// promise about the whole call, not about git's runtime after some unbounded
// wait. A full queue is refused outright rather than queued.
@@ -814,10 +826,17 @@ async function runGit(args: string[], timeoutMs: number, maxStdoutBytes: number)
}
}
/** Is a usable `git` on this machine? Memoized: the answer cannot change without a restart. */
/**
* Is a usable `git` on this machine? Memoized: the answer cannot change without a restart. The one
* exception is a Mac whose only git is Apple's placeholder with no developer tools behind it: running
* that, even as `git --version`, opens macOS's "install the developer tools" window, so it is never
* run, and that refusal is not memoized here (the gate keeps its own short memory), so the page finds
* git once the tools are installed.
*/
let gitAvailable: boolean | null = null;
export function isGitAvailable(): boolean {
if (gitAvailable !== null) return gitAvailable;
if (!gitSpawnAllowed()) return false;
try {
execFileSync('git', ['--version'], {
encoding: 'utf-8',
+4
View File
@@ -65,6 +65,7 @@ import {
resolveWorkspaceRepos,
type GitRunner,
} from './git-workspace-status.js';
import { gitMissingError, gitSpawnAllowed } from './utils/git-availability.js';
const execFileAsync = promisify(execFile);
@@ -205,6 +206,7 @@ export function fetchEnvFor(base: NodeJS.ProcessEnv, repoSshCommand: string | nu
* add a fifth git process or push a fetch past the user's timeout: it spends part of it.
*/
export async function readRepoSshCommand(cwd: string, timeoutMs: number): Promise<string | null> {
if (!gitSpawnAllowed()) return null;
try {
const { stdout } = await execFileAsync('git', ['config', '--get', 'core.sshCommand'], {
cwd,
@@ -240,6 +242,8 @@ export async function readRepoSshCommand(cwd: string, timeoutMs: number): Promis
* as a timeout without starting the fetch.
*/
export const runFetch: GitRunner = async (cwd, args, opts) => {
// Never Apple's placeholder git on a Mac without developer tools: answered as GIT_MISSING.
if (!gitSpawnAllowed()) throw gitMissingError();
const timeoutMs = opts?.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS;
const startedAt = Date.now();
const env = fetchEnvFor(process.env, await readRepoSshCommand(cwd, timeoutMs));
+3
View File
@@ -50,6 +50,7 @@ import { homedir } from 'node:os';
import { basename, join, relative, sep } from 'node:path';
import { promisify } from 'node:util';
import { gitNonInteractiveEnv, redactGitCredentials } from './git-clone.js';
import { gitMissingError, gitSpawnAllowed } from './utils/git-availability.js';
const execFileAsync = promisify(execFile);
@@ -265,6 +266,8 @@ export function parseCommitLog(text: string): GitCommitEntry[] {
export type GitRunner = (cwd: string, args: string[], opts?: { timeoutMs?: number }) => Promise<string>;
export const runGit: GitRunner = async (cwd, args, opts) => {
// Never Apple's placeholder git on a Mac without developer tools (utils/git-availability.ts).
if (!gitSpawnAllowed()) throw gitMissingError();
const { stdout } = await execFileAsync(
'git',
// --no-optional-locks: never touch the index just to look. core.fsmonitor=false: do not start or
+6
View File
@@ -62,6 +62,7 @@ import { homedir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { gitNonInteractiveEnv, isSafeGitRef, sanitizeGitOutput } from './git-clone.js';
import { isInsideAny, isUnrelatedAncestor } from './git-workspace-status.js';
import { gitMissingError, gitSpawnAllowed } from './utils/git-availability.js';
// ─── Limits ──────────────────────────────────────────────────────────────────
@@ -371,6 +372,11 @@ const READ_ONLY_GIT_OPTIONS = ['--no-optional-locks', '-c', 'core.fsmonitor=fals
*/
export const runWorktreeGit: WorktreeGitRunner = (cwd, args, opts) =>
new Promise<WorktreeGitResult>((resolveRun) => {
// Never Apple's placeholder git on a Mac without developer tools: answered as "git is not installed".
if (!gitSpawnAllowed()) {
resolveRun({ code: null, stdout: '', stderr: '', timedOut: false, spawnError: String(gitMissingError()) });
return;
}
let child: ReturnType<typeof spawn>;
try {
child = spawn('git', args, {
+3
View File
@@ -21,6 +21,7 @@ import { open, readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { promisify } from 'node:util';
import type { PredictionToolCall, WorkspaceSignals } from './readmymind-context.js';
import { gitMissingError, gitSpawnAllowed } from './utils/git-availability.js';
const execFileAsync = promisify(execFile);
@@ -150,6 +151,8 @@ const MAX_STATUS_LINES = 30;
*/
export async function collectWorkspaceSignals(workingDir: string): Promise<WorkspaceSignals | null> {
const git = async (args: string[]): Promise<string> => {
// Never Apple's placeholder git on a Mac without developer tools (utils/git-availability.ts).
if (!gitSpawnAllowed()) throw gitMissingError();
const { stdout } = await execFileAsync('git', args, {
cwd: workingDir,
timeout: GIT_TIMEOUT_MS,
+147
View File
@@ -0,0 +1,147 @@
/**
* @fileoverview The ONE gate in front of every `git` the server starts.
*
* macOS ships `/usr/bin/git` as a placeholder. On a Mac without the developer tools (Xcode or the
* Command Line Tools), running it, even as `git --version`, makes macOS open its "install the command
* line developer tools" window and exit non-zero. The server used to ask "is git here?" that way on the
* first page load, so a user who had just installed Codeman without git and without an administrator
* password got that window one second after the install finished, and again at every login.
* `install.sh` never runs the placeholder for the same reason.
*
* So on macOS, when `git` on the server's PATH resolves to that placeholder, the developer tools are
* proven first: `xcode-select -p` (a real binary that prints and never opens a window) must name a
* folder that holds a git of its own. Otherwise git counts as absent and is never started.
*
* Every site that starts git calls `gitSpawnAllowed()` first and answers a refusal the way it already
* answers a machine with no git (`gitMissingError()` carries `code: 'ENOENT'` for that).
* `test/git-spawn-gate.test.ts` fails on a git spawn in a file that does not go through this gate.
*
* The decision is pure (`gitSpawnWouldPrompt`, `findOnPath`); the IO around it is two bounded steps, a
* PATH scan and one `xcode-select -p` (a few milliseconds, capped at 3 s), and only on macOS. A "yes" is
* kept for the life of the process; a "no" is asked again after `GIT_GATE_NEGATIVE_TTL_MS`, so
* installing the developer tools later needs no server restart for the git features (the page's own
* "git is available" flag stays memoized per process, like every other availability flag there).
*
* @module utils/git-availability
*/
import { execFileSync } from 'node:child_process';
import { realpathSync } from 'node:fs';
import { delimiter, isAbsolute, join } from 'node:path';
import { isExecutableRegularFile } from './cli-executable-resolver.js';
/** Apple's placeholder. A real git (Homebrew, MacPorts, Nix) sits elsewhere on the PATH. */
export const APPLE_GIT_PLACEHOLDER = '/usr/bin/git';
const XCODE_SELECT = '/usr/bin/xcode-select';
const XCODE_SELECT_TIMEOUT_MS = 3_000;
/** How long a refusal is kept before the machine is looked at again. */
export const GIT_GATE_NEGATIVE_TTL_MS = 60_000;
/**
* The first `name` on a PATH-style list that `isExecutable` accepts, or null. Pure.
* Empty and relative entries are skipped: they mean "the current directory" of whoever runs the
* command, which this lookup cannot know.
*/
export function findOnPath(
name: string,
pathEnv: string | undefined,
isExecutable: (path: string) => boolean
): string | null {
for (const dir of (pathEnv ?? '').split(delimiter)) {
if (!dir || !isAbsolute(dir)) continue;
const candidate = join(dir, name);
if (isExecutable(candidate)) return candidate;
}
return null;
}
export interface GitGateFacts {
platform: NodeJS.Platform;
/** What `git` resolves to on the server's PATH (symlinks followed), or null when there is none. */
gitPath: string | null;
/** Asked only when it decides the answer, so other machines never pay for it. */
developerToolsPresent: () => boolean;
}
/**
* Would starting `git` open macOS's "install the developer tools" window? Pure.
* Only Apple's placeholder does that, and only while no developer tools are installed. No git on the
* PATH at all is not this function's case: the spawn then fails with ENOENT, which every caller handles.
*/
export function gitSpawnWouldPrompt(facts: GitGateFacts): boolean {
if (facts.platform !== 'darwin') return false;
if (facts.gitPath !== APPLE_GIT_PLACEHOLDER) return false;
return !facts.developerToolsPresent();
}
/**
* The developer folder `xcode-select -p` names must hold a git of its own (`usr/bin/git`, true for both
* Xcode and the Command Line Tools). A selected folder that has since been deleted would otherwise read
* as "tools present" and the placeholder would open its window after all.
*/
export function developerDirHoldsGit(developerDir: string, isExecutable: (path: string) => boolean): boolean {
const dir = developerDir.trim();
if (!dir || !isAbsolute(dir)) return false;
return isExecutable(join(dir, 'usr', 'bin', 'git'));
}
function resolveGitOnPath(): string | null {
const found = findOnPath('git', process.env.PATH, isExecutableRegularFile);
if (!found) return null;
try {
return realpathSync(found);
} catch {
return found;
}
}
function developerToolsPresent(): boolean {
try {
const out = execFileSync(XCODE_SELECT, ['-p'], {
encoding: 'utf8',
timeout: XCODE_SELECT_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
});
return developerDirHoldsGit(out, isExecutableRegularFile);
} catch {
return false; // exit 2: no developer folder. Never the placeholder's window.
}
}
let allowed: boolean | null = null;
let refusedAt = 0;
/**
* May the server start `git` right now? False only on a Mac whose only git is Apple's placeholder with
* no developer tools behind it. Callers answer false as "git is not installed".
*/
export function gitSpawnAllowed(): boolean {
if (allowed === true) return true;
if (allowed === false && Date.now() - refusedAt < GIT_GATE_NEGATIVE_TTL_MS) return false;
const platform = process.platform;
allowed = !gitSpawnWouldPrompt({
platform,
gitPath: platform === 'darwin' ? resolveGitOnPath() : null,
developerToolsPresent,
});
if (!allowed) refusedAt = Date.now();
return allowed;
}
/** The error a refused spawn stands in for: what Node raises when there is no `git` to start. */
export function gitMissingError(): NodeJS.ErrnoException {
const err: NodeJS.ErrnoException = new Error('spawn git ENOENT');
err.code = 'ENOENT';
err.errno = -2;
err.syscall = 'spawn git';
err.path = 'git';
return err;
}
/** Test seam: forget the remembered answer. */
export function resetGitGateForTests(): void {
allowed = null;
refusedAt = 0;
}
+3
View File
@@ -41,6 +41,7 @@ import { createRequire } from 'node:module';
import { promisify } from 'node:util';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { gitNonInteractiveEnv, redactGitCredentials } from '../git-clone.js';
import { gitSpawnAllowed } from '../utils/git-availability.js';
import { getInstallInfo } from './self-update.js';
import type { RepoIncomingCommit, RepoRemoteRole, RepoRemoteStatus, RepositoryStatusResult } from '../types/update.js';
@@ -242,6 +243,8 @@ interface GitResult {
* spawn would block the event loop for the whole wait.
*/
async function runGit(args: string[], cwd: string, timeout = EXEC_TIMEOUT_MS): Promise<GitResult> {
// Never Apple's placeholder git on a Mac without developer tools (utils/git-availability.ts).
if (!gitSpawnAllowed()) return { ok: false, stdout: '', stderr: 'git is not installed' };
try {
const { stdout } = await execFileAsync('git', args, {
cwd,
+3
View File
@@ -41,6 +41,7 @@ import { createRequire } from 'node:module';
import { dataPath } from '../config/instance.js';
import { LAUNCHD_LABEL, SYSTEMD_UNIT } from '../config/service-names.js';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { gitSpawnAllowed } from '../utils/git-availability.js';
import type {
EnvironmentBlocker,
EnvironmentGate,
@@ -429,6 +430,8 @@ export function reconcileUpdateOnBoot(now = Date.now()): void {
/** Run a command, returning trimmed stdout, or null on any error. */
function tryExec(cmd: string, args: string[], cwd?: string, timeout = EXEC_TIMEOUT_MS): string | null {
// Never Apple's placeholder git on a Mac without developer tools (utils/git-availability.ts).
if (cmd === 'git' && !gitSpawnAllowed()) return null;
try {
return execFileSync(cmd, args, { cwd, encoding: 'utf-8', timeout, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
} catch {