Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): resolve git helper tools under minimal GUI PATH (#2685)
miles-kt-inkeep5c48336b2636
diff --git a/.changeset/git-helper-path-resolution.md b/.changeset/git-helper-path-resolution.mdnew file mode 100644index 000000000..2118da1b8--- /dev/null+++ b/.changeset/git-helper-path-resolution.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Opening a shared branch in a worktree (and other git operations) no longer fails with a generic error when the repository uses git-lfs installed via Homebrew. The desktop app and its server now append well-known tool directories (Homebrew, MacPorts, `~/.local/bin`, asdf/mise shims) to the PATH used for git commands, so helpers git spawns mid-operation — LFS filters, credential helpers, hooks — resolve even though macOS launches apps with a minimal PATH. When a required helper still can't be found, the error now names it ("Git needs git-lfs…") instead of a retry-blind generic message, and the underlying git error is recorded in the desktop log.diff --git a/packages/app/src/components/NewWorktreeDialog.tsx b/packages/app/src/components/NewWorktreeDialog.tsxindex 6eb70e547..a224e4028 100644--- a/packages/app/src/components/NewWorktreeDialog.tsx+++ b/packages/app/src/components/NewWorktreeDialog.tsx@@ -133,6 +133,8 @@ function createErrorCopy(reason: string): MessageDescriptor {return msg`Enter a valid branch name (no spaces, no leading dot, no "..").`;case 'no-git':return msg`This project isn't a git repository, so worktrees aren't available.`;+ case 'helper-not-found':+ return msg`Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again.`;default:return msg`Couldn't create the worktree. Try a different name.`;}diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsxindex b92c9050d..c90536d87 100644--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx@@ -434,8 +434,20 @@ export function ShareBranchSwitchDialog({// error vocabulary (NewWorktreeDialog's inline copy), adapted where that copy// assumes a typed-name form field. Exhaustive so a new create-failure reason// is a compile error here instead of a silent generic toast.- function showWorktreeFailureToast(reason: WorktreeCheckoutSideEffectReason): void {+ function showWorktreeFailureToast(+ reason: WorktreeCheckoutSideEffectReason,+ helper?: string,+ ): void {switch (reason) {+ case 'helper-not-found': {+ // `helper` accompanies this reason from the classifier; the fallback+ // keeps the copy coherent if a future producer omits it.+ const tool = helper ?? t`a required git tool`;+ toast.error(+ t`Git needs ${tool} for this repository, but it isn't installed or couldn't be found. Install it, then try again.`,+ );+ return;+ }case 'branch-not-found':toast.error(t`Branch ${shareBranch} no longer exists on the remote.`);return;@@ -476,12 +488,14 @@ export function ShareBranchSwitchDialog({// because neither branch's capture variable gets set.function applyWorktreeOutcome(result: WorktreeCreateResult | null): void {let failureReason: WorktreeCheckoutSideEffectReason | null = null;+ let failureHelper: string | undefined;let shouldDismiss = false;let openPath: string | null = null;setBranchSwitchState((prev) => {const { state: next, sideEffect } = applyWorktreeCheckoutOutcome(prev, result);if (sideEffect) {failureReason = sideEffect.reason;+ failureHelper = sideEffect.helper;shouldDismiss = next.phase === 'dismissed';}if (next.phase === 'opening-worktree') {@@ -496,7 +510,7 @@ export function ShareBranchSwitchDialog({branch: shareBranch,}),);- showWorktreeFailureToast(failureReason);+ showWorktreeFailureToast(failureReason, failureHelper);}if (openPath !== null) {// The anchor window's cached worktree model is stale now (a worktree wasdiff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.tsindex c83266c36..e734964b4 100644--- a/packages/app/src/lib/share/branch-switch-flow.test.ts+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts@@ -697,6 +697,21 @@ describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {}});+ test('helper-not-found stays open and threads the missing command to the toast signal', () => {+ const result = applyWorktreeCheckoutOutcome(creating, {+ ok: false,+ reason: 'helper-not-found',+ helper: 'git-lfs',+ message: 'git-lfs filter-process: git-lfs: command not found',+ });+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });+ expect(result.sideEffect).toEqual({+ kind: 'toast',+ reason: 'helper-not-found',+ helper: 'git-lfs',+ });+ });+test('null (IPC rejection) stays open with the proxy-null toast signal', () => {const result = applyWorktreeCheckoutOutcome(creating, null);expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.tsindex ff936f49f..887c72e94 100644--- a/packages/app/src/lib/share/branch-switch-flow.ts+++ b/packages/app/src/lib/share/branch-switch-flow.ts@@ -576,6 +576,9 @@ export interface ApplyWorktreeCheckoutOutcomeResult {readonly sideEffect?: {readonly kind: 'toast';readonly reason: WorktreeCheckoutSideEffectReason;+ /** Set iff `reason === 'helper-not-found'` — the missing command git+ * reported (e.g. `git-lfs`), interpolated into the toast copy. */+ readonly helper?: string;};}@@ -620,6 +623,6 @@ export function applyWorktreeCheckoutOutcome(}return {state: { phase: 'ready', info: state.info },- sideEffect: { kind: 'toast', reason: result.reason },+ sideEffect: { kind: 'toast', reason: result.reason, helper: result.helper },};}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 6b46af90f..c0c220432 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -826,6 +826,9 @@"Hp1l6f": ["Current"],"HpK_8d": ["Reload"],"HptUxX": ["Number"],+ "HqOPpj": [+ "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."+ ],"HqiZvw": ["OpenKnowledge stores its configuration and internal files inside a newly created <0>.ok</0> directory in your project root folder."],@@ -1542,6 +1545,11 @@"Z6rrjc": ["No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."],+ "Z7x_Zh": [+ "Git needs ",+ ["tool"],+ " for this repository, but it isn't installed or couldn't be found. Install it, then try again."+ ],"Z8KDox": ["Enter a folder name (e.g. brain)."],"Z8lGw6": ["Share"],"ZARuZJ": ["Couldn't load files"],@@ -1703,6 +1711,7 @@"cGV6Mh": ["Show a preview card when you hover an external link in the editor. This setting applies only to this computer."],+ "cHhH3i": ["a required git tool"],"cIptmH": ["In the Claude Desktop App"],"cKjLuT": ["(project + user)"],"cN1Gcp": ["A worktree folder for ", ["shareBranch"], " already exists."],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex a765f733c..02fd75ee6 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -667,6 +667,10 @@ msgstr "A real shell is off for this project. Turning it on runs commands with tmsgid "A report helps us find the cause. Nothing is sent until you review it."msgstr "A report helps us find the cause. Nothing is sent until you review it."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "a required git tool"+msgstr "a required git tool"+#: src/components/NewTemplateDialog.tsxmsgid "A reusable starting point for new documents in this folder."msgstr "A reusable starting point for new documents in this folder."@@ -3706,6 +3710,14 @@ msgstr "Git auto-sync"msgid "Git identity isn't set — commits use a default author. Set yours so teammates see your name."msgstr "Git identity isn't set — commits use a default author. Set yours so teammates see your name."+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Git needs {tool} for this repository, but it isn't installed or couldn't be found. Install it, then try again."+msgstr "Git needs {tool} for this repository, but it isn't installed or couldn't be found. Install it, then try again."++#: src/components/NewWorktreeDialog.tsx+msgid "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."+msgstr "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr "GitHub authentication failed. Try signing in again."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 772a3a84f..886b65e92 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -826,6 +826,9 @@"Hp1l6f": ["Ćũŕŕēńţ"],"HpK_8d": ["Ŕēĺōàď"],"HptUxX": ["Ńũḿƀēŕ"],+ "HqOPpj": [+ "Ĝĩţ ńēēďś à ĥēĺƥēŕ ţōōĺ (śũćĥ àś ĝĩţ-ĺƒś) ţĥàţ ĩśń'ţ ĩńśţàĺĺēď ōŕ ćōũĺďń'ţ ƀē ƒōũńď. Ĩńśţàĺĺ ĩţ, ţĥēń ţŕŷ àĝàĩń."+ ],"HqiZvw": ["ŌƥēńĶńōŵĺēďĝē śţōŕēś ĩţś ćōńƒĩĝũŕàţĩōń àńď ĩńţēŕńàĺ ƒĩĺēś ĩńśĩďē à ńēŵĺŷ ćŕēàţēď <0>.ōķ</0> ďĩŕēćţōŕŷ ĩń ŷōũŕ ƥŕōĴēćţ ŕōōţ ƒōĺďēŕ."],@@ -1542,6 +1545,11 @@"Z6rrjc": ["Ńō <0>.ḿàŕķďōŵńĺĩńţ.*</0> ƒĩĺē ŷēţ — ēvēŕŷ ŕũĺē ŕũńś ōń ţĥē śàḿē ďēƒàũĺţś àś ţĥē VŚ Ćōďē ḿàŕķďōŵńĺĩńţ ēxţēńśĩōń: àĺĺ ōń, ēxćēƥţ ĺĩńē ĺēńĝţĥ."],+ "Z7x_Zh": [+ "Ĝĩţ ńēēďś ",+ ["tool"],+ " ƒōŕ ţĥĩś ŕēƥōśĩţōŕŷ, ƀũţ ĩţ ĩśń'ţ ĩńśţàĺĺēď ōŕ ćōũĺďń'ţ ƀē ƒōũńď. Ĩńśţàĺĺ ĩţ, ţĥēń ţŕŷ àĝàĩń."+ ],"Z8KDox": ["Ēńţēŕ à ƒōĺďēŕ ńàḿē (ē.ĝ. ƀŕàĩń)."],"Z8lGw6": ["Śĥàŕē"],"ZARuZJ": ["Ćōũĺďń'ţ ĺōàď ƒĩĺēś"],@@ -1703,6 +1711,7 @@"cGV6Mh": ["Śĥōŵ à ƥŕēvĩēŵ ćàŕď ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ ĩń ţĥē ēďĩţōŕ. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."],+ "cHhH3i": ["à ŕēǫũĩŕēď ĝĩţ ţōōĺ"],"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],"cN1Gcp": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ", ["shareBranch"], " àĺŕēàďŷ ēxĩśţś."],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 8ace8ef82..6c9d9394d 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -662,6 +662,10 @@ msgstr ""msgid "A report helps us find the cause. Nothing is sent until you review it."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "a required git tool"+msgstr ""+#: src/components/NewTemplateDialog.tsxmsgid "A reusable starting point for new documents in this folder."msgstr ""@@ -3701,6 +3705,14 @@ msgstr ""msgid "Git identity isn't set — commits use a default author. Set yours so teammates see your name."msgstr ""+#: src/components/ShareBranchSwitchDialog.tsx+msgid "Git needs {tool} for this repository, but it isn't installed or couldn't be found. Install it, then try again."+msgstr ""++#: src/components/NewWorktreeDialog.tsx+msgid "Git needs a helper tool (such as git-lfs) that isn't installed or couldn't be found. Install it, then try again."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "GitHub authentication failed. Try signing in again."msgstr ""diff --git a/packages/core/src/git/git-spawn-path.test.ts b/packages/core/src/git/git-spawn-path.test.tsnew file mode 100644index 000000000..eec87eca8--- /dev/null+++ b/packages/core/src/git/git-spawn-path.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from 'bun:test';+import { augmentGitSpawnPath, wellKnownToolDirs } from './git-spawn-path.ts';++const HOME = '/Users/tester';++function darwinOpts(existing: readonly string[]) {+ const set = new Set(existing);+ return {+ platform: 'darwin' as const,+ homeDir: HOME,+ isDir: (dir: string) => set.has(dir),+ delimiter: ':',+ };+}++describe('augmentGitSpawnPath', () => {+ test('appends existing well-known dirs to a minimal launchd PATH', () => {+ const out = augmentGitSpawnPath(+ '/usr/bin:/bin:/usr/sbin:/sbin',+ darwinOpts(['/opt/homebrew/bin']),+ );+ expect(out).toBe('/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin');+ });++ test('never prepends — existing entries keep resolution priority', () => {+ const out = augmentGitSpawnPath('/usr/bin', darwinOpts(['/opt/homebrew/bin']));+ expect(out.startsWith('/usr/bin')).toBe(true);+ });++ test('skips directories that do not exist on disk', () => {+ const out = augmentGitSpawnPath('/usr/bin', darwinOpts([]));+ expect(out).toBe('/usr/bin');+ });++ test('does not duplicate a well-known dir already on PATH', () => {+ const out = augmentGitSpawnPath(+ '/opt/homebrew/bin:/usr/bin',+ darwinOpts(['/opt/homebrew/bin']),+ );+ expect(out).toBe('/opt/homebrew/bin:/usr/bin');+ });++ test('is idempotent', () => {+ const opts = darwinOpts(['/opt/homebrew/bin', '/usr/local/bin']);+ const once = augmentGitSpawnPath('/usr/bin', opts);+ expect(augmentGitSpawnPath(once, opts)).toBe(once);+ });++ test('yields the well-known dirs alone when PATH is undefined or empty', () => {+ expect(augmentGitSpawnPath(undefined, darwinOpts(['/usr/local/bin']))).toBe('/usr/local/bin');+ expect(augmentGitSpawnPath('', darwinOpts(['/usr/local/bin']))).toBe('/usr/local/bin');+ });++ test('adds nothing on win32 (Git for Windows manages its own PATH)', () => {+ const out = augmentGitSpawnPath('C:\\Windows', {+ platform: 'win32',+ homeDir: 'C:\\Users\\tester',+ isDir: () => true,+ delimiter: ';',+ });+ expect(out).toBe('C:\\Windows');+ });++ test('darwin dir list covers both Homebrew prefixes and shim dirs', () => {+ const dirs = wellKnownToolDirs('darwin', HOME);+ expect(dirs).toContain('/opt/homebrew/bin');+ expect(dirs).toContain('/usr/local/bin');+ expect(dirs).toContain(`${HOME}/.asdf/shims`);+ });++ // The CLI is cross-platform and Linux-tested — a regression in the default+ // (Linux) list would leave git helpers unresolvable on Linux hosts with no+ // other signal.+ test('linux (default) dir list covers linuxbrew and shim dirs but not macOS prefixes', () => {+ const dirs = wellKnownToolDirs('linux', HOME);+ expect(dirs).toContain('/usr/local/bin');+ expect(dirs).toContain('/home/linuxbrew/.linuxbrew/bin');+ expect(dirs).toContain(`${HOME}/.asdf/shims`);+ expect(dirs).toContain(`${HOME}/.local/share/mise/shims`);+ expect(dirs).not.toContain('/opt/homebrew/bin');+ expect(dirs).not.toContain('/opt/local/bin');+ });+});diff --git a/packages/core/src/git/git-spawn-path.ts b/packages/core/src/git/git-spawn-path.tsnew file mode 100644index 000000000..d72c72992--- /dev/null+++ b/packages/core/src/git/git-spawn-path.ts@@ -0,0 +1,97 @@+/**+ * PATH augmentation for git spawns from GUI-launched processes.+ *+ * macOS GUI apps (and their descendants — including the detached OK server)+ * inherit launchd's minimal `PATH=/usr/bin:/bin:/usr/sbin:/sbin`, not the+ * login shell's. git itself survives that (Apple ships /usr/bin/git, and+ * git-preflight probes fallback locations for the binary), but git spawns+ * PATH-resolved *helper* subprocesses mid-operation — `filter.lfs.process`+ * (git-lfs), credential helpers, `core.sshCommand`, `core.fsmonitor`, hook+ * interpreters — and those are typically package-manager installs that only a+ * shell profile puts on PATH. A missing helper aborts the whole operation+ * (`filter.lfs.required=true` makes checkout fatal), so every git spawn env+ * must carry an augmented PATH, not just a resolved git binary.+ *+ * Static augmentation (append well-known tool directories) is deliberate over+ * login-shell env resolution: it is deterministic, costs nothing at startup,+ * has no interaction with user shell configs (timeouts, non-POSIX shells,+ * stdout pollution), and behaves identically in dev and packaged builds. The+ * trade-off — installs outside these directories stay unreachable — is+ * covered by `detectMissingGitHelper`, which turns the residual failure into+ * an actionable message instead of a generic error.+ *+ * Appending (never prepending) keeps the user's existing PATH order+ * authoritative: an entry already on PATH always wins over the same name in a+ * well-known directory, so augmentation can only ADD resolution, never change+ * which binary an existing lookup finds.+ */++/** Injectable seams so the pure augmentation logic is testable per-platform.+ * All host facts are caller-supplied — this module is bundled into the+ * browser app via the core barrel, so it MUST NOT import `node:path` /+ * `node:os` / `node:fs` (Vite externalizes them and the property access+ * throws at client startup, blanking the app). */+export interface GitSpawnPathOptions {+ readonly platform: NodeJS.Platform;+ /** User home directory (`os.homedir()`). */+ readonly homeDir: string;+ /** Existence probe for a candidate directory (`fs.existsSync` in prod). */+ readonly isDir: (dir: string) => boolean;+ /** PATH separator — pass the host's `path.delimiter`. */+ readonly delimiter: string;+}++/**+ * Well-known tool directories per platform, ordered by install-base size.+ * Homebrew (both prefixes) dominates macOS; MacPorts and `~/.local/bin` cover+ * the common remainder; asdf/mise shim directories cover version-managed+ * installs whose real binaries live behind versioned paths no static list can+ * express. Windows returns empty — Git for Windows bundles git-lfs and its+ * installer manages PATH, so augmentation has nothing safe to add.+ */+export function wellKnownToolDirs(platform: NodeJS.Platform, homeDir: string): readonly string[] {+ // '/'-joined literals, not `path.join` — browser-safe (see the interface+ // note), and correct for every platform that reaches them: the win32 arm+ // (the only backslash platform) never builds a home-relative path.+ switch (platform) {+ case 'darwin':+ return [+ '/opt/homebrew/bin', // Apple Silicon brew+ '/usr/local/bin', // Intel brew + manual installs+ '/opt/local/bin', // MacPorts+ `${homeDir}/.local/bin`,+ `${homeDir}/.asdf/shims`,+ `${homeDir}/.local/share/mise/shims`,+ ];+ case 'win32':+ return [];+ default:+ return [+ '/usr/local/bin',+ '/home/linuxbrew/.linuxbrew/bin', // Homebrew on Linux+ `${homeDir}/.local/bin`,+ `${homeDir}/.asdf/shims`,+ `${homeDir}/.local/share/mise/shims`,+ ];+ }+}++/**+ * Return `currentPath` with well-known tool directories APPENDED: only+ * directories that exist on disk and aren't already present (exact string+ * match against current entries). `undefined`/empty input yields just the+ * existing well-known dirs, so a spawn env never ends up with an empty PATH.+ * Idempotent — augmenting an already-augmented PATH is a no-op.+ */+export function augmentGitSpawnPath(+ currentPath: string | undefined,+ options: GitSpawnPathOptions,+): string {+ const delim = options.delimiter;+ const existing = (currentPath ?? '').split(delim).filter((entry) => entry.length > 0);+ const present = new Set(existing);+ const additions = wellKnownToolDirs(options.platform, options.homeDir).filter(+ (dir) => !present.has(dir) && options.isDir(dir),+ );+ return [...existing, ...additions].join(delim);+}diff --git a/packages/core/src/git/missing-git-helper.test.ts b/packages/core/src/git/missing-git-helper.test.tsnew file mode 100644index 000000000..6cf83431c--- /dev/null+++ b/packages/core/src/git/missing-git-helper.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'bun:test';+import { detectMissingGitHelper } from './missing-git-helper.ts';++describe('detectMissingGitHelper', () => {+ // The incident stderr, verbatim: packaged desktop spawned git with launchd's+ // minimal PATH, git-lfs (Homebrew-installed) unresolvable at checkout.+ test('extracts git-lfs from the lfs filter-process failure', () => {+ const stderr =+ 'git-lfs filter-process: git-lfs: command not found\nfatal: the remote end hung up unexpectedly';+ expect(detectMissingGitHelper(stderr)).toBe('git-lfs');+ });++ test('extracts the command from bash 127 phrasing', () => {+ expect(detectMissingGitHelper('sh: gpg: command not found')).toBe('gpg');+ });++ test('extracts the command from dash 127 phrasing (Linux /bin/sh)', () => {+ expect(detectMissingGitHelper('sh: 1: git-lfs: not found')).toBe('git-lfs');+ });++ test("extracts the command from git's start_command failure", () => {+ expect(detectMissingGitHelper('error: cannot run gpg: No such file or directory')).toBe('gpg');+ expect(detectMissingGitHelper('fatal: cannot run ssh: No such file or directory')).toBe('ssh');+ });++ test('extracts the hook path from a cannot-exec failure', () => {+ expect(+ detectMissingGitHelper(+ "fatal: cannot exec '.husky/post-checkout': No such file or directory",+ ),+ ).toBe('.husky/post-checkout');+ });++ test('extracts a credential helper dispatched through the git namespace', () => {+ expect(+ detectMissingGitHelper("git: 'credential-manager' is not a git command. See 'git --help'."),+ ).toBe('credential-manager');+ });++ test('returns null for non-helper git failures', () => {+ expect(detectMissingGitHelper("fatal: 'dev' is already checked out at '/tmp/x'")).toBeNull();+ expect(detectMissingGitHelper("fatal: a branch named 'dev' already exists")).toBeNull();+ expect(detectMissingGitHelper("fatal: couldn't find remote ref refs/heads/gone")).toBeNull();+ expect(detectMissingGitHelper('fatal: not a git repository')).toBeNull();+ expect(detectMissingGitHelper('')).toBeNull();+ });++ // "ref not found"-style prose has no colon directly before the phrase, so+ // the shell-127 pattern must not fire on it.+ test('does not misread prose containing "not found" without a command colon', () => {+ expect(detectMissingGitHelper('fatal: remote ref not found')).toBeNull();+ });+});diff --git a/packages/core/src/git/missing-git-helper.ts b/packages/core/src/git/missing-git-helper.tsnew file mode 100644index 000000000..f6d93aa4c--- /dev/null+++ b/packages/core/src/git/missing-git-helper.ts@@ -0,0 +1,57 @@+/**+ * Classifier for git stderr that means "git spawned a configured helper+ * program and the OS couldn't find it" — the failure shape a minimal GUI+ * PATH produces for git-lfs filters, credential helpers, `core.sshCommand`,+ * `core.fsmonitor`, gpg, and `core.hooksPath` interpreters. Distinguishing+ * this class from generic git failures lets the UI say WHICH tool is missing+ * ("Git needs git-lfs…") instead of a retry-blind generic error.+ *+ * Matching assumes English-locale stderr — every OK git spawn pins+ * `LANG=C`/`LC_ALL=C` (see the desktop git spawn env and the server's+ * `buildGitEnv`), the same discipline `git-checkout.ts` relies on for its+ * stderr classification.+ */++/**+ * stderr shapes, one per spawn-failure surface:+ *+ * 1. Shell 127 phrasing — a filter/helper command line run via `sh -c`:+ * `git-lfs filter-process: git-lfs: command not found` (bash)+ * `sh: gpg: command not found` (bash)+ * `sh: 1: git-lfs: not found` (dash — Linux)+ * The token immediately before ": [command] not found" is the command the+ * shell failed to resolve (earlier `<label>:` prefixes are the reporting+ * program, not the missing one). Requiring the colon directly after the+ * token keeps prose like `fatal: remote ref not found` from matching.+ *+ * 2. git's own start_command failure (helpers git execs directly):+ * `error: cannot run gpg: No such file or directory`+ * `fatal: cannot run ssh: No such file or directory`+ *+ * 3. exec failure with a quoted path (hooks, sendemail helpers):+ * `fatal: cannot exec '.husky/post-checkout': No such file or directory`+ *+ * 4. credential-helper dispatch through the git command namespace:+ * `git: 'credential-manager' is not a git command. See 'git --help'.`+ */+const MISSING_HELPER_PATTERNS: readonly RegExp[] = [+ /([^\s:'"]+): (?:command )?not found/,+ /cannot run ([^:\n]+): No such file or directory/,+ /cannot exec '([^']+)': No such file or directory/,+ /git: '(credential-[^']+)' is not a git command/,+];++/**+ * Extract the missing command from git stderr, or `null` when the failure is+ * not the missing-helper class. Returns the command as reported (a bare name+ * for PATH lookups, a path for hook exec failures); callers display it+ * verbatim. First matching pattern wins.+ */+export function detectMissingGitHelper(stderr: string): string | null {+ for (const pattern of MISSING_HELPER_PATTERNS) {+ const match = pattern.exec(stderr);+ const command = match?.[1]?.trim();+ if (command !== undefined && command.length > 0) return command;+ }+ return null;+}diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.tsindex 418297d1b..1e7dcf26a 100644--- a/packages/core/src/git/worktree-selector-model.ts+++ b/packages/core/src/git/worktree-selector-model.ts@@ -124,6 +124,18 @@ export interface WorktreeCreateRequest {*/export type WorktreeCreateResult =| { readonly ok: true; readonly path: string; readonly created: boolean }+ | {+ readonly ok: false;+ readonly reason: 'helper-not-found';+ /**+ * The command git tried to spawn and couldn't resolve (e.g. `git-lfs`),+ * extracted by `detectMissingGitHelper`. Required on this arm so a+ * producer can't emit the reason without naming the tool — the failure+ * copy shows it verbatim so the user knows what to install.+ */+ readonly helper: string;+ readonly message?: string;+ }| {readonly ok: false;readonly reason:@@ -136,6 +148,7 @@ export type WorktreeCreateResult =| 'fetch-failed'| 'error';readonly message?: string;+ readonly helper?: never;};export interface BuildWorktreeSelectorModelInput {diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f810625d2..14c0d0688 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -334,6 +334,12 @@ export {type WikiLinkEmbedAttrs,} from './extensions/wiki-link-embed.ts';export { parseBranchList } from './git/branch-list-parser.ts';+export {+ augmentGitSpawnPath,+ type GitSpawnPathOptions,+ wellKnownToolDirs,+} from './git/git-spawn-path.ts';+export { detectMissingGitHelper } from './git/missing-git-helper.ts';export {type BridgeWorktreeEntry,parseWorktreeListPorcelain,diff --git a/packages/desktop/src/main/git-spawn-env.ts b/packages/desktop/src/main/git-spawn-env.tsnew file mode 100644index 000000000..d5a9d5987--- /dev/null+++ b/packages/desktop/src/main/git-spawn-env.ts@@ -0,0 +1,57 @@+/**+ * Shared spawn env for every desktop-main git invocation.+ *+ * Packaged Electron inherits launchd's minimal `PATH` (Finder launch AND the+ * CLI handoff — `open -b` routes through LaunchServices, so the app never+ * sees a terminal's PATH). git survives that, but the helper subprocesses git+ * spawns mid-operation (git-lfs filters, credential helpers, hooks) are+ * typically Homebrew installs that minimal PATH can't resolve, and a missing+ * required helper aborts the whole operation. `augmentGitSpawnPath` appends+ * well-known tool directories so those helpers resolve; existing PATH entries+ * keep priority (append-only).+ *+ * `LANG=C`/`LC_ALL=C` pin stderr to English so classification+ * (`detectMissingGitHelper`, the add-error / branch-gone matchers) survives a+ * non-English host locale — same discipline as the server's `buildGitEnv`.+ *+ * Computed lazily and cached: the augmentation stats well-known directories,+ * and PATH/homedir don't change within a process lifetime.+ */++import { existsSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { delimiter } from 'node:path';+import { augmentGitSpawnPath } from '@inkeep/open-knowledge-core';++let cached: Record<string, string | undefined> | null = null;++/** True iff `dir` exists and is a directory (symlinks followed). */+function isDir(dir: string): boolean {+ try {+ return existsSync(dir) && statSync(dir).isDirectory();+ } catch {+ return false;+ }+}++/**+ * The env for desktop-main git spawns: `process.env` with augmented PATH and+ * pinned English locale. Callers spread additional vars on top (e.g. the+ * share-fetch arm's `GIT_TERMINAL_PROMPT=0`).+ */+export function gitSpawnEnv(): Record<string, string | undefined> {+ if (cached === null) {+ cached = {+ ...process.env,+ LANG: 'C',+ LC_ALL: 'C',+ PATH: augmentGitSpawnPath(process.env.PATH, {+ platform: process.platform,+ homeDir: homedir(),+ isDir,+ delimiter,+ }),+ };+ }+ return cached;+}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 73ab8255f..f64e51426 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -4107,17 +4107,33 @@ function registerIpcHandlers() {if (request.kind === 'list') {return listWorktreeSelector(anchor, anchor);}- if (request.kind === 'checkout') {- return checkoutShareBranchWorktree({ anchorPath: anchor, branch: request.branch });+ const result =+ request.kind === 'checkout'+ ? await checkoutShareBranchWorktree({ anchorPath: anchor, branch: request.branch })+ : await createWorktree({+ anchorPath: anchor,+ branch: request.branch,+ baseBranch: request.baseBranch,+ baseRef: request.baseRef,+ remoteRef: request.remoteRef,+ createBranch: request.createBranch,+ });+ if (!result.ok) {+ // The renderer's toast shows only the typed reason; the classified git+ // stderr in `message` (and the missing-helper name) lands here so a+ // failure is diagnosable from ~/.ok/logs without a devtools session.+ getLogger('worktree').warn(+ {+ kind: request.kind,+ reason: result.reason,+ helper: result.helper,+ message: result.message,+ branch: request.branch,+ },+ 'worktree dispatch failed',+ );}- return createWorktree({- anchorPath: anchor,- branch: request.branch,- baseBranch: request.baseBranch,- baseRef: request.baseRef,- remoteRef: request.remoteRef,- createBranch: request.createBranch,- });+ return result;});handle('ok:share:validate-folder', async (_event, request) => {diff --git a/packages/desktop/src/main/list-git-worktrees.ts b/packages/desktop/src/main/list-git-worktrees.tsindex f6987fcaf..969f49ab9 100644--- a/packages/desktop/src/main/list-git-worktrees.ts+++ b/packages/desktop/src/main/list-git-worktrees.ts@@ -24,6 +24,7 @@ import { realpathSync } from 'node:fs';import { isAbsolute } from 'node:path';import { promisify } from 'node:util';import { type BridgeWorktreeEntry, parseWorktreeListPorcelain } from '@inkeep/open-knowledge-core';+import { gitSpawnEnv } from './git-spawn-env.ts';const execFileAsync = promisify(execFile);@@ -61,7 +62,7 @@ export async function listGitWorktrees(anchorPath: string): Promise<BridgeWorktrtry {const result = await execFileAsync('git', ['worktree', 'list', '--porcelain'], {cwd: anchorPath,- env: { ...process.env, LANG: 'C', LC_ALL: 'C' },+ env: gitSpawnEnv(),maxBuffer: MAX_STDOUT_BYTES,});stdout = String(result.stdout);diff --git a/packages/desktop/src/main/worktree-recents.ts b/packages/desktop/src/main/worktree-recents.tsindex 2b1b98c03..35f41cc28 100644--- a/packages/desktop/src/main/worktree-recents.ts+++ b/packages/desktop/src/main/worktree-recents.ts@@ -22,8 +22,9 @@ import { execFile, execFileSync } from 'node:child_process';import { realpathSync } from 'node:fs';import { basename, dirname, isAbsolute, resolve } from 'node:path';import { promisify } from 'node:util';+import { gitSpawnEnv } from './git-spawn-env.ts';-const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C' } as const;+const GIT_ENV = gitSpawnEnv();const execFileAsync = promisify(execFile);diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.tsindex 9c1d83b22..2375005b2 100644--- a/packages/desktop/src/main/worktree-service.test.ts+++ b/packages/desktop/src/main/worktree-service.test.ts@@ -328,6 +328,52 @@ describe('worktree-service', () => {expect(res.reason).toBe('path-exists');});+ // drive the `helper-not-found` branch via a real git failure: a REQUIRED+ // clean/smudge filter whose command doesn't exist anywhere on PATH — the+ // same failure shape a Homebrew git-lfs produces under a packaged app's+ // minimal launchd PATH (the checkout aborts before writing any files).+ test('createWorktree classifies a missing required filter as helper-not-found', async () => {+ handle = await makeRepo();+ const missing = 'ok-test-missing-helper-cmd';+ await git(handle.mainRepo, 'config', 'filter.okbogus.clean', `${missing} clean`);+ await git(handle.mainRepo, 'config', 'filter.okbogus.smudge', `${missing} smudge`);+ await git(handle.mainRepo, 'config', 'filter.okbogus.required', 'true');+ writeFileSync(join(handle.mainRepo, '.gitattributes'), 'data.bin filter=okbogus\n');+ // Commit the attributed file with the filter DISABLED (`-c` outranks the+ // repo config) so the fixture commit itself doesn't need the helper.+ writeFileSync(join(handle.mainRepo, 'data.bin'), 'payload\n');+ await git(+ handle.mainRepo,+ '-c',+ 'filter.okbogus.required=false',+ '-c',+ 'filter.okbogus.clean=cat',+ 'add',+ '-A',+ );+ await git(+ handle.mainRepo,+ '-c',+ 'filter.okbogus.required=false',+ '-c',+ 'filter.okbogus.clean=cat',+ 'commit',+ '-m',+ 'add filtered file',+ );+ await git(handle.mainRepo, 'branch', 'filtered');+ const res = await createWorktree({+ anchorPath: handle.mainRepo,+ branch: 'filtered',+ createBranch: false,+ });+ expect(res.ok).toBe(false);+ if (res.ok) return;+ expect(res.reason).toBe('helper-not-found');+ expect(res.helper).toContain(missing);+ expect((res.message ?? '').length).toBeGreaterThan(0);+ });+// drive the `error` fallthrough with a git failure that matches none of// the recognized classifications, and confirm the raw stderr is surfaced.test('createWorktree surfaces an unrecognized git failure as error with a message', async () => {diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.tsindex 674db9008..170df6771 100644--- a/packages/desktop/src/main/worktree-service.ts+++ b/packages/desktop/src/main/worktree-service.ts@@ -27,6 +27,7 @@ import { isAbsolute, join, sep } from 'node:path';import { promisify } from 'node:util';import {buildWorktreeSelectorModel,+ detectMissingGitHelper,isBranchNotFoundGitError,isValidBranchName,parseBranchList,@@ -37,6 +38,7 @@ import {type WorktreeListResult,worktreeRelativeDir,} from '@inkeep/open-knowledge-core';+import { gitSpawnEnv } from './git-spawn-env.ts';import { listGitWorktrees } from './list-git-worktrees.ts';import { seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';import { clearRecentGitCache } from './worktree-recents.ts';@@ -44,9 +46,8 @@ import { seedWorktreeProjectSetup } from './worktree-setup-inherit.ts';const execFileAsync = promisify(execFile);-/** English-stable git env — mirrors `list-git-worktrees.ts` so stderr- * classification survives a non-English host locale. */-const GIT_ENV = { ...process.env, LANG: 'C', LC_ALL: 'C' } as const;+/** English-stable, PATH-augmented git env — see `git-spawn-env.ts`. */+const GIT_ENV = gitSpawnEnv();/** Fetch spawn env: `GIT_ENV` plus `GIT_TERMINAL_PROMPT=0`, mirroring the* server's git discipline — desktop main has no terminal to answer a@@ -516,10 +517,19 @@ interface ExecErr {message?: string;}-interface AddErrorClassification {- readonly reason: 'branch-exists' | 'already-checked-out' | 'path-exists' | 'error';- readonly message?: string;-}+type AddErrorClassification =+ | {+ /** The command git couldn't spawn — required, mirroring the+ * `WorktreeCreateResult` arm this classification flows into. */+ readonly reason: 'helper-not-found';+ readonly helper: string;+ readonly message?: string;+ }+ | {+ readonly reason: 'branch-exists' | 'already-checked-out' | 'path-exists' | 'error';+ readonly message?: string;+ readonly helper?: never;+ };/** Raw error text of a failed git spawn: stderr when present (Buffer or* string), else the error message. Buffer.isBuffer narrows the stable@@ -544,5 +554,12 @@ function classifyAddError(err: unknown): AddErrorClassification {return { reason: 'branch-exists' };}if (stderr.includes('already exists')) return { reason: 'path-exists' };+ // A configured helper (git-lfs filter, credential helper, hook interpreter)+ // that PATH can't resolve — surfaced by name so the failure copy can say+ // which tool to install instead of the retry-blind generic arm.+ const helper = detectMissingGitHelper(raw);+ if (helper !== null) {+ return { reason: 'helper-not-found', helper, message: raw.replace(/\s+/g, ' ').slice(0, 300) };+ }return { reason: 'error', message: raw.replace(/\s+/g, ' ').slice(0, 300) };}diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.tsindex 35ae6ede5..bc5e77721 100644--- a/packages/server/src/git-handle.test.ts+++ b/packages/server/src/git-handle.test.ts@@ -49,9 +49,12 @@ describe('buildGitEnv', () => {expect(buildGitEnv().GIT_MERGE_AUTOEDIT).toBe('no');});- test('preserves PATH so a bare-command credential helper resolves', () => {+ test('preserves PATH (as a prefix) so a bare-command credential helper resolves', () => {withEnvEntries({ PATH: '/custom/bin:/usr/bin' }, () => {- expect(buildGitEnv().PATH).toBe('/custom/bin:/usr/bin');+ // Augmentation may APPEND well-known tool dirs (git-lfs & co. under a+ // packaged app's minimal launchd PATH) but must never reorder or drop+ // the inherited entries — existing resolution stays authoritative.+ expect(buildGitEnv().PATH?.startsWith('/custom/bin:/usr/bin')).toBe(true);});});diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.tsindex 6a9a5dac9..fa4223f80 100644--- a/packages/server/src/git-handle.ts+++ b/packages/server/src/git-handle.ts@@ -6,9 +6,24 @@* write operations to prevent concurrent git index corruption.*/-import { resolve } from 'node:path';+import { existsSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { delimiter, resolve } from 'node:path';+import { augmentGitSpawnPath } from '@inkeep/open-knowledge-core';import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';+/** Existence probe for `augmentGitSpawnPath` — directories only. Named to+ * match the `GitSpawnPathOptions.isDir` seam (and the desktop twin in+ * `git-spawn-env.ts`); duplicated rather than shared because core stays+ * browser-compatible and can't export a `node:fs` probe. */+function isDir(dir: string): boolean {+ try {+ return existsSync(dir) && statSync(dir).isDirectory();+ } catch {+ return false;+ }+}+export { withParentLock } from './git-mutex.ts';// ---------------------------------------------------------------------------@@ -143,10 +158,19 @@ export function buildGitEnv(ghToken?: RelayGhToken): Record<string, string> {GIT_TERMINAL_PROMPT: '0',GIT_MERGE_AUTOEDIT: 'no',};+ // Augmented, not raw: a packaged-desktop-spawned server inherits launchd's+ // minimal PATH, which resolves git but NOT the helpers git spawns+ // mid-operation (git-lfs filters, credential helpers, hooks). Appending+ // well-known tool dirs keeps existing PATH entries authoritative while+ // making those helpers resolvable — the terminal-launched `ok start` path+ // is a no-op (its PATH already contains them).const path = process.env.PATH ?? process.env.Path;- if (path !== undefined) {- env.PATH = path;- }+ env.PATH = augmentGitSpawnPath(path, {+ platform: process.platform,+ homeDir: homedir(),+ isDir,+ delimiter,+ });for (const key of GIT_AUTH_ENV_KEYS) {const value = process.env[key];if (value !== undefined) env[key] = value;