Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): sync authenticates via gh token, matching clone (#1772)
miles-kt-inkeep645f58d686f5
diff --git a/.changeset/sync-gh-token-credential-relay.md b/.changeset/sync-gh-token-credential-relay.mdnew file mode 100644index 000000000..7c210b145--- /dev/null+++ b/.changeset/sync-gh-token-credential-relay.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++Sync now authenticates to GitHub using your `gh` CLI login, matching how clone already works. Previously the background sync engine only consulted Open Knowledge's own credential store, so users who were signed in with `gh` but had never completed a separate Open Knowledge sign-in saw a persistent "GitHub sign-in is missing or expired" error in the sync popover even though their `gh` session was valid. The server now resolves the `gh` token (the same source the push-permission check already used) and relays it to the git credential helper, which prefers it over its own stored token. A fresh `gh auth login` or a reconnect is picked up on the next sync cycle without a restart.++Also fixes `ok clone` so its `gh`-based authentication works on installs where `gh` lives outside the default PATH (e.g. Homebrew at `/opt/homebrew/bin`): clone now inherits your shell environment instead of replacing it, so the `gh` credential helper can locate `gh` and its config.diff --git a/packages/cli/src/commands/auth/git-credential.test.ts b/packages/cli/src/commands/auth/git-credential.test.tsindex 2cec49626..b7bed9110 100644--- a/packages/cli/src/commands/auth/git-credential.test.ts+++ b/packages/cli/src/commands/auth/git-credential.test.ts@@ -256,3 +256,108 @@ describe('handleCredentialGet diagnostic logging', () => {expect(result()).toBe('username=alice\npassword=gho_abc\n');});});++describe('handleCredentialGet gh-token relay', () => {+ let tmpDir: string;+ let savedToken: string | undefined;+ let savedHost: string | undefined;++ beforeEach(() => {+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-git-cred-relay-'));+ savedToken = process.env.OK_GH_TOKEN;+ savedHost = process.env.OK_GH_TOKEN_HOST;+ delete process.env.OK_GH_TOKEN;+ delete process.env.OK_GH_TOKEN_HOST;+ });+ afterEach(() => {+ rmSync(tmpDir, { recursive: true, force: true });+ if (savedToken === undefined) delete process.env.OK_GH_TOKEN;+ else process.env.OK_GH_TOKEN = savedToken;+ if (savedHost === undefined) delete process.env.OK_GH_TOKEN_HOST;+ else process.env.OK_GH_TOKEN_HOST = savedHost;+ });++ test('relayed token for a matching host wins over the stored entry', async () => {+ const store = makeStore(tmpDir);+ await store.set('github.com', 'alice', 'gho_stored');+ process.env.OK_GH_TOKEN = 'gho_relayed';+ process.env.OK_GH_TOKEN_HOST = 'github.com';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable, result } = makeOutput();++ const code = await handleCredentialGet(input, writable, store);++ expect(code).toBe(0);+ expect(result()).toBe('username=x-access-token\npassword=gho_relayed\n');+ });++ test('relayed token serves even when the store is empty (the reported bug)', async () => {+ const store = makeStore(tmpDir);+ process.env.OK_GH_TOKEN = 'gho_relayed';+ process.env.OK_GH_TOKEN_HOST = 'github.com';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable, result } = makeOutput();++ const code = await handleCredentialGet(input, writable, store);++ expect(code).toBe(0);+ expect(result()).toBe('username=x-access-token\npassword=gho_relayed\n');+ });++ test('host mismatch falls through to the stored entry', async () => {+ const store = makeStore(tmpDir);+ await store.set('github.com', 'alice', 'gho_stored');+ process.env.OK_GH_TOKEN = 'gho_relayed';+ process.env.OK_GH_TOKEN_HOST = 'ghe.internal.example';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable, result } = makeOutput();++ const code = await handleCredentialGet(input, writable, store);++ expect(code).toBe(0);+ expect(result()).toBe('username=alice\npassword=gho_stored\n');+ });++ test('token present but host var unset falls through to the store', async () => {+ const store = makeStore(tmpDir);+ await store.set('github.com', 'alice', 'gho_stored');+ process.env.OK_GH_TOKEN = 'gho_relayed';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable, result } = makeOutput();++ const code = await handleCredentialGet(input, writable, store);++ expect(code).toBe(0);+ expect(result()).toBe('username=alice\npassword=gho_stored\n');+ });++ test('CR and LF in the relayed token are stripped before write', async () => {+ const store = makeStore(tmpDir);+ process.env.OK_GH_TOKEN = 'gho_relayed\r\nurl=http://evil';+ process.env.OK_GH_TOKEN_HOST = 'github.com';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable, result } = makeOutput();++ const code = await handleCredentialGet(input, writable, store);++ expect(code).toBe(0);+ expect(result()).toBe('username=x-access-token\npassword=gho_relayedurl=http://evil\n');+ });++ test('logs gh-env-token at debug and never the token', async () => {+ const store = makeStore(tmpDir);+ process.env.OK_GH_TOKEN = 'gho_relayed_secret';+ process.env.OK_GH_TOKEN_HOST = 'github.com';+ const input = makeStream('protocol=https\nhost=github.com\n\n');+ const { writable } = makeOutput();+ const { logger, calls } = makeFakeLogger();++ const code = await handleCredentialGet(input, writable, store, { log: logger });++ expect(code).toBe(0);+ expect(calls).toHaveLength(1);+ expect(calls[0]?.level).toBe('debug');+ expect(calls[0]?.fields).toMatchObject({ host: 'github.com', outcome: 'gh-env-token' });+ expect(JSON.stringify(calls)).not.toContain('gho_relayed_secret');+ });+});diff --git a/packages/cli/src/commands/auth/git-credential.ts b/packages/cli/src/commands/auth/git-credential.tsindex 31c7104df..9c8436b89 100644--- a/packages/cli/src/commands/auth/git-credential.ts+++ b/packages/cli/src/commands/auth/git-credential.ts@@ -21,6 +21,8 @@ export async function handleCredentialGet(const attrs = parseCredentialInput(text);const host = attrs.host ?? '';+ const safeLine = (s: string) => s.replace(/[\r\n]/g, '');+if (!host) {ctx?.log?.warn({ outcome: 'no-host', backend: tokenStore.backend },@@ -29,6 +31,17 @@ export async function handleCredentialGet(return 1;}+ const relayToken = process.env.OK_GH_TOKEN;+ const relayTokenHost = process.env.OK_GH_TOKEN_HOST;+ if (relayToken && relayTokenHost === host) {+ ctx?.log?.debug(+ { host, outcome: 'gh-env-token', backend: tokenStore.backend },+ '[auth] git-credential get',+ );+ output.write(`username=x-access-token\npassword=${safeLine(relayToken)}\n`);+ return 0;+ }+const entry = await tokenStore.get(host);const diag = ctx?.getDiag?.();const outcome = entry != null ? 'found' : (diag?.kind ?? 'absent');@@ -45,7 +58,6 @@ export async function handleCredentialGet(if (entry == null) return 1;- const safeLine = (s: string) => s.replace(/[\r\n]/g, '');output.write(`username=${safeLine(entry.login)}\npassword=${safeLine(entry.token)}\n`);return 0;}diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.tsindex 72560f080..93fbae87f 100644--- a/packages/cli/src/commands/clone.test.ts+++ b/packages/cli/src/commands/clone.test.ts@@ -6,12 +6,33 @@ import { join, resolve } from 'node:path';import { OK_DIR } from '../constants.ts';import {buildCloneArgs,+ buildCloneEnv,cloneWithBranchFallback,ensureOkExcludedFromGit,isBranchNotFoundError,shouldSkipAuthForPublicRepo,} from './clone.ts';+describe('buildCloneEnv', () => {+ test('inherits PATH and HOME from the source env', () => {+ const env = buildCloneEnv({ PATH: '/opt/homebrew/bin:/usr/bin', HOME: '/Users/me' });+ expect(env.PATH).toBe('/opt/homebrew/bin:/usr/bin');+ expect(env.HOME).toBe('/Users/me');+ });++ test('pins GIT_TERMINAL_PROMPT=0 and LANG/LC_ALL=C, overriding inherited locale', () => {+ const env = buildCloneEnv({ PATH: '/usr/bin', LANG: 'fr_FR.UTF-8', LC_ALL: 'fr_FR.UTF-8' });+ expect(env.GIT_TERMINAL_PROMPT).toBe('0');+ expect(env.LANG).toBe('C');+ expect(env.LC_ALL).toBe('C');+ });++ test('drops undefined entries (no `undefined` strings reach the child env)', () => {+ const env = buildCloneEnv({ PATH: '/usr/bin', SOME_UNSET: undefined });+ expect('SOME_UNSET' in env).toBe(false);+ });+});+describe('shouldSkipAuthForPublicRepo', () => {test('https + github.com + isPublic=true → true (anonymous clone path)', () => {expect(shouldSkipAuthForPublicRepo('https', 'github.com', true)).toBe(true);diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.tsindex dd6e5babb..e0364bfb4 100644--- a/packages/cli/src/commands/clone.ts+++ b/packages/cli/src/commands/clone.ts@@ -35,6 +35,17 @@ function emit(json: boolean, obj: Record<string, unknown>): void {if (json) process.stdout.write(`${JSON.stringify(obj)}\n`);}+export function buildCloneEnv(sourceEnv: NodeJS.ProcessEnv = process.env): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [key, value] of Object.entries(sourceEnv)) {+ if (value !== undefined) env[key] = value;+ }+ env.GIT_TERMINAL_PROMPT = '0';+ env.LANG = 'C';+ env.LC_ALL = 'C';+ return env;+}+export function buildCloneArgs(branch: string | null | undefined): string[] {if (typeof branch !== 'string' || branch.length === 0) return ['--progress'];return ['--progress', '-b', branch];@@ -108,9 +119,7 @@ async function runClone(? { tier: 'none' as const, credentialArgs: [] as string[] }: await resolveAuth(parsed.hostname, tokenStore, {});- const env: Record<string, string> = {- GIT_TERMINAL_PROMPT: '0',- };+ const env = buildCloneEnv();const gitConfig = resolved.credentialArgs.length >= 2 ? [resolved.credentialArgs[1]] : [];diff --git a/packages/server/src/gh-token-source.test.ts b/packages/server/src/gh-token-source.test.tsnew file mode 100644index 000000000..925102435--- /dev/null+++ b/packages/server/src/gh-token-source.test.ts@@ -0,0 +1,92 @@+import { describe, expect, test } from 'bun:test';+import { createGhTokenSource } from './gh-token-source.ts';+import type { DetectGhFn } from './github-permissions.ts';++function makeDetectGh(result: ReturnType<DetectGhFn>): { fn: DetectGhFn; calls: () => number } {+ let calls = 0;+ return {+ fn: (_host?: string) => {+ calls++;+ return result;+ },+ calls: () => calls,+ };+}++function makeClock(start = 1_000): { now: () => number; advance: (ms: number) => void } {+ let t = start;+ return { now: () => t, advance: (ms: number) => (t += ms) };+}++describe('createGhTokenSource', () => {+ test('returns null throughout when no detectGh is injected', () => {+ const source = createGhTokenSource(undefined);+ expect(source.get('github.com')).toBeNull();+ });++ test('returns null when gh is unavailable', () => {+ const detect = makeDetectGh({ available: false });+ const source = createGhTokenSource(detect.fn);+ expect(source.get('github.com')).toBeNull();+ });++ test('returns null when gh is available but carries no token', () => {+ const detect = makeDetectGh({ available: true });+ const source = createGhTokenSource(detect.fn);+ expect(source.get('github.com')).toBeNull();+ });++ test('resolves the token host-scoped when gh is authenticated', () => {+ const detect = makeDetectGh({ available: true, token: 'gho_abc' });+ const source = createGhTokenSource(detect.fn);+ expect(source.get('github.com')).toEqual({ token: 'gho_abc', host: 'github.com' });+ });++ test('caches within the TTL — only one detectGh call', () => {+ const detect = makeDetectGh({ available: true, token: 'gho_abc' });+ const clock = makeClock();+ const source = createGhTokenSource(detect.fn, { ttlMs: 60_000, now: clock.now });++ source.get('github.com');+ clock.advance(59_000);+ source.get('github.com');++ expect(detect.calls()).toBe(1);+ });++ test('re-resolves after the TTL expires', () => {+ const detect = makeDetectGh({ available: true, token: 'gho_abc' });+ const clock = makeClock();+ const source = createGhTokenSource(detect.fn, { ttlMs: 60_000, now: clock.now });++ source.get('github.com');+ clock.advance(60_001);+ source.get('github.com');++ expect(detect.calls()).toBe(2);+ });++ test('caches the negative result too (no token) within the TTL', () => {+ const detect = makeDetectGh({ available: false });+ const clock = makeClock();+ const source = createGhTokenSource(detect.fn, { ttlMs: 60_000, now: clock.now });++ expect(source.get('github.com')).toBeNull();+ clock.advance(30_000);+ expect(source.get('github.com')).toBeNull();++ expect(detect.calls()).toBe(1);+ });++ test('invalidate() forces the next get to re-resolve', () => {+ const detect = makeDetectGh({ available: true, token: 'gho_abc' });+ const clock = makeClock();+ const source = createGhTokenSource(detect.fn, { ttlMs: 60_000, now: clock.now });++ source.get('github.com');+ source.invalidate();+ source.get('github.com');++ expect(detect.calls()).toBe(2);+ });+});diff --git a/packages/server/src/gh-token-source.ts b/packages/server/src/gh-token-source.tsnew file mode 100644index 000000000..23fad0b49--- /dev/null+++ b/packages/server/src/gh-token-source.ts@@ -0,0 +1,49 @@+import type { RelayGhToken } from './git-handle.ts';+import type { DetectGhFn } from './github-permissions.ts';++export interface GhTokenSource {+ get(host: string): RelayGhToken | null;+ invalidate(): void;+}++interface CacheEntry {+ token: string | null;+ expiresAt: number;+}++export interface GhTokenSourceOptions {+ ttlMs?: number;+ now?: () => number;+}++const DEFAULT_TTL_MS = 60_000;++export function createGhTokenSource(+ detectGh: DetectGhFn | undefined,+ options: GhTokenSourceOptions = {},+): GhTokenSource {+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;+ const now = options.now ?? Date.now;+ const cache = new Map<string, CacheEntry>();++ return {+ get(host: string): RelayGhToken | null {+ if (!detectGh) return null;++ const t = now();+ const cached = cache.get(host);+ if (cached && cached.expiresAt > t) {+ return cached.token != null ? { token: cached.token, host } : null;+ }++ const result = detectGh(host);+ const token = result.available && result.token ? result.token : null;+ cache.set(host, { token, expiresAt: t + ttlMs });+ return token != null ? { token, host } : null;+ },++ invalidate(): void {+ cache.clear();+ },+ };+}diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.tsindex eadaf9843..4ef1c5bb0 100644--- a/packages/server/src/git-handle.test.ts+++ b/packages/server/src/git-handle.test.ts@@ -47,6 +47,16 @@ describe('buildGitEnv', () => {expect('ELECTRON_RUN_AS_NODE' in buildGitEnv()).toBe(false);});});++ test('emits OK_GH_TOKEN/OK_GH_TOKEN_HOST only when a relay token is supplied', () => {+ const without = buildGitEnv();+ expect('OK_GH_TOKEN' in without).toBe(false);+ expect('OK_GH_TOKEN_HOST' in without).toBe(false);++ const withToken = buildGitEnv({ token: 'gho_relayed', host: 'github.com' });+ expect(withToken.OK_GH_TOKEN).toBe('gho_relayed');+ expect(withToken.OK_GH_TOKEN_HOST).toBe('github.com');+ });});describe('createGitInstance (credential.helper config)', () => {diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.tsindex 71ba2f48b..be8409285 100644--- a/packages/server/src/git-handle.ts+++ b/packages/server/src/git-handle.ts@@ -3,9 +3,15 @@ import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';export { withParentLock } from './git-mutex.ts';+export interface RelayGhToken {+ token: string;+ host: string;+}+interface GitHandleOptions {credentialArgs?: string[];gitIndexFile?: string;+ ghToken?: RelayGhToken;}export interface GitHandle {@@ -20,7 +26,7 @@ type CredentialHelperUnsafeGitOptions = SimpleGitOptions & {};};-export function buildGitEnv(): Record<string, string> {+export function buildGitEnv(ghToken?: RelayGhToken): Record<string, string> {const env: Record<string, string> = { LANG: 'C', LC_ALL: 'C', GIT_TERMINAL_PROMPT: '0' };if (process.env.PATH !== undefined) {env.PATH = process.env.PATH;@@ -28,13 +34,17 @@ export function buildGitEnv(): Record<string, string> {if (process.env.ELECTRON_RUN_AS_NODE !== undefined) {env.ELECTRON_RUN_AS_NODE = process.env.ELECTRON_RUN_AS_NODE;}+ if (ghToken) {+ env.OK_GH_TOKEN = ghToken.token;+ env.OK_GH_TOKEN_HOST = ghToken.host;+ }return env;}export function createGitInstance(projectDir: string, options: GitHandleOptions = {}): GitHandle {- const { credentialArgs = [], gitIndexFile } = options;+ const { credentialArgs = [], gitIndexFile, ghToken } = options;- const env: Record<string, string | undefined> = buildGitEnv();+ const env: Record<string, string | undefined> = buildGitEnv(ghToken);if (gitIndexFile) {env.GIT_INDEX_FILE = resolve(projectDir, gitIndexFile);}diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex bcac7e406..b93aef004 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -7,6 +7,8 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { LOCAL_DIR } from '@inkeep/open-knowledge-core';import simpleGit from 'simple-git';+import { classifyGitError } from './error-classification.ts';+import type { DetectGhFn } from './github-permissions.ts';import type { SyncState } from './sync-engine.ts';import { SyncEngine } from './sync-engine.ts';@@ -1359,6 +1361,8 @@ interface InternalState {pullError?: string;pushErrorCode?: string;pullErrorCode?: string;+ gitHandle: () => unknown;+ handleError: (classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull') => void;}describe('SyncEngine auth-error recovery', () => {@@ -1433,3 +1437,88 @@ describe('SyncEngine auth-error recovery', () => {expect(engine.getStatus().state).toBe(before);});});++function recordDetectGh(result: ReturnType<DetectGhFn>): {+ fn: DetectGhFn;+ calls: () => number;+ lastHost: () => string | undefined;+} {+ let calls = 0;+ let lastHost: string | undefined;+ return {+ fn: (host?: string) => {+ calls++;+ lastHost = host;+ return result;+ },+ calls: () => calls,+ lastHost: () => lastHost,+ };+}++describe('SyncEngine gh-token credential relay', () => {+ test('threads the resolved gh token through git handles during a real push cycle', async () => {+ const git = simpleGit(projectDir);+ await git.init(['--initial-branch=main']);+ await git.raw('config', 'user.name', 'Test');+ await git.raw('config', 'user.email', '[email protected]');+ writeFileSync(join(projectDir, 'README.md'), '# Test\n');+ await git.add('.');+ await git.commit('Initial');++ const bareDir = join(tmpDir, 'bare.git');+ mkdirSync(bareDir, { recursive: true });+ await simpleGit(bareDir).init(true);+ await git.addRemote('origin', bareDir);+ await git.push(['--set-upstream', 'origin', 'main']);++ writeFileSync(join(projectDir, 'README.md'), '# Test\n\nchange\n');+ await git.add('.');+ await git.commit('local commit');++ const detect = recordDetectGh({ available: true, token: 'gho_relayed' });+ const engine = new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ detectGh: detect.fn,+ });+ try {+ await engine.start();+ await engine.trigger('push');++ expect(detect.calls()).toBeGreaterThan(0);+ expect(detect.lastHost()).toBe('github.com');+ } finally {+ await engine.destroy();+ }+ });++ test('caches the gh token across handles, then re-resolves after an auth error', () => {+ const detect = recordDetectGh({ available: true, token: 'gho_relayed' });+ const engine = new SyncEngine({+ projectDir,+ contentDir,+ contentFilter: stubContentFilter,+ syncEnabled: true,+ detectGh: detect.fn,+ });+ const internal = engine as unknown as InternalState;++ internal.gitHandle();+ internal.gitHandle();+ expect(detect.calls()).toBe(1);++ internal.handleError(+ classifyGitError(+ new Error(+ 'fatal: could not read Username for https://github.com: terminal prompts disabled',+ ),+ ),+ 'push',+ );+ internal.gitHandle();+ expect(detect.calls()).toBe(2);+ });+});diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex e284ba120..1bed2d2c6 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -20,6 +20,7 @@ import {classifyGitError,type UserFacingErrorCode,} from './error-classification.ts';+import { createGhTokenSource, type GhTokenSource } from './gh-token-source.ts';import { createGitInstance, type GitHandle, withParentLock } from './git-handle.ts';import { resolveGitIdentity } from './git-identity.ts';import {@@ -41,6 +42,8 @@ const log = getLogger('sync-engine');const SHA_HEX_40 = /^[0-9a-f]{40}$/i;+const SYNC_GH_TOKEN_HOST = 'github.com';+export type SyncState =| 'dormant'| 'idle'@@ -192,6 +195,7 @@ export class SyncEngine {private setBatchInProgress: ((value: boolean) => void) | undefined;private onAutoDisable: ((reason: 'protected-branch') => void | Promise<void>) | undefined;private detectGh: DetectGhFn | undefined;+ private ghTokenSource: GhTokenSource;private tokenStore: ProbeTokenStore | null | undefined;private checkPushPermissionFn: (opts: CheckPushPermissionOptions) => Promise<PushPermission>;private pushPermission: PushPermissionStatus | null = null;@@ -240,12 +244,21 @@ export class SyncEngine {this.setBatchInProgress = options.setBatchInProgress;this.onAutoDisable = options.onAutoDisable;this.detectGh = options.detectGh;+ this.ghTokenSource = createGhTokenSource(options.detectGh);this.tokenStore = options.tokenStore;this.checkPushPermissionFn = options.checkPushPermissionFn ?? defaultCheckPushPermission;this.statePath = resolve(getLocalDir(this.projectDir), 'sync-state.json');this.conflictStore = new ConflictStore(this.projectDir, this.currentBranch);}+ private gitHandle(gitIndexFile?: string): GitHandle {+ return createGitInstance(this.projectDir, {+ credentialArgs: this.credentialArgs,+ gitIndexFile,+ ghToken: this.ghTokenSource.get(SYNC_GH_TOKEN_HOST) ?? undefined,+ });+ }+async start(): Promise<void> {if (this.state !== 'dormant') return;@@ -253,9 +266,7 @@ export class SyncEngine {let hasRemote = false;try {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const handle = this.gitHandle();const remoteOutput = await handle.git.raw('remote', '-v');hasRemote = remoteOutput.trim().length > 0;this.hasRemote = hasRemote;@@ -304,9 +315,7 @@ export class SyncEngine {this.conflictCount = 0;} else if (this.conflictCount > 0 && mergeInProgress) {try {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const handle = this.gitHandle();const out = (await handle.git.raw(['diff', '--name-only', '--diff-filter=U'])).trim();const stillUnmerged = new Set(out@@ -337,7 +346,7 @@ export class SyncEngine {if (mergeInProgress && this.conflictCount === 0) {log.warn({}, '[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge');try {- const handle = createGitInstance(this.projectDir, { credentialArgs: this.credentialArgs });+ const handle = this.gitHandle();await handle.git.raw(['merge', '--abort']);} catch (e) {log.warn({ err: e }, '[sync] git merge --abort for stale MERGE_HEAD failed');@@ -444,6 +453,9 @@ export class SyncEngine {async notifyCredentialsChanged(): Promise<void> {if (!this.syncEnabled) return;++ this.ghTokenSource.invalidate();+if (this.state !== 'auth-error' && this.pausedReason !== 'auth-error') return;this.pausedReason = undefined;@@ -640,9 +652,7 @@ export class SyncEngine {private async probeRemote(): Promise<boolean> {if (!existsSync(join(this.projectDir, '.git'))) return false;try {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const handle = this.gitHandle();const remoteOutput = await handle.git.raw('remote', '-v');return remoteOutput.trim().length > 0;} catch (e) {@@ -671,9 +681,7 @@ export class SyncEngine {this.conflictCount = 0;} else {try {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const handle = this.gitHandle();const out = (await handle.git.raw(['diff', '--name-only', '--diff-filter=U'])).trim();const stillUnmerged = new Set(out@@ -812,9 +820,7 @@ export class SyncEngine {}private async doPullCycle(): Promise<void> {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const handle = this.gitHandle();let branch: string;try {@@ -911,10 +917,7 @@ export class SyncEngine {try {await withParentLock(async () => {- const handle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- gitIndexFile: tmpIndexPath,- });+ const handle = this.gitHandle(tmpIndexPath);if (isUnbornHead(this.projectDir)) {log.info({}, '[sync] repo has no commits yet — skipping push cycle');@@ -1105,9 +1108,7 @@ export class SyncEngine {if (classified.class === 'semantic' && classified.subclass === 'non-fast-forward') {if (retriesLeft > 0) {log.info({}, '[sync] push rejected (non-fast-forward) — fetching, merging, retrying');- const retryHandle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const retryHandle = this.gitHandle();this.setBatchInProgress?.(true);try {await retryHandle.git.fetch('origin');@@ -1164,10 +1165,7 @@ export class SyncEngine {if (contentFiles.length === 0 && headContentSet.size === 0) return null;const tmpIndex = join(tmpdir(), `ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`);- const isoHandle = createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- gitIndexFile: tmpIndex,- });+ const isoHandle = this.gitHandle(tmpIndex);try {await isoHandle.git.raw(['read-tree', headSha]);const BATCH = 100;@@ -1361,11 +1359,7 @@ export class SyncEngine {private async resetRealIndexForPaths(paths: string[], handle?: GitHandle): Promise<void> {if (paths.length === 0) return;- const realIndexHandle =- handle ??- createGitInstance(this.projectDir, {- credentialArgs: this.credentialArgs,- });+ const realIndexHandle = handle ?? this.gitHandle();const unique = [...new Set(paths)];const BATCH = 100;for (let i = 0; i < unique.length; i += BATCH) {@@ -1387,7 +1381,7 @@ export class SyncEngine {}private async handleMergeConflict(): Promise<void> {- const handle = createGitInstance(this.projectDir, { credentialArgs: this.credentialArgs });+ const handle = this.gitHandle();let conflictedFiles: string[] = [];try {@@ -1561,6 +1555,7 @@ export class SyncEngine {);if (classified.class === 'auth') {+ this.ghTokenSource.invalidate();this.transitionTo('auth-error');this.pausedReason = 'auth-error';} else if (classified.class === 'semantic' && classified.subclass === 'protected-branch') {