Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): discover git identity from included git configs (#2864)

omar-inkeepcbdc10b54ca6
diff --git a/.changeset/git-identity-included-configs.md b/.changeset/git-identity-included-configs.md
new file mode 100644
index 000000000..badd6013c
--- /dev/null
+++ b/.changeset/git-identity-included-configs.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Discover git committer identity supplied through included git configs. Auto-save commit identity resolution now reads the effective merged git config (`git config --get`) instead of probing the `--worktree`/`--local`/`--global` scopes one at a time. A scope-limited read only sees values written literally in that one file, so an identity provided via an `include` or `includeIf` directive (for example `gitdir:` or `hasconfig:remote.*.url:` identity switching) was invisible and OK fell back to prompting. The merged read is exactly what git resolves for a commit, so it honors full scope precedence and resolves included configs.
diff --git a/packages/app/src/hooks/use-git-sync-status.ts b/packages/app/src/hooks/use-git-sync-status.ts
index 25f8ecc74..f84855c0c 100644
--- a/packages/app/src/hooks/use-git-sync-status.ts
+++ b/packages/app/src/hooks/use-git-sync-status.ts
@@ -44,7 +44,7 @@ export interface GitSyncStatus {
/** User's sync toggle preference (false by default — disabled for safety). */
syncEnabled: boolean;
/**
- * Soft signal: the git identity chain (local → global → OAuth)
+ * Soft signal: the git identity chain (merged git config → OAuth)
* returned null on the last probe. Commits still succeed under a default
* identity — the UI surfaces a non-blocking nudge to set a real one.
*/
diff --git a/packages/server/src/git-identity.includes.test.ts b/packages/server/src/git-identity.includes.test.ts
new file mode 100644
index 000000000..96ab407b4
--- /dev/null
+++ b/packages/server/src/git-identity.includes.test.ts
@@ -0,0 +1,102 @@
+/**
+ * Integration tests for resolveGitIdentity against a real git repo whose
+ * identity is supplied through `include` / `includeIf` directives.
+ *
+ * Regression: users who switch committer identity via
+ * `includeIf "gitdir:…"` or `includeIf "hasconfig:remote.*.url:…"` in their
+ * global config saw OK fail to discover any identity. The old chain probed
+ * `--worktree` / `--local` / `--global` scopes one at a time, and a
+ * scope-limited read never resolves included config — only the effective
+ * merged read (`git config --get`) does.
+ *
+ * Isolation: GIT_CONFIG_GLOBAL points git at a temp global file and
+ * GIT_CONFIG_SYSTEM is neutralized, so the ambient developer / CI git identity
+ * cannot leak in. All other GIT_* vars are scrubbed so an inherited GIT_DIR
+ * doesn't redirect the reads into the surrounding repo.
+ */
+
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+
+import { resolveGitIdentity } from './git-identity.ts';
+
+function run(cwd: string, ...args: string[]): { status: number; stderr: string } {
+ const result = spawnSync('git', args, { cwd, encoding: 'utf-8', timeout: 10_000 });
+ return { status: result.status ?? -1, stderr: result.stderr?.trim() ?? '' };
+}
+
+describe('resolveGitIdentity with included git config', () => {
+ let tmp: string;
+ let repo: string;
+ let identityFile: string;
+ let globalFile: string;
+ let savedGitEnv: Record<string, string | undefined>;
+
+ beforeEach(() => {
+ // Scrub inherited GIT_* so a parent shell can't redirect our reads, then
+ // pin the global/system config so the developer's real identity can't leak.
+ savedGitEnv = {};
+ for (const k of Object.keys(process.env)) {
+ if (k.startsWith('GIT_')) {
+ savedGitEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ }
+
+ tmp = mkdtempSync(join(tmpdir(), 'ok-git-identity-inc-'));
+ repo = join(tmp, 'repo');
+ identityFile = join(tmp, 'identity');
+ globalFile = join(tmp, 'gitconfig');
+
+ process.env.GIT_CONFIG_GLOBAL = globalFile;
+ process.env.GIT_CONFIG_NOSYSTEM = '1';
+
+ writeFileSync(identityFile, '[user]\n\tname = Included Dev\n\temail = [email protected]\n');
+
+ expect(run(tmp, 'init', '-b', 'main', 'repo').status).toBe(0);
+ });
+
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ for (const k of Object.keys(process.env)) {
+ if (k.startsWith('GIT_')) delete process.env[k];
+ }
+ for (const [k, v] of Object.entries(savedGitEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ });
+
+ test('resolves identity from an unconditional [include] directive', async () => {
+ writeFileSync(globalFile, `[include]\n\tpath = ${identityFile}\n`);
+ const resolved = await resolveGitIdentity(repo);
+ expect(resolved).toEqual({ name: 'Included Dev', email: '[email protected]' });
+ });
+
+ test('resolves identity from includeIf "gitdir:" matching the repo', async () => {
+ // Glob on the unique temp-dir basename so symlinked temp roots
+ // (e.g. macOS /var -> /private/var) still match.
+ const marker = basename(tmp);
+ writeFileSync(globalFile, `[includeIf "gitdir:**/${marker}/**"]\n\tpath = ${identityFile}\n`);
+ const resolved = await resolveGitIdentity(repo);
+ expect(resolved).toEqual({ name: 'Included Dev', email: '[email protected]' });
+ });
+
+ test('resolves identity from includeIf "hasconfig:remote.*.url:" once the remote matches', async () => {
+ writeFileSync(
+ globalFile,
+ '[includeIf "hasconfig:remote.*.url:[email protected]:acme/**"]\n' +
+ `\tpath = ${identityFile}\n`,
+ );
+
+ // Before the matching remote exists the condition is false → no identity.
+ expect(await resolveGitIdentity(repo)).toBeNull();
+
+ expect(run(repo, 'remote', 'add', 'origin', '[email protected]:acme/thing.git').status).toBe(0);
+ const resolved = await resolveGitIdentity(repo);
+ expect(resolved).toEqual({ name: 'Included Dev', email: '[email protected]' });
+ });
+});
diff --git a/packages/server/src/git-identity.test.ts b/packages/server/src/git-identity.test.ts
index 616dab248..38f3a9e28 100644
--- a/packages/server/src/git-identity.test.ts
+++ b/packages/server/src/git-identity.test.ts
@@ -2,7 +2,12 @@
* Unit tests for resolveGitIdentity() — chain order + fallback logic.
* Uses injected GitConfigReader so no actual git or simple-git calls are made.
*
- * Chain: per-worktree → repo-local → global → tokenStore → null
+ * Chain: effective merged git config → tokenStore → null
+ *
+ * Scope precedence (system < global < local < worktree) and include / includeIf
+ * resolution are delegated to git's own merged read; that behavior is covered by
+ * the real-git integration tests in git-identity.worktree.test.ts and
+ * git-identity.includes.test.ts.
*/
import { describe, expect, test } from 'vitest';
@@ -14,11 +19,9 @@ import {
// ─── Helpers ──────────────────────────────────────────────────────────────────
-/** Build a mock GitConfigReader that returns pre-defined values per (key, scope). */
-function mockReader(
- values: Partial<Record<string, Partial<Record<'worktree' | 'local' | 'global', string | null>>>>,
-): GitConfigReader {
- return (_dir, key, scope) => values[key]?.[scope] ?? null;
+/** Build a mock GitConfigReader that returns pre-defined effective values per key. */
+function mockReader(values: Partial<Record<string, string | null>>): GitConfigReader {
+ return (_dir, key) => values[key] ?? null;
}
/** A minimal TokenStore stub. */
@@ -32,78 +35,39 @@ function makeTokenStore(entry: { login: string; name?: string; email?: string }
// ─── Chain order tests ────────────────────────────────────────────────────────
describe('resolveGitIdentity chain order', () => {
- test('Step 1 (worktree): per-worktree identity wins over local + global', async () => {
- const reader = mockReader({
- 'user.name': { worktree: 'WT Dev', local: 'Local Dev', global: 'Global Dev' },
- 'user.email': {
- worktree: '[email protected]',
- local: '[email protected]',
- global: '[email protected]',
- },
- });
- const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'WT Dev', email: '[email protected]' });
- });
-
- test('Step 1 partial: worktree name only — falls through to local pair', async () => {
- const reader = mockReader({
- 'user.name': { worktree: 'WT Dev', local: 'Local Dev', global: 'Global Dev' },
- 'user.email': { worktree: null, local: '[email protected]', global: '[email protected]' },
- });
- const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Local Dev', email: '[email protected]' });
- });
-
- test('Step 1 partial: worktree email only — falls through to local pair', async () => {
- const reader = mockReader({
- 'user.name': { worktree: null, local: 'Local Dev', global: 'Global Dev' },
- 'user.email': {
- worktree: '[email protected]',
- local: '[email protected]',
- global: '[email protected]',
- },
- });
- const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Local Dev', email: '[email protected]' });
- });
-
- test('Step 1 absent: empty worktree scope falls through to local (extension off / non-worktree)', async () => {
+ test('Step 1: returns the effective git config identity when name + email are both set', async () => {
const reader = mockReader({
- 'user.name': { local: 'Local Dev' },
- 'user.email': { local: '[email protected]' },
+ 'user.name': 'Config Dev',
+ 'user.email': '[email protected]',
});
const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Local Dev', email: '[email protected]' });
+ expect(result).toEqual({ name: 'Config Dev', email: '[email protected]' });
});
- test('Step 2: returns repo-local identity when both name + email are set locally', async () => {
- const reader = mockReader({
- 'user.name': { local: 'Local Dev', global: 'Global Dev' },
- 'user.email': { local: '[email protected]', global: '[email protected]' },
+ test('Step 1 partial: name only — falls through to token store', async () => {
+ const reader = mockReader({ 'user.name': 'Config Dev' });
+ const store = makeTokenStore({
+ login: 'octocat',
+ name: 'The Octocat',
+ email: '[email protected]',
});
- const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Local Dev', email: '[email protected]' });
+ const result = await resolveGitIdentity('/fake/repo', store, 'github.com', reader);
+ expect(result).toEqual({ name: 'The Octocat', email: '[email protected]' });
});
- test('Step 2 partial: local name only — falls through to global', async () => {
- const reader = mockReader({
- 'user.name': { local: 'Local Dev', global: 'Global Dev' },
- 'user.email': { local: null, global: '[email protected]' },
- });
+ test('Step 1 partial: email only — falls through to null when no token store', async () => {
+ const reader = mockReader({ 'user.email': '[email protected]' });
const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Global Dev', email: '[email protected]' });
+ expect(result).toBeNull();
});
- test('Step 3: returns global identity when local is empty', async () => {
- const reader = mockReader({
- 'user.name': { local: null, global: 'Global Dev' },
- 'user.email': { local: null, global: '[email protected]' },
- });
+ test('Step 1 partial: name only — falls through to null when no token store', async () => {
+ const reader = mockReader({ 'user.name': 'Config Dev' });
const result = await resolveGitIdentity('/fake/repo', null, null, reader);
- expect(result).toEqual({ name: 'Global Dev', email: '[email protected]' });
+ expect(result).toBeNull();
});
- test('Step 4: uses tokenStore when both git configs are empty', async () => {
+ test('Step 2: uses tokenStore when git config is empty', async () => {
const reader = mockReader({});
const store = makeTokenStore({
login: 'octocat',
@@ -114,14 +78,14 @@ describe('resolveGitIdentity chain order', () => {
expect(result).toEqual({ name: 'The Octocat', email: '[email protected]' });
});
- test('Step 4: uses login as name fallback when entry.name is absent', async () => {
+ test('Step 2: uses login as name fallback when entry.name is absent', async () => {
const reader = mockReader({});
const store = makeTokenStore({ login: 'octocat', email: '[email protected]' });
const result = await resolveGitIdentity('/fake/repo', store, 'github.com', reader);
expect(result).toEqual({ name: 'octocat', email: '[email protected]' });
});
- test('Step 4: synthesizes noreply email when entry.email is absent', async () => {
+ test('Step 2: synthesizes noreply email when entry.email is absent', async () => {
const reader = mockReader({});
const store = makeTokenStore({ login: 'octocat' }); // no email
const result = await resolveGitIdentity('/fake/repo', store, 'github.com', reader);
@@ -131,41 +95,41 @@ describe('resolveGitIdentity chain order', () => {
});
});
- test('Step 5: returns null when all sources are empty', async () => {
+ test('Step 3: returns null when all sources are empty', async () => {
const reader = mockReader({});
const result = await resolveGitIdentity('/fake/repo', null, null, reader);
expect(result).toBeNull();
});
- test('Step 5: returns null when tokenStore.get returns null', async () => {
+ test('Step 3: returns null when tokenStore.get returns null', async () => {
const reader = mockReader({});
const store = makeTokenStore(null);
const result = await resolveGitIdentity('/fake/repo', store, 'github.com', reader);
expect(result).toBeNull();
});
- test('Step 4 skipped: no host provided — falls through to null', async () => {
+ test('Step 2 skipped: no host provided — falls through to null', async () => {
const reader = mockReader({});
const store = makeTokenStore({
login: 'octocat',
name: 'The Octocat',
});
- // host not provided — step 3 skipped even with a valid store
+ // host not provided — token step skipped even with a valid store
const result = await resolveGitIdentity('/fake/repo', store, null, reader);
expect(result).toBeNull();
});
- test('Step 4 skipped: no tokenStore — falls through to null', async () => {
+ test('Step 2 skipped: no tokenStore — falls through to null', async () => {
const reader = mockReader({});
const result = await resolveGitIdentity('/fake/repo', null, 'github.com', reader);
expect(result).toBeNull();
});
- test('Local (Step 2) wins over global + tokenStore when set', async () => {
+ test('Git config (Step 1) wins over tokenStore when set', async () => {
const reader = mockReader({
- 'user.name': { local: 'Repo Dev', global: 'Global Dev' },
- 'user.email': { local: '[email protected]', global: '[email protected]' },
+ 'user.name': 'Repo Dev',
+ 'user.email': '[email protected]',
});
const store = makeTokenStore({
login: 'octocat',
diff --git a/packages/server/src/git-identity.ts b/packages/server/src/git-identity.ts
index c544d146c..05f0a4ce4 100644
--- a/packages/server/src/git-identity.ts
+++ b/packages/server/src/git-identity.ts
@@ -2,15 +2,18 @@
* Git identity resolution chain.
*
* Resolves git user.name + user.email for auto-save commits via:
- * 1. Per-worktree git config (.git/worktrees/<name>/config.worktree)
- * 2. Repo-local / common git config (.git/config)
- * 3. Global git config (~/.gitconfig)
- * 4. Stored token entry (login + name/email from OAuth profile)
- * 5. null — caller must prompt
+ * 1. Effective (merged) git config — the identity git itself would commit
+ * with, read from the project dir
+ * 2. Stored token entry (login + name/email from OAuth profile)
+ * 3. null — caller must prompt
*
- * Step 1 only fires when `extensions.worktreeConfig` is enabled; otherwise
- * `git config --worktree` errors out in linked worktrees, which the reader
- * surfaces as null and the chain falls through.
+ * Step 1 reads the *merged* config (`git config --get <key>`, no scope flag)
+ * rather than probing `--worktree` / `--local` / `--global` in turn. The merged
+ * read is what git resolves for a commit: it honors the full scope precedence
+ * (system < global < local < worktree) AND — critically — resolves `include` /
+ * `includeIf` directives (e.g. `gitdir:` or `hasconfig:remote.*.url:` identity
+ * switching). Scope-limited reads only see values written literally in that one
+ * file, so an identity supplied through an included config is invisible to them.
*
* Uses spawnSync('git', ['config', …]) instead of simple-git so this module
* has no runtime dependency on simple-git (avoids broken symlink in test env).
@@ -38,33 +41,28 @@ export interface GitIdentityTokenStore {
/**
* Injectable git-config reader (real or mock in tests).
*
+ * Reads the *effective* (merged) config from `projectDir`, i.e. what git
+ * resolves for a commit after applying scope precedence and all `include` /
+ * `includeIf` directives — not a single scope's raw file.
+ *
* @param projectDir Absolute path to the git root.
* @param key Git config key (e.g. 'user.name').
- * @param scope 'worktree' reads .git/worktrees/<name>/config.worktree (only
- * populated when `extensions.worktreeConfig` is enabled);
- * 'local' reads .git/config; 'global' reads ~/.gitconfig.
* @returns The trimmed value, or null if not set / not found.
*/
-export type GitConfigReader = (
- projectDir: string,
- key: string,
- scope: 'worktree' | 'local' | 'global',
-) => string | null;
+export type GitConfigReader = (projectDir: string, key: string) => string | null;
// ─── Default reader (production) ─────────────────────────────────────────────
/**
- * Production config reader — spawns `git config --worktree|--local|--global <key>`.
- * Returns null on any error (non-zero exit, missing key, spawn failure). `--worktree`
- * in a linked worktree without `extensions.worktreeConfig` exits 128 (fatal); that
- * still maps to null, which is the correct fall-through for the chain.
+ * Production config reader — spawns `git config --get <key>` (no scope flag) so
+ * git returns the effective merged value: full scope precedence plus resolved
+ * `include` / `includeIf` directives. Returns null on any error (non-zero exit,
+ * missing key, spawn failure).
*/
-const defaultGitConfigReader: GitConfigReader = (projectDir, key, scope) => {
- const scopeFlag =
- scope === 'worktree' ? '--worktree' : scope === 'local' ? '--local' : '--global';
+const defaultGitConfigReader: GitConfigReader = (projectDir, key) => {
const result = spawnSync(
'git',
- ['config', scopeFlag, key],
+ ['config', '--get', key],
withHiddenWindowsConsole({
cwd: projectDir,
encoding: 'utf-8',
@@ -158,11 +156,10 @@ function ensureWorktreeConfigExtension(projectDir: string): void {
* Resolve git identity for auto-save commits.
*
* Chain (stops at first complete name+email pair):
- * 1. per-worktree config (`--worktree`; only meaningful when extension on)
- * 2. repo-local / common config (`--local`)
- * 3. global config (`--global`)
- * 4. TokenStore entry (login as name fallback; entry.name preferred)
- * 5. null (caller must prompt)
+ * 1. effective merged git config (`git config --get`; resolves scope
+ * precedence + `include` / `includeIf` directives)
+ * 2. TokenStore entry (login as name fallback; entry.name preferred)
+ * 3. null (caller must prompt)
*
* @param projectDir Absolute path to the git root.
* @param tokenStore Optional credential store for fallback identity.
@@ -175,30 +172,18 @@ export async function resolveGitIdentity(
host?: string | null,
_reader: GitConfigReader = defaultGitConfigReader,
): Promise<GitIdentity | null> {
- // ── Step 1: per-worktree config ───────────────────────────────────────────
- // Harmless on main worktrees / non-git dirs: reader maps any non-zero exit
- // (incl. "extensions.worktreeConfig not enabled" fatal) to null.
- const worktreeName = _reader(projectDir, 'user.name', 'worktree');
- const worktreeEmail = _reader(projectDir, 'user.email', 'worktree');
- if (worktreeName && worktreeEmail) {
- return { name: worktreeName, email: worktreeEmail };
- }
-
- // ── Step 2: repo-local / common config ─────────────────────────────────────
- const localName = _reader(projectDir, 'user.name', 'local');
- const localEmail = _reader(projectDir, 'user.email', 'local');
- if (localName && localEmail) {
- return { name: localName, email: localEmail };
- }
-
- // ── Step 3: global config ──────────────────────────────────────────────────
- const globalName = _reader(projectDir, 'user.name', 'global');
- const globalEmail = _reader(projectDir, 'user.email', 'global');
- if (globalName && globalEmail) {
- return { name: globalName, email: globalEmail };
+ // ── Step 1: effective merged git config ────────────────────────────────────
+ // The identity git itself commits with. The merged read resolves the full
+ // scope precedence (system < global < local < worktree) and — unlike a
+ // scope-limited read — any identity supplied through an `include` /
+ // `includeIf` directive (gitdir / hasconfig identity switching).
+ const configName = _reader(projectDir, 'user.name');
+ const configEmail = _reader(projectDir, 'user.email');
+ if (configName && configEmail) {
+ return { name: configName, email: configEmail };
}
- // ── Step 4: stored token entry ─────────────────────────────────────────────
+ // ── Step 2: stored token entry ─────────────────────────────────────────────
if (tokenStore && host) {
const entry = await tokenStore.get(host);
if (entry) {
@@ -211,7 +196,7 @@ export async function resolveGitIdentity(
}
}
- // ── Step 5: unresolved ────────────────────────────────────────────────────
+ // ── Step 3: unresolved ─────────────────────────────────────────────────────
return null;
}
diff --git a/packages/server/src/git-identity.worktree.test.ts b/packages/server/src/git-identity.worktree.test.ts
index c23225bf9..c99c280c1 100644
--- a/packages/server/src/git-identity.worktree.test.ts
+++ b/packages/server/src/git-identity.worktree.test.ts
@@ -100,10 +100,9 @@ describe('writeGitIdentity in a linked worktree', () => {
test('resolveGitIdentity in a linked worktree without the extension enabled falls through to the main identity', async () => {
// Pre-condition: a fresh worktree where no `writeGitIdentity` call has
- // flipped `extensions.worktreeConfig`. `git config --worktree` exits 128
- // (fatal) on this state; `defaultGitConfigReader` must map that to null
- // so the chain falls through to `--local`. This is the correctness
- // guarantee that lets us prepend the worktree-tier read unconditionally.
+ // flipped `extensions.worktreeConfig`. Without the extension git's merged
+ // read (`git config --get`) ignores `config.worktree` entirely, so the
+ // shared identity from the common `.git/config` must win here.
const resolved = await resolveGitIdentity(env.linked);
expect(resolved).toEqual({ name: 'Main Test', email: '[email protected]' });
});
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 560f1d916..cb1700245 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -1474,7 +1474,7 @@ export class SyncEngine {
const message = this.buildCommitMessage(changedContentRelPaths);
// ── 9. Author identity (resolveGitIdentity chain, soft fallback) ─
- // Chain: repo-local → global → (OAuth profile, when tokenStore plumbed) →
+ // Chain: effective merged git config → (OAuth profile, when tokenStore plumbed) →
// hard-coded "OpenKnowledge" default. We never error on unresolved
// identity — attribution silently degrades to the default and the UI
// surfaces a non-blocking nudge via `status.identityUnresolved`.