Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Consolidate Git repository and branch handling (#2755)
Dimitri POSTOLOV5d44ede3974b
diff --git a/.changeset/robust-git-repository-inspection.md b/.changeset/robust-git-repository-inspection.mdnew file mode 100644index 000000000..6e6efc778--- /dev/null+++ b/.changeset/robust-git-repository-inspection.md@@ -0,0 +1,13 @@+---+"@inkeep/open-knowledge": patch+---++Local Git-backed workflows now inspect repositories consistently across the `ok` CLI, Desktop, and the collaboration server. This removes several places where each surface parsed `.git`, `HEAD`, refs, and remotes differently.++- Linked worktrees now read `HEAD` from the worktree-specific Git directory while reading remotes, refs, and clone-wide excludes from the shared common Git directory. Folder validation, share-receive matching, branch display, and `ok config-sharing` therefore work the same in a linked worktree as in a primary checkout.+- Shadow-repository setup now recognizes the nearest enclosing repository when an OpenKnowledge project is rooted in a subdirectory, while still refusing to promote a repository rooted at the user's home directory.+- Branch and remote inspection now handles loose and packed refs, symbolic refs, SHA-1 and SHA-256 object IDs, relative or absolute worktree pointers, and quoted or commented remote configuration through one shared implementation.+- Missing refs, malformed metadata, stale worktree pointers, inaccessible Git files, and unsafe ref paths are classified separately so sync and branch-watching code can fail safely instead of treating every read problem as a missing branch.+- Branch-switch conflict checks now wait for both Git probes to finish before returning an invalid-target error, preventing a leftover child process from racing repository cleanup.++No configuration or migration is required.diff --git a/packages/cli/src/github/folder-validator.test.ts b/packages/cli/src/github/folder-validator.test.tsindex b28ecf458..a6dee0b6a 100644--- a/packages/cli/src/github/folder-validator.test.ts+++ b/packages/cli/src/github/folder-validator.test.ts@@ -1,7 +1,7 @@-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { resolve } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import { validateLocalFolderForShare } from './folder-validator.ts';describe('validateLocalFolderForShare', () => {@@ -116,6 +116,18 @@ describe('validateLocalFolderForShare', () => {expect(result).toEqual({ kind: 'no-origin' });});+ test('returns no-origin when the origin URL is an empty quoted value', async () => {+ const folder = resolve(tmpDir, 'repo');+ mkdirSync(folder);+ seedRepo(folder, '""');++ const result = await validateLocalFolderForShare(folder, {+ owner: 'inkeep',+ repo: 'open-knowledge',+ });+ expect(result).toEqual({ kind: 'no-origin' });+ });+test('worktree case: .git is a file pointing at the primary checkout gitdir', async () => {const primaryDir = resolve(tmpDir, 'primary');const primaryGitDir = resolve(primaryDir, '.git');diff --git a/packages/cli/src/github/folder-validator.ts b/packages/cli/src/github/folder-validator.tsindex 5bf6fb3da..d2ad50b40 100644--- a/packages/cli/src/github/folder-validator.ts+++ b/packages/cli/src/github/folder-validator.ts@@ -22,8 +22,9 @@*/import { statSync } from 'node:fs';-import { readFile, realpath } from 'node:fs/promises';+import { realpath } from 'node:fs/promises';import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';import { parseGitUrl } from './url.ts';/** Outcome of `validateLocalFolderForShare`. Discriminated by `kind`. */@@ -78,7 +79,6 @@ export async function validateLocalFolderForShare(return { kind: 'not-git' };}- let gitDir: string;if (dotGitStat.isDirectory()) {let realDotGit: string;try {@@ -92,39 +92,22 @@ export async function validateLocalFolderForShare(if (!isDescendantOrEqual(realDotGit, realFolder)) {return { kind: 'symlink-escape' };}- gitDir = realDotGit;- } else if (dotGitStat.isFile()) {- let pointerContents: string;- try {- pointerContents = await readFile(dotGit, 'utf-8');- } catch {- return { kind: 'not-git' };- }- const match = /^gitdir:\s*(.+)$/m.exec(pointerContents.trim());- if (!match) return { kind: 'not-git' };- const target = match[1].trim();- const absoluteTarget = isAbsolute(target) ? target : resolve(realFolder, target);- try {- gitDir = await realpath(absoluteTarget);- } catch {- return { kind: 'not-git' };- }- } else {+ } else if (!dotGitStat.isFile()) {return { kind: 'not-git' };}- // 3. Read git config + locate `[remote "origin"]` URL. For a linked worktree- // `gitDir` has no `config` of its own — it lives in the shared common dir,- // reached via the gitdir's `commondir` pointer.- const configPath = join(await resolveCommonDir(gitDir), 'config');- let configContents: string;- try {- configContents = await readFile(configPath, 'utf-8');- } catch {+ // 3. Repository mechanics are shared; this adapter retains the folder-picker's+ // stricter realpath admission and user-facing failure vocabulary.+ const inspected = inspectGitRepository(realFolder);+ if (inspected.kind !== 'repository') {return { kind: 'not-git' };}- const originUrl = extractOriginUrl(configContents);- if (originUrl === null) return { kind: 'no-origin' };+ const origin = inspected.repository.readRemoteUrl('origin');+ if (origin.kind === 'unreadable') return { kind: 'not-git' };+ if (origin.kind === 'absent') {+ return origin.reason === 'config-missing' ? { kind: 'not-git' } : { kind: 'no-origin' };+ }+ const originUrl = origin.url;// 4. Parse origin via the shared `parseGitUrl`. Anything we can't parse// OR that points off-github lands as `non-github` — same downstream@@ -149,28 +132,6 @@ export async function validateLocalFolderForShare(};}-/**- * Resolve the shared common git dir, where `config` lives. A linked worktree's- * gitdir carries a `commondir` file pointing at the main `.git` (relative to- * the gitdir, occasionally absolute); a primary checkout has no `commondir`- * and is its own common dir. Returns `gitDir` unchanged on any read failure.- */-async function resolveCommonDir(gitDir: string): Promise<string> {- let contents: string;- try {- contents = (await readFile(join(gitDir, 'commondir'), 'utf-8')).trim();- } catch {- return gitDir;- }- if (contents.length === 0) return gitDir;- const resolved = isAbsolute(contents) ? contents : resolve(gitDir, contents);- try {- return await realpath(resolved);- } catch {- return resolved;- }-}-/*** `relative(parent, child)` returns `''` for equal paths, a `..`-prefixed* string when `child` sits outside `parent`, and a non-`..` relative path@@ -182,53 +143,3 @@ function isDescendantOrEqual(child: string, parent: string): boolean {const rel = relative(parent, child);return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel);}--/**- * Strip git-config inline comments (`;` or `#`) and surrounding whitespace.- * Both characters are valid comment markers in git's `*.config` grammar; the- * shape of `[remote "origin"]` URLs (no semicolons, no hashes) means the- * naive split is safe here.- */-function stripCommentAndTrim(line: string): string {- const hashIdx = line.indexOf('#');- const semiIdx = line.indexOf(';');- let cutAt = -1;- if (hashIdx >= 0 && semiIdx >= 0) cutAt = Math.min(hashIdx, semiIdx);- else if (hashIdx >= 0) cutAt = hashIdx;- else if (semiIdx >= 0) cutAt = semiIdx;- return (cutAt === -1 ? line : line.slice(0, cutAt)).trim();-}--/**- * Extract the first `url = ...` value from the `[remote "origin"]` section- * of a git config file. Returns null when the section is absent or has no- * `url` line. Tolerates indented values, comments, quoted values, and CRLF- * line endings.- */-export function extractOriginUrl(configContents: string): string | null {- let inOriginSection = false;- for (const rawLine of configContents.split(/\r?\n/)) {- const line = stripCommentAndTrim(rawLine);- if (line.length === 0) continue;- if (line.startsWith('[')) {- inOriginSection = /^\[\s*remote\s+["']origin["']\s*\]$/.test(line);- continue;- }- if (!inOriginSection) continue;- const m = /^url\s*=\s*(.+)$/.exec(line);- if (!m) continue;- return unquote(m[1]);- }- return null;-}--function unquote(value: string): string {- const trimmed = value.trim();- if (- (trimmed.startsWith('"') && trimmed.endsWith('"')) ||- (trimmed.startsWith("'") && trimmed.endsWith("'"))- ) {- return trimmed.slice(1, -1);- }- return trimmed;-}diff --git a/packages/cli/src/sharing/git-exclude.test.ts b/packages/cli/src/sharing/git-exclude.test.tsindex 0ce5665b9..be7d2cc10 100644--- a/packages/cli/src/sharing/git-exclude.test.ts+++ b/packages/cli/src/sharing/git-exclude.test.ts@@ -1,9 +1,9 @@-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';import { execFileSync } from 'node:child_process';-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { OK_DIR } from '@inkeep/open-knowledge-core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {addOkPathsToGitExclude,formatTrackedRemediation,@@ -345,10 +345,9 @@ describe('addOkPathsToGitExclude', () => {}});- it('writes to the linked-worktree admin dir, not <projectRoot>/.git/info/exclude', () => {- // Reproduce the worktree-blind bug: in a linked- // worktree, <projectRoot>/.git is a regular file containing- // `gitdir: <abs-path>`, and `info/exclude` lives under that admin dir.+ it('writes to the linked worktree common dir, not <projectRoot>/.git/info/exclude', () => {+ // In a linked worktree, <projectRoot>/.git points at a per-worktree admin+ // dir, while the clone-level `info/exclude` lives in the shared common dir.const mainRepo = uniqueDir('main-repo');const linkedWorktree = uniqueDir('linked-worktree');initGitRepo(mainRepo);@@ -451,6 +450,22 @@ build/expect(result.kind).toBe('updated');});+ it.skipIf(process.platform === 'win32')(+ 'reports an unreadable linked-worktree common-dir pointer as inaccessible',+ () => {+ rmSync(join(dir, '.git'), { recursive: true });+ const gitDir = join(dir, '.git-state');+ mkdirSync(gitDir);+ writeFileSync(join(dir, '.git'), `gitdir: ${gitDir}\n`);+ symlinkSync('commondir', join(gitDir, 'commondir'));++ expect(removeOkPathsFromGitExclude(dir, ['.ok/'])).toEqual({+ kind: 'no-exclude',+ reason: 'inaccessible',+ });+ },+ );+it('reports the actually-removed artifact paths in `removed` (not the full candidate list)', () => {writeExclude(dir, '# header\n.ok/\n.mcp.json\nbuild/\n');const result = removeOkPathsFromGitExclude(dir, ['.ok/', '.mcp.json', '.cursor/mcp.json']);diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.tsindex 089b45087..2180b2325 100644--- a/packages/cli/src/sharing/git-exclude.ts+++ b/packages/cli/src/sharing/git-exclude.ts@@ -6,11 +6,8 @@* `.git/info/exclude`. No parallel registry; `readSharingMode` derives the* mode by checking whether any OK artifact appears in the exclude file.*- * Worktree-aware: every read/write resolves the gitdir via- * `resolveGitDirDetailed` from `@inkeep/open-knowledge-core` so linked- * worktrees (where `<projectRoot>/.git` is a pointer file) write to the- * correct `<repo>/.git/worktrees/<name>/info/exclude`, not a non-existent- * `<projectRoot>/.git/info/exclude`.+ * Worktree-aware: every read/write resolves the repository common dir so+ * linked worktrees and main worktrees share the clone-level `info/exclude`.** Every transition to local-only (init `--local-only`, `ok config-sharing unshare`,* desktop create radio, desktop settings panel) flows through@@ -23,7 +20,7 @@import { execFileSync } from 'node:child_process';import { existsSync, readFileSync, writeFileSync } from 'node:fs';-import { isAbsolute, join, relative, resolve, sep } from 'node:path';+import { join, relative, resolve, sep } from 'node:path';import {EDITOR_PROJECT_SKILL_ROOT,type EditorId,@@ -33,10 +30,7 @@ import {RESERVED_PROJECT_SKILL_NAME,SKILL_CONTENT_ROOT,} from '@inkeep/open-knowledge-core';-// `resolveGitDirDetailed` is in the `node:fs`-importing subpath of core —-// the barrel deliberately omits it to keep the main entry browser-safe-// (see `packages/core/src/index.ts`).-import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { discoverGitRepository } from '@inkeep/open-knowledge-core/git-repository';import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { ALL_EDITOR_IDS, EDITOR_TARGETS } from '../commands/editors.ts';@@ -554,29 +548,23 @@ type ResolveExcludePathResult =| { kind: 'no-exclude'; result: Extract<ExcludeWriteResult, { kind: 'no-exclude' }> };/**- * Resolve `<gitdir>/info/exclude` via the shared resolver. Maps each- * non-directory / non-linked outcome to a typed `no-exclude` sub-reason so- * callers don't need to handle `MalformedGitPointerError` /- * `GitDirAccessError` themselves.+ * Resolve `<common-dir>/info/exclude` via shared repository inspection. Maps+ * each unusable outcome to a typed `no-exclude` sub-reason for callers.** Order of precedence — gitdir resolution first, then `info/` existence.* Skipping the `info/` check when the gitdir is resolvable but lacks an* `info/` dir would silently no-op rather than telling callers why.*/function resolveExcludePath(projectRoot: string): ResolveExcludePathResult {- const detail = resolveGitDirDetailed(projectRoot);- switch (detail.kind) {- case 'directory':- case 'linked': {+ const inspected = discoverGitRepository(projectRoot);+ switch (inspected.kind) {+ case 'repository': {// `.git/info/exclude` is a per-clone artifact, not a per-worktree one.- // In a linked worktree, `<projectRoot>/.git` points at the per-worktree- // admin dir (`<repo>/.git/worktrees/<name>/`), but the exclude file- // lives in the COMMON dir (the shared `<repo>/.git/`). Git stores the- // path to the common dir in a `commondir` file inside the admin dir,- // relative to that admin dir. For main worktrees, no `commondir` file- // exists and the gitdir IS the common dir.- const commonDir = resolveCommonDir(detail.path);- const info = join(commonDir, 'info');+ const commonDir = inspected.repository.readCommonDir();+ if (commonDir.kind === 'unreadable') {+ return { kind: 'no-exclude', result: { kind: 'no-exclude', reason: 'inaccessible' } };+ }+ const info = join(commonDir.path, 'info');if (!existsSync(info)) {return { kind: 'no-exclude', result: { kind: 'no-exclude', reason: 'no-info-dir' } };}@@ -594,31 +582,6 @@ function resolveExcludePath(projectRoot: string): ResolveExcludePathResult {}}-/**- * Resolve the common-dir of a gitdir. In a linked worktree, the per-worktree- * admin dir contains a `commondir` text file whose body is a path- * (typically relative) to the shared `.git` directory. In a main worktree,- * no `commondir` file exists and the gitdir IS the common dir.- *- * The `commondir` body is git's documented mechanism for resolving shared- * per-clone artifacts (refs/, objects/, info/, hooks/) from a linked- * worktree's gitdir; we use the same mechanism rather than re-running- * `git rev-parse --git-common-dir` so the resolution stays in-process and- * doesn't depend on a working `git` binary at sharing-mode evaluation time.- */-function resolveCommonDir(gitDir: string): string {- const commondirFile = join(gitDir, 'commondir');- if (!existsSync(commondirFile)) return gitDir;- let body: string;- try {- body = readFileSync(commondirFile, 'utf-8').trim();- } catch {- return gitDir;- }- if (body.length === 0) return gitDir;- return isAbsolute(body) ? body : resolve(gitDir, body);-}-/*** Recognized variants for a single artifact path. Mirrors gitignore's* tolerance for the four common spellings: with/without trailing slash,diff --git a/packages/core/package.json b/packages/core/package.jsonindex fcdc8bb54..bfe010072 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -15,6 +15,11 @@"types": "./src/shadow-repo-layout.ts","default": "./dist/shadow-repo-layout.mjs"},+ "./git-repository": {+ "development": "./src/git-repository.ts",+ "types": "./src/git-repository.ts",+ "default": "./dist/git-repository.mjs"+ },"./server": {"development": "./src/server.ts","types": "./src/server.ts",diff --git a/packages/core/src/git-repository.test.ts b/packages/core/src/git-repository.test.tsnew file mode 100644index 000000000..269543ada--- /dev/null+++ b/packages/core/src/git-repository.test.ts@@ -0,0 +1,352 @@+import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import { discoverGitRepository, inspectGitRepository } from './git-repository.ts';++interface RemoteUrlFixture {+ readonly name: string;+ readonly config: string;+ readonly expected: string | null;+}++const REMOTE_URL_FIXTURES: readonly RemoteUrlFixture[] = [+ {+ name: 'canonical HTTPS origin',+ config: '[remote "origin"]\n\turl = https://github.com/owner/repo.git\n',+ expected: 'https://github.com/owner/repo.git',+ },+ {+ name: 'SSH origin',+ config: '[remote "origin"]\n\turl = [email protected]:owner/repo.git\n',+ expected: '[email protected]:owner/repo.git',+ },+ {+ name: 'whitespace inside the section header',+ config: '[ remote "origin" ]\n\turl = https://github.com/owner/repo.git\n',+ expected: 'https://github.com/owner/repo.git',+ },+ {+ name: 'single-quoted section header',+ config: "[remote 'origin']\n\turl = https://github.com/owner/repo.git\n",+ expected: 'https://github.com/owner/repo.git',+ },+ {+ name: 'inline semicolon comment',+ config: '[remote "origin"]\n\turl = https://github.com/o/r.git ; legacy origin\n',+ expected: 'https://github.com/o/r.git',+ },+ {+ name: 'inline hash comment',+ config: '[remote "origin"]\n\turl = https://github.com/o/r.git # primary\n',+ expected: 'https://github.com/o/r.git',+ },+ {+ name: 'CRLF line endings',+ config: '[remote "origin"]\r\n\turl = https://github.com/o/r.git\r\n',+ expected: 'https://github.com/o/r.git',+ },+ {+ name: 'quoted URL value',+ config: '[remote "origin"]\n\turl = "https://github.com/o/r.git"\n',+ expected: 'https://github.com/o/r.git',+ },+ {+ name: 'absent origin section',+ config:+ '[core]\n\tbare = false\n[remote "upstream"]\n\turl = https://github.com/forky/spoon.git\n',+ expected: null,+ },+ { name: 'empty config', config: '', expected: null },+ {+ name: 'origin section without a URL',+ config: '[remote "origin"]\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n',+ expected: null,+ },+ {+ name: 'empty URL before a configured URL',+ config: '[remote "origin"]\n\turl =\n\turl = https://github.com/owner/repository.git\n',+ expected: 'https://github.com/owner/repository.git',+ },+];++describe('inspectGitRepository', () => {+ const temporaryDirectories: string[] = [];++ afterEach(() => {+ for (const path of temporaryDirectories.splice(0)) {+ rmSync(path, { recursive: true, force: true });+ }+ });++ async function makeTemporaryDirectory(): Promise<string> {+ const path = await mkdtemp(join(tmpdir(), 'ok-git-repository-'));+ temporaryDirectories.push(path);+ return path;+ }++ test('reads worktree HEAD from the git dir and origin from the common dir', async () => {+ const root = await makeTemporaryDirectory();++ const projectRoot = join(root, 'worktree');+ const commonDir = join(root, 'main', '.git');+ const gitDir = join(commonDir, 'worktrees', 'feature');+ mkdirSync(projectRoot, { recursive: true });+ mkdirSync(gitDir, { recursive: true });+ writeFileSync(join(projectRoot, '.git'), `gitdir: ${gitDir}\n`);+ writeFileSync(join(gitDir, 'commondir'), '../..\n');+ writeFileSync(join(gitDir, 'HEAD'), 'ref: refs/heads/feature/deep-inspection\n');+ writeFileSync(+ join(commonDir, 'config'),+ '[remote "origin"]\n\turl = [email protected]:inkeep/open-knowledge.git\n',+ );++ const result = inspectGitRepository(projectRoot);++ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.kind).toBe('linked');+ expect(result.repository.gitDir).toBe(gitDir);+ expect(result.repository.readCommonDir()).toEqual({+ kind: 'resolved',+ path: resolve(gitDir, '../..'),+ });+ expect(result.repository.readHead()).toEqual({+ kind: 'branch',+ branch: 'feature/deep-inspection',+ ref: 'refs/heads/feature/deep-inspection',+ });+ expect(result.repository.readRemoteUrl('origin')).toEqual({+ kind: 'configured',+ url: '[email protected]:inkeep/open-knowledge.git',+ });+ });++ test.runIf(process.platform !== 'win32')(+ 'reports an unreadable common-dir pointer without falling back to the worktree git dir',+ async () => {+ const root = await makeTemporaryDirectory();+ const projectRoot = join(root, 'worktree');+ const gitDir = join(root, 'worktree-state');+ mkdirSync(projectRoot);+ mkdirSync(gitDir);+ writeFileSync(join(projectRoot, '.git'), `gitdir: ${gitDir}\n`);+ symlinkSync('commondir', join(gitDir, 'commondir'));++ const result = inspectGitRepository(projectRoot);++ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.readCommonDir().kind).toBe('unreadable');+ expect(result.repository.readRemoteUrl('origin').kind).toBe('unreadable');+ expect(result.repository.readRef('refs/heads/main').kind).toBe('unreadable');++ const commonDir = join(root, 'common');+ rmSync(join(gitDir, 'commondir'));+ mkdirSync(commonDir);+ writeFileSync(join(gitDir, 'commondir'), `${commonDir}\n`);+ expect(result.repository.readCommonDir()).toEqual({ kind: 'resolved', path: commonDir });+ },+ );++ test('keeps exact-root inspection distinct from enclosing-working-tree discovery', async () => {+ const root = await makeTemporaryDirectory();++ const projectRoot = join(root, 'repo', 'docs', 'handbook');+ const repositoryRoot = join(root, 'repo');+ mkdirSync(join(repositoryRoot, '.git'), { recursive: true });+ mkdirSync(projectRoot, { recursive: true });++ expect(inspectGitRepository(projectRoot)).toEqual({ kind: 'absent' });++ const discovered = discoverGitRepository(projectRoot);+ expect(discovered.kind).toBe('repository');+ if (discovered.kind !== 'repository') return;+ expect(discovered.repository.projectRoot).toBe(repositoryRoot);+ expect(discovered.repository.projectSubPath).toBe(join('docs', 'handbook'));+ });++ test('rejects a linked-worktree pointer whose target no longer exists', async () => {+ const root = await makeTemporaryDirectory();+ writeFileSync(join(root, '.git'), 'gitdir: ../missing-worktree-state\n');++ const result = inspectGitRepository(root);++ expect(result.kind).toBe('malformed-pointer');+ if (result.kind !== 'malformed-pointer') return;+ expect(result.gitPath).toBe(join(root, '.git'));+ expect(result.target).toBe(resolve(root, '../missing-worktree-state'));+ });++ test('rejects a worktree pointer with extra lines around the gitdir', async () => {+ const root = await makeTemporaryDirectory();+ const gitDir = join(root, 'worktree-state');+ mkdirSync(gitDir);+ for (const contents of [`unexpected\ngitdir: ${gitDir}\n`, `gitdir:\n${gitDir}\n`]) {+ writeFileSync(join(root, '.git'), contents);+ expect(inspectGitRepository(root)).toMatchObject({+ kind: 'malformed-pointer',+ gitPath: join(root, '.git'),+ target: '',+ });+ }+ });++ test('does not discover a repository rooted at the home directory', async () => {+ const root = await makeTemporaryDirectory();+ mkdirSync(join(root, '.git'));++ const previousHome = process.env.HOME;+ process.env.HOME = root;+ try {+ expect(inspectGitRepository(root).kind).toBe('repository');+ expect(discoverGitRepository(root)).toEqual({ kind: 'absent' });+ } finally {+ if (previousHome === undefined) delete process.env.HOME;+ else process.env.HOME = previousHome;+ }+ });++ test.runIf(process.platform !== 'win32')(+ 'stops at an inaccessible ancestor instead of selecting a repository above it',+ async () => {+ const root = await makeTemporaryDirectory();+ const repositoryRoot = join(root, 'repository');+ const inaccessibleAncestor = join(repositoryRoot, 'inaccessible');+ const projectRoot = join(inaccessibleAncestor, 'project');+ mkdirSync(join(repositoryRoot, '.git'), { recursive: true });+ mkdirSync(projectRoot, { recursive: true });+ symlinkSync('.git', join(inaccessibleAncestor, '.git'));++ const result = discoverGitRepository(projectRoot);++ expect(result.kind).toBe('inaccessible');+ if (result.kind !== 'inaccessible') return;+ expect(result.gitPath).toBe(join(inaccessibleAncestor, '.git'));+ },+ );++ test('accepts a SHA-256 object id for detached HEAD', async () => {+ const root = await makeTemporaryDirectory();+ const gitDir = join(root, '.git');+ const oid = '0123456789abcdef'.repeat(4);+ mkdirSync(gitDir);+ writeFileSync(join(gitDir, 'HEAD'), `${oid}\n`);++ const result = inspectGitRepository(root);++ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.readHead()).toEqual({ kind: 'detached', oid });+ });++ test('resolves packed refs from the common directory', async () => {+ const root = await makeTemporaryDirectory();++ const gitDir = join(root, '.git');+ mkdirSync(gitDir, { recursive: true });+ writeFileSync(+ join(gitDir, 'packed-refs'),+ '0123456789abcdef0123456789abcdef01234567 refs/remotes/origin/feature/deep-inspection\n',+ );++ const result = inspectGitRepository(root);+ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.readRef('refs/remotes/origin/feature/deep-inspection')).toEqual({+ kind: 'present',+ storage: 'packed',+ value: {+ kind: 'oid',+ oid: '0123456789abcdef0123456789abcdef01234567',+ },+ });+ });++ test('reads the oid stored in a loose ref', async () => {+ const root = await makeTemporaryDirectory();++ const gitDir = join(root, '.git');+ const refDir = join(gitDir, 'refs', 'heads');+ mkdirSync(refDir, { recursive: true });+ writeFileSync(join(refDir, 'main'), 'fedcba9876543210fedcba9876543210fedcba98\n');++ const result = inspectGitRepository(root);+ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.readRef('refs/heads/main')).toEqual({+ kind: 'present',+ storage: 'loose',+ value: {+ kind: 'oid',+ oid: 'fedcba9876543210fedcba9876543210fedcba98',+ },+ });+ });++ test('reports malformed loose and packed object ids', async () => {+ const root = await makeTemporaryDirectory();++ const gitDir = join(root, '.git');+ const refDir = join(gitDir, 'refs', 'heads');+ mkdirSync(refDir, { recursive: true });+ writeFileSync(join(refDir, 'main'), 'not-an-object-id\n');++ const result = inspectGitRepository(root);+ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ expect(result.repository.readRef('refs/heads/main')).toEqual({+ kind: 'malformed',+ raw: 'not-an-object-id',+ });++ rmSync(join(refDir, 'main'));+ writeFileSync(join(gitDir, 'packed-refs'), 'not-an-object-id refs/heads/main\n');+ expect(result.repository.readRef('refs/heads/main')).toEqual({+ kind: 'malformed',+ raw: 'not-an-object-id refs/heads/main',+ });+ });++ test('ref inspection rejects unsafe paths before filesystem access', async () => {+ const root = await makeTemporaryDirectory();+ mkdirSync(join(root, '.git'), { recursive: true });++ const result = inspectGitRepository(root);+ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;+ for (const ref of [+ 'refs/remotes/origin/../../config',+ 'heads/main',+ 'refs/heads/ma\0in',+ 'refs/heads/ma\\in',+ 'refs/heads//main',+ 'refs/heads/main/',+ ]) {+ expect(result.repository.readRef(ref)).toEqual({ kind: 'invalid' });+ }+ });++ describe('readRemoteUrl', () => {+ for (const fixture of REMOTE_URL_FIXTURES) {+ test(fixture.name, async () => {+ const root = await makeTemporaryDirectory();+ const gitDir = join(root, '.git');+ mkdirSync(gitDir, { recursive: true });+ writeFileSync(join(gitDir, 'config'), fixture.config);++ const result = inspectGitRepository(root);+ expect(result.kind).toBe('repository');+ if (result.kind !== 'repository') return;++ const remote = result.repository.readRemoteUrl('origin');+ expect(remote).toEqual(+ fixture.expected === null+ ? { kind: 'absent', reason: 'remote-missing' }+ : { kind: 'configured', url: fixture.expected },+ );+ });+ }+ });+});diff --git a/packages/core/src/git-repository.ts b/packages/core/src/git-repository.tsnew file mode 100644index 000000000..19dd2d231--- /dev/null+++ b/packages/core/src/git-repository.ts@@ -0,0 +1,323 @@+import { readFileSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';++const MAX_DISCOVERY_DEPTH = 64;++/**+ * Node-only, read-only Git facts shared by CLI, Desktop, and server adapters.+ * HEAD belongs to the per-worktree git dir; config and refs belong to the+ * common dir. Path admission, forge classification, and user-facing failure+ * policy deliberately stay with each caller.+ */++export type GitHeadResult =+ | { readonly kind: 'branch'; readonly branch: string; readonly ref: string }+ | { readonly kind: 'detached'; readonly oid: string }+ | { readonly kind: 'absent' }+ | { readonly kind: 'malformed'; readonly raw: string }+ | { readonly kind: 'unreadable'; readonly cause: unknown };++export type GitRemoteUrlResult =+ | { readonly kind: 'configured'; readonly url: string }+ | { readonly kind: 'absent'; readonly reason: 'config-missing' | 'remote-missing' }+ | { readonly kind: 'unreadable'; readonly cause: unknown };++export type GitCommonDirResult =+ | { readonly kind: 'resolved'; readonly path: string }+ | { readonly kind: 'unreadable'; readonly cause: unknown };++export type GitRefValue =+ | { readonly kind: 'oid'; readonly oid: string }+ | { readonly kind: 'symbolic'; readonly target: string };++export type GitRefResult =+ | {+ readonly kind: 'present';+ readonly storage: 'loose' | 'packed';+ readonly value: GitRefValue;+ }+ | { readonly kind: 'absent' }+ | { readonly kind: 'invalid' }+ | { readonly kind: 'malformed'; readonly raw: string }+ | { readonly kind: 'unreadable'; readonly cause: unknown };++export interface GitRepository {+ readonly kind: 'directory' | 'linked';+ readonly projectRoot: string;+ readonly projectSubPath: string;+ readonly gitPath: string;+ readonly gitDir: string;+ readCommonDir(): GitCommonDirResult;+ readHead(): GitHeadResult;+ readRemoteUrl(remote: string): GitRemoteUrlResult;+ readRef(ref: string): GitRefResult;+}++export type GitRepositoryResult =+ | { readonly kind: 'repository'; readonly repository: GitRepository }+ | { readonly kind: 'absent' }+ | {+ readonly kind: 'malformed-pointer';+ readonly gitPath: string;+ readonly target: string;+ readonly cause?: unknown;+ }+ | { readonly kind: 'inaccessible'; readonly gitPath: string; readonly cause: unknown };++class LocalGitRepository implements GitRepository {+ readonly kind: 'directory' | 'linked';+ readonly projectRoot: string;+ readonly projectSubPath: string;+ readonly gitPath: string;+ readonly gitDir: string;++ private cachedCommonDir: string | undefined;++ constructor(+ kind: 'directory' | 'linked',+ projectRoot: string,+ projectSubPath: string,+ gitPath: string,+ gitDir: string,+ ) {+ this.kind = kind;+ this.projectRoot = projectRoot;+ this.projectSubPath = projectSubPath;+ this.gitPath = gitPath;+ this.gitDir = gitDir;+ }++ readCommonDir(): GitCommonDirResult {+ if (this.cachedCommonDir !== undefined) {+ return { kind: 'resolved', path: this.cachedCommonDir };+ }++ let commonDir = this.gitDir;+ try {+ const pointer = readFileSync(join(this.gitDir, 'commondir'), 'utf-8').trim();+ if (pointer.length > 0) {+ commonDir = isAbsolute(pointer) ? pointer : resolve(this.gitDir, pointer);+ }+ } catch (cause) {+ if (!isMissing(cause)) return { kind: 'unreadable', cause };+ // Main worktrees and gitfile-based repositories without a separate+ // common dir use their git dir directly.+ }+ this.cachedCommonDir = commonDir;+ return { kind: 'resolved', path: commonDir };+ }++ readHead(): GitHeadResult {+ let raw: string;+ try {+ raw = readFileSync(join(this.gitDir, 'HEAD'), 'utf-8').trim();+ } catch (cause) {+ if (isMissing(cause)) return { kind: 'absent' };+ return { kind: 'unreadable', cause };+ }++ const symbolic = /^ref:[ \t]*(refs\/heads\/(.+))$/.exec(raw);+ if (symbolic?.[2]) {+ return { kind: 'branch', branch: symbolic[2], ref: symbolic[1] };+ }+ if (isObjectId(raw)) return { kind: 'detached', oid: raw };+ return { kind: 'malformed', raw };+ }++ readRemoteUrl(remote: string): GitRemoteUrlResult {+ const commonDir = this.readCommonDir();+ if (commonDir.kind === 'unreadable') return commonDir;++ let config: string;+ try {+ config = readFileSync(join(commonDir.path, 'config'), 'utf-8');+ } catch (cause) {+ if (isMissing(cause)) return { kind: 'absent', reason: 'config-missing' };+ return { kind: 'unreadable', cause };+ }++ const url = extractRemoteUrl(config, remote);+ return url === null+ ? { kind: 'absent', reason: 'remote-missing' }+ : { kind: 'configured', url };+ }++ readRef(ref: string): GitRefResult {+ if (!isSafeRef(ref)) return { kind: 'invalid' };++ const commonDir = this.readCommonDir();+ if (commonDir.kind === 'unreadable') return commonDir;++ const loosePath = resolve(commonDir.path, ref);+ const relativePath = relative(commonDir.path, loosePath);+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) return { kind: 'invalid' };+ try {+ const raw = readFileSync(loosePath, 'utf-8').trim();+ const value = parseRefValue(raw);+ return value === null+ ? { kind: 'malformed', raw }+ : { kind: 'present', storage: 'loose', value };+ } catch (cause) {+ if (!isMissing(cause)) return { kind: 'unreadable', cause };+ }++ let packedRefs: string;+ try {+ packedRefs = readFileSync(join(commonDir.path, 'packed-refs'), 'utf-8');+ } catch (cause) {+ if (isMissing(cause)) return { kind: 'absent' };+ return { kind: 'unreadable', cause };+ }+ for (const rawLine of packedRefs.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (line.length === 0 || line.startsWith('#') || line.startsWith('^')) continue;+ const fields = line.split(/\s+/);+ if (fields.length === 2 && fields[1] === ref) {+ if (!isObjectId(fields[0])) return { kind: 'malformed', raw: line };+ return {+ kind: 'present',+ storage: 'packed',+ value: { kind: 'oid', oid: fields[0] },+ };+ }+ }+ return { kind: 'absent' };+ }+}++export function inspectGitRepository(projectRoot: string): GitRepositoryResult {+ const root = resolve(projectRoot);+ return inspectRepositoryAt(root, '');+}++/** Find the nearest enclosing repository without treating `~/.git` as a project. */+export function discoverGitRepository(projectRoot: string): GitRepositoryResult {+ const start = resolve(projectRoot);+ const home = resolve(homedir());+ if (start === home) return { kind: 'absent' };++ const direct = inspectRepositoryAt(start, '');+ if (direct.kind !== 'absent') return direct;++ let cursor = start;+ for (let depth = 0; depth < MAX_DISCOVERY_DEPTH; depth++) {+ if (cursor === home) return { kind: 'absent' };+ const parent = dirname(cursor);+ if (parent === cursor || parent === home) return { kind: 'absent' };++ const result = inspectRepositoryAt(parent, relative(parent, start));+ if (result.kind !== 'absent') return result;+ cursor = parent;+ }+ return { kind: 'absent' };+}++function inspectRepositoryAt(root: string, projectSubPath: string): GitRepositoryResult {+ const gitPath = join(root, '.git');+ let stat: ReturnType<typeof statSync>;+ try {+ stat = statSync(gitPath);+ } catch (cause) {+ if (isMissing(cause)) return { kind: 'absent' };+ return { kind: 'inaccessible', gitPath, cause };+ }++ if (stat.isDirectory()) {+ return {+ kind: 'repository',+ repository: new LocalGitRepository('directory', root, projectSubPath, gitPath, gitPath),+ };+ }+ if (!stat.isFile()) return { kind: 'absent' };++ let pointer: string;+ try {+ pointer = readFileSync(gitPath, 'utf-8').trim();+ } catch (cause) {+ return { kind: 'malformed-pointer', gitPath, target: '', cause };+ }+ const match = /^gitdir:[ \t]*(.+)$/.exec(pointer);+ if (!match) return { kind: 'malformed-pointer', gitPath, target: '' };++ const rawTarget = match[1].trim();+ const target = isAbsolute(rawTarget) ? rawTarget : resolve(root, rawTarget);+ try {+ if (!statSync(target).isDirectory()) {+ return { kind: 'malformed-pointer', gitPath, target };+ }+ } catch (cause) {+ return { kind: 'malformed-pointer', gitPath, target, cause };+ }++ return {+ kind: 'repository',+ repository: new LocalGitRepository('linked', root, projectSubPath, gitPath, target),+ };+}++function extractRemoteUrl(config: string, remote: string): string | null {+ let inRemote = false;+ for (const rawLine of config.split(/\r?\n/)) {+ const line = stripComment(rawLine);+ if (line.length === 0) continue;+ if (line.startsWith('[')) {+ const section = /^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(line);+ inRemote = section?.[1] === remote;+ continue;+ }+ if (!inRemote) continue;+ const match = /^url\s*=\s*(.*)$/.exec(line);+ if (!match) continue;+ const value = unquote(match[1]);+ if (value.length > 0) return value;+ }+ return null;+}++function stripComment(line: string): string {+ const commentIndex = line.search(/[;#]/);+ return (commentIndex === -1 ? line : line.slice(0, commentIndex)).trim();+}++function unquote(value: string): string {+ const trimmed = value.trim();+ if (+ (trimmed.startsWith('"') && trimmed.endsWith('"')) ||+ (trimmed.startsWith("'") && trimmed.endsWith("'"))+ ) {+ return trimmed.slice(1, -1);+ }+ return trimmed;+}++function isMissing(cause: unknown): boolean {+ const code = (cause as NodeJS.ErrnoException | undefined)?.code;+ // ENOENT means the artifact is absent. ENOTDIR means a path component cannot+ // contain it; both classifications let loose-ref reads fall through to packed refs.+ return code === 'ENOENT' || code === 'ENOTDIR';+}++function isSafeRef(ref: string): boolean {+ return (+ ref.startsWith('refs/') &&+ !ref.includes('\0') &&+ !ref.includes('\\') &&+ !ref.includes('..') &&+ !ref.includes('//') &&+ !ref.endsWith('/')+ );+}++function parseRefValue(raw: string): GitRefValue | null {+ if (raw.length === 0) return null;+ const symbolic = /^ref:[ \t]*(refs\/.+)$/.exec(raw);+ if (symbolic) {+ return isSafeRef(symbolic[1]) ? { kind: 'symbolic', target: symbolic[1] } : null;+ }+ return isObjectId(raw) ? { kind: 'oid', oid: raw } : null;+}++function isObjectId(value: string): boolean {+ return /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value);+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 596973fe2..22e7d8ee2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1077,8 +1077,8 @@ export {// Shadow-repo layout helpers are NOT re-exported here — they import `node:fs`// and would contaminate core's browser-compatibility contract. Import via the-// subpath: `import { parseWriterId } from '@inkeep/open-knowledge-core/shadow-repo-layout'`.-// CLI read path and server write path are the only consumers.+// Node-only Git helpers are exposed through `./git-repository` and+// `./shadow-repo-layout` subpaths so the browser-safe barrel stays clean.// Bridge — observer/CRDT-bridge shared utilities (precedent #14)export {diff --git a/packages/core/src/shadow-repo-layout.ts b/packages/core/src/shadow-repo-layout.tsindex dbb65ebfe..2095e4b51 100644--- a/packages/core/src/shadow-repo-layout.ts+++ b/packages/core/src/shadow-repo-layout.ts@@ -36,10 +36,10 @@* This file uses only `node:fs` (no other server/runtime deps) so it is safe* to include from any workspace package.*/-import { existsSync, readFileSync, statSync } from 'node:fs';-import { homedir } from 'node:os';-import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';+import { existsSync } from 'node:fs';+import { resolve, sep } from 'node:path';import { fnv1aDigest } from './bridge/hash-util.ts';+import { discoverGitRepository } from './git-repository.ts';/*** Writer-ID taxonomy (precedent #25). Classified system writers are non-attributable@@ -112,10 +112,9 @@ const WRITER_ID_RE =/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;/**- * Classification of `<projectRoot>/.git`. Centralizes the single- * `statSync` + pointer-parse so `resolveGitDir` (lossy: `string | null`),- * `resolveShadowDir` (typed: throws on each unusable kind), and boot-time- * worktree-attribute computation consume the same source of truth.+ * Compatibility view of shared repository discovery for shadow-repo callers.+ * `resolveGitDir` consumes it lossily, while `resolveShadowDir` preserves the+ * distinct recovery paths below.** Three failure modes — distinct because their recoveries differ:* - `'absent'` — `.git` is not on disk (`ENOENT`). Recovery: run@@ -159,141 +158,29 @@ export type ResolvedGitDir =| { kind: 'malformed-pointer'; gitPath: string; target: string; cause?: unknown }| { kind: 'inaccessible'; gitPath: string; cause: unknown };-/**- * Classify a `.git` path (file or directory) without walking up the- * filesystem. The caller supplies `workTreeRoot` — the directory CONTAINING- * the `.git` entry — so we can resolve relative `gitdir:` pointers correctly- * even when the `.git` lives at an ancestor of `projectRoot`.- */-function classifyGitEntry(- gitPath: string,- workTreeRoot: string,- projectRoot: string,-): ResolvedGitDir {- let stat: ReturnType<typeof statSync>;- try {- stat = statSync(gitPath);- } catch (err) {- const code = (err as NodeJS.ErrnoException).code;- if (code === 'ENOENT' || code === 'ENOTDIR') return { kind: 'absent' };- return { kind: 'inaccessible', gitPath, cause: err };- }- const projectSubPath = computeProjectSubPath(workTreeRoot, projectRoot);- if (stat.isDirectory()) return { kind: 'directory', path: gitPath, projectSubPath };- if (stat.isFile()) {- let content: string;- try {- content = readFileSync(gitPath, 'utf-8').trim();- } catch (err) {- return { kind: 'malformed-pointer', gitPath, target: '', cause: err };- }- const match = content.match(/^gitdir:\s*(.+)$/);- if (!match) return { kind: 'malformed-pointer', gitPath, target: '' };- // Relative pointers resolve against the directory that contains the- // `.git` file (the worktree root), not against `projectRoot` — these- // differ when `.git` lives at an ancestor of `projectRoot`.- return {- kind: 'linked',- path: resolve(workTreeRoot, match[1]),- gitPath,- projectSubPath,- };- }- // socket / device / etc. — treat as absent for the consumers' purposes.- return { kind: 'absent' };-}--/**- * Return the path component from `workTreeRoot` down to `projectRoot`. Empty- * string when they coincide. Non-empty result is guaranteed to NOT begin with- * `..` (the walk-up only ever discovers `.git` at an ancestor, so projectRoot- * is always a descendant). Defensive `..`-check guards against future callers- * that pass arbitrary paths.- */-function computeProjectSubPath(workTreeRoot: string, projectRoot: string): string {- const rel = relative(workTreeRoot, projectRoot);- if (rel === '' || rel === '.') return '';- if (rel.startsWith('..') || isAbsolute(rel)) return '';- return rel;-}--/**- * Walk up from `startDir` looking for a `.git` (directory or pointer file) at- * any ancestor. Stops at `homedir()` (matching `folder-admission.ts`'s- * "don't promote at-or-above home" policy — `~/.git` would be a hostile- * carve-out we want to refuse) and at the filesystem root. Returns the path- * to the discovered `.git` entry and the ancestor directory containing it,- * or `null` if none found within the bound.- */-function findAncestorGitEntry(startDir: string): { gitPath: string; workTreeRoot: string } | null {- const home = homedir();- let cursor = resolve(startDir);- // Hard cap so a hostile or pathological tree (cyclic symlinks via realpath- // edge cases, very deep mount stacks) can't pin a server boot in a tight- // statSync loop. 64 is well beyond any realistic monorepo depth.- const MAX_DEPTH = 64;- for (let i = 0; i < MAX_DEPTH; i++) {- if (cursor === home) return null;- const parent = dirname(cursor);- if (parent === cursor) return null; // reached filesystem root- if (parent === home) return null; // refuse ~/.git (at-or-above-home policy)- const candidate = resolve(parent, '.git');- try {- const stat = statSync(candidate);- if (stat.isDirectory() || stat.isFile()) {- return { gitPath: candidate, workTreeRoot: parent };- }- } catch (err) {- // ENOENT / EACCES / etc. — keep walking; if a parent is unreadable we- // can't tell whether `.git` exists there, but surfacing that as an- // error would block boot for every container that mounts a parent of- // its project read-only without execute. Prefer the safe fallthrough- // — at worst the caller hits the legacy `<projectRoot>/.git/ok` path.- const code = (err as NodeJS.ErrnoException).code;- if (code !== 'ENOENT' && code !== 'ENOTDIR') {- console.warn(- `[shadow-repo-layout] Cannot stat ${candidate} (${code ?? 'unknown'}); skipping ancestor`,- );- }- }- cursor = parent;- }- return null;-}-export function resolveGitDirDetailed(projectRoot: string): ResolvedGitDir {- const projectRootAbs = resolve(projectRoot);- const direct = classifyGitEntry(resolve(projectRootAbs, '.git'), projectRootAbs, projectRootAbs);- // Direct hit at projectRoot — return as-is. Covers main-worktree, linked-- // worktree, AND the pre-existing-shell-`.git/` case (where a prior subfolder- // boot under the bug left an empty `.git/` directory containing only `ok/`).- // The shell-`.git/` case continues to be repaired by `ensureProjectGit` and- // its shadow continues to live where it was created. We never walk up if- // `.git` is present at projectRoot.- if (direct.kind !== 'absent') return direct;+ const result = discoverGitRepository(projectRoot);+ if (result.kind !== 'repository') return result;- // No `.git` at projectRoot — projectRoot may be a subfolder of an existing- // work tree. Walk up. If we find an ancestor `.git`, host the shadow inside- // its gitdir (with a per-subfolder namespace; see `resolveShadowDir`) rather- // than creating a nested `<projectRoot>/.git/` shell. This eliminates the- // bug class where `initShadowRepo`'s mkdir materialised a shell `.git/`- // inside a subfolder of an existing repo, which on next boot tricked- // `ensureProjectGit`'s shell-repair path into running `git init` and- // fragmenting the user's history into a nested repo.- const ancestor = findAncestorGitEntry(projectRootAbs);- if (ancestor === null) {- // ENOENT / ENOTDIR were the original errors at projectRoot — fall- // through to the legacy `<projectRoot>/.git/ok` path. Callers handle the- // no-`.git` case via `ensureProjectGit` upstream.- return { kind: 'absent' };+ const { repository } = result;+ if (repository.kind === 'directory') {+ return {+ kind: 'directory',+ path: repository.gitDir,+ projectSubPath: repository.projectSubPath,+ };}- return classifyGitEntry(ancestor.gitPath, ancestor.workTreeRoot, projectRootAbs);+ return {+ kind: 'linked',+ path: repository.gitDir,+ gitPath: repository.gitPath,+ projectSubPath: repository.projectSubPath,+ };}/**- * Resolve the actual `.git` directory for a project root — handles both the- * standard `.git`-as-directory case and the linked-worktree case where- * `<projectRoot>/.git` is a regular file containing `gitdir: <abs>`.+ * Resolve the actual `.git` directory for the nearest enclosing repository,+ * including linked worktrees whose `.git` is a `gitdir:` pointer file.** Returns the resolved absolute path on success, or `null` when `.git` is* absent OR when the pointer file is unreadable / malformed. Callers that@@ -344,7 +231,7 @@ export function resolveShadowDir(projectRoot: string): string {return resolve(result.path, shadowSubdirName(result.projectSubPath));case 'linked':if (!existsSync(result.path)) {- // Pointer parsed but target dir is gone (stale `git worktree` admin).+ // Discovery verified the pointer target, but it can disappear before use.throw new MalformedGitPointerError(result.gitPath, result.path);}return resolve(result.path, shadowSubdirName(result.projectSubPath));diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex 4fd53ddf1..f5eb5eb99 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -3,6 +3,7 @@ import { defineConfig } from 'tsdown';export default defineConfig({entry: {index: 'src/index.ts',+ 'git-repository': 'src/git-repository.ts','shadow-repo-layout': 'src/shadow-repo-layout.ts',server: 'src/server.ts',keepalive: 'src/keepalive/keepalive.ts',diff --git a/packages/desktop/src/main/folder-admission.test.ts b/packages/desktop/src/main/folder-admission.test.tsindex 53e48908c..97a552f8a 100644--- a/packages/desktop/src/main/folder-admission.test.ts+++ b/packages/desktop/src/main/folder-admission.test.ts@@ -1,9 +1,9 @@-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { execFile } from 'node:child_process';import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { promisify } from 'node:util';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import {type DiscoverProjectOptions,type DiscoverProjectResult,@@ -407,8 +407,10 @@ describe('discoverProject — linked-worktree carveout scoping', () => {// instead of promoting to the git root.const worktree = resolve(fakeHome, 'wt');const sub = resolve(worktree, 'public/open-knowledge');+ const gitDir = resolve(fakeHome, 'main/.git/worktrees/wt');mkdirSync(sub, { recursive: true });- writeFileSync(resolve(worktree, '.git'), 'gitdir: /main/.git/worktrees/wt\n');+ mkdirSync(gitDir, { recursive: true });+ writeFileSync(resolve(worktree, '.git'), `gitdir: ${gitDir}\n`);const result = await discoverProject(sub, {homeDir: fakeHome,@@ -428,9 +430,11 @@ describe('discoverProject — linked-worktree carveout scoping', () => {// subfolder fix must not weaken this.const parent = resolve(fakeHome, 'parent');const worktree = resolve(parent, 'wt');+ const gitDir = resolve(fakeHome, 'main/.git/worktrees/wt');mkdirSync(worktree, { recursive: true });+ mkdirSync(gitDir, { recursive: true });writeOkConfig(parent);- writeFileSync(resolve(worktree, '.git'), 'gitdir: /main/.git/worktrees/wt\n');+ writeFileSync(resolve(worktree, '.git'), `gitdir: ${gitDir}\n`);const result = await discoverProject(worktree, {homeDir: fakeHome,diff --git a/packages/desktop/src/main/git-remote.test.ts b/packages/desktop/src/main/git-remote.test.tsindex f3900a0b3..3974cfb29 100644--- a/packages/desktop/src/main/git-remote.test.ts+++ b/packages/desktop/src/main/git-remote.test.ts@@ -1,77 +1,8 @@-import { describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, relative } from 'node:path';-import { extractOriginUrl, readCanonicalGitHubRemoteUrl } from './git-remote.ts';--describe('extractOriginUrl', () => {- test('returns the url from a canonical [remote "origin"] block', () => {- const config = [- '[core]',- '\trepositoryformatversion = 0',- '[remote "origin"]',- '\turl = https://github.com/inkeep/open-knowledge.git',- '\tfetch = +refs/heads/*:refs/remotes/origin/*',- '',- ].join('\n');- expect(extractOriginUrl(config)).toBe('https://github.com/inkeep/open-knowledge.git');- });-- test("returns the SSH form unchanged (canonicalization is the caller's job)", () => {- const config = ['[remote "origin"]', '\turl = [email protected]:inkeep/open-knowledge.git'].join(- '\n',- );- expect(extractOriginUrl(config)).toBe('[email protected]:inkeep/open-knowledge.git');- });-- test('ignores [remote "upstream"] when origin is also present', () => {- const config = [- '[remote "upstream"]',- '\turl = https://github.com/some/fork.git',- '[remote "origin"]',- '\turl = https://github.com/inkeep/open-knowledge.git',- ].join('\n');- expect(extractOriginUrl(config)).toBe('https://github.com/inkeep/open-knowledge.git');- });-- test('returns null when no origin section is present', () => {- const config = ['[core]', '\trepositoryformatversion = 0'].join('\n');- expect(extractOriginUrl(config)).toBeNull();- });-- test('returns null when origin section has no url key', () => {- const config = ['[remote "origin"]', '\tfetch = +refs/heads/*:refs/remotes/origin/*'].join(- '\n',- );- expect(extractOriginUrl(config)).toBeNull();- });-- test('tolerates CRLF line endings', () => {- const config = [- '[core]\r',- '\trepositoryformatversion = 0\r',- '[remote "origin"]\r',- '\turl = https://github.com/inkeep/open-knowledge.git\r',- ].join('\n');- expect(extractOriginUrl(config)).toBe('https://github.com/inkeep/open-knowledge.git');- });-- test('handles quoted url values', () => {- const config = [- '[remote "origin"]',- '\turl = "https://github.com/inkeep/open-knowledge.git"',- ].join('\n');- expect(extractOriginUrl(config)).toBe('https://github.com/inkeep/open-knowledge.git');- });-- test('strips trailing semicolon and hash comments', () => {- const config = [- '[remote "origin"]',- '\turl = https://github.com/inkeep/open-knowledge.git ; was example/old.git',- ].join('\n');- expect(extractOriginUrl(config)).toBe('https://github.com/inkeep/open-knowledge.git');- });-});+import { describe, expect, test } from 'vitest';+import { readCanonicalGitHubRemoteUrl } from './git-remote.ts';describe('readCanonicalGitHubRemoteUrl (filesystem round-trip)', () => {function withTempProject(setup: (projectDir: string) => void): string | null {@@ -132,6 +63,21 @@ describe('readCanonicalGitHubRemoteUrl (filesystem round-trip)', () => {expect(result).toBeNull();});+ test('skips empty entries before the configured origin URL', () => {+ const result = withTempProject((projectDir) => {+ mkdirSync(join(projectDir, '.git'));+ writeFileSync(+ join(projectDir, '.git', 'config'),+ [+ '[remote "origin"]',+ '\turl =',+ '\turl = https://github.com/inkeep/open-knowledge.git',+ ].join('\n'),+ );+ });+ expect(result).toBe('https://github.com/inkeep/open-knowledge.git');+ });+test('does not throw when .git/config is unreadable', () => {// Project dir exists, .git/config does not — read fails silently.const result = withTempProject((projectDir) => {diff --git a/packages/desktop/src/main/git-remote.ts b/packages/desktop/src/main/git-remote.tsindex 12b74552d..b5f8b710f 100644--- a/packages/desktop/src/main/git-remote.ts+++ b/packages/desktop/src/main/git-remote.ts@@ -3,22 +3,13 @@* `RecentProject.gitRemoteUrl` on every project open so the share-receive* lookup finds previously opened projects by `{owner, repo}`.*- * Why not shell out to `git config --get`: backfill runs synchronously on- * the boot hot path. A spawn round-trip is ~30-50ms on macOS; the file- * read is sub-millisecond. The downside — we ignore git's includeIf /- * conditional includes — is acceptable here because `[remote "origin"]`- * lives in the repo's common `.git/config`, never in a parent include. For a- * linked worktree that common config is reached via the gitdir's `commondir`- * pointer — the worktree's own gitdir holds HEAD but no `config`.- ** Why re-emit canonical form: senders may have cloned via SSH* (`[email protected]:owner/repo.git`) while receivers via HTTPS — both must* normalize to one URL for the string compare to hit.*/-import { readFileSync, statSync } from 'node:fs';-import { isAbsolute, join, resolve } from 'node:path';import { parseGitUrl } from '@inkeep/open-knowledge';+import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';/*** Best-effort: returns the canonical GitHub remote URL for the project@@ -27,127 +18,16 @@ import { parseGitUrl } from '@inkeep/open-knowledge';* I/O or parse error returns `null` so callers can fall through silently* (the field stays undefined, the user pays a one-time cost on first* share-receive for this project).- *- * Handles git worktrees: when `.git` is a regular file containing- * `gitdir: <path>`, follow the pointer to the worktree gitdir and then to- * the shared common dir (via the gitdir's `commondir` pointer), where the- * origin config actually lives — a linked worktree's gitdir holds HEAD but- * no `config`. Without this, every worktree user silently misses the- * share-receive lookup. Mirrors the worktree handling in `git-context.ts`- * (`resolveGitDir` + `resolveCommonDir`).*/export function readCanonicalGitHubRemoteUrl(projectPath: string): string | null {- const gitDir = resolveGitDir(projectPath);- if (gitDir === null) return null;- let raw: string;- try {- // Origin config lives in the shared common dir, which differs from the- // resolved git dir for a linked worktree (whose gitdir has no `config`).- raw = readFileSync(join(resolveCommonDir(gitDir), 'config'), 'utf-8');- } catch {- return null;- }- const originUrl = extractOriginUrl(raw);- if (originUrl === null) return null;- const parsed = parseGitUrl(originUrl);+ const inspection = inspectGitRepository(projectPath);+ if (inspection.kind !== 'repository') return null;++ const origin = inspection.repository.readRemoteUrl('origin');+ if (origin.kind !== 'configured') return null;++ const parsed = parseGitUrl(origin.url);if (parsed === null) return null;if (parsed.hostname !== 'github.com') return null;return `https://github.com/${parsed.owner}/${parsed.name}.git`;}--/**- * Resolve `<projectPath>/.git` to the gitdir holding the actual `config`- * file. For a primary checkout `.git` is itself the dir; for a worktree- * `.git` is a file whose contents are `gitdir: <path>` (absolute or- * relative-to-projectPath). Returns `null` on any I/O or parse error.- */-function resolveGitDir(projectPath: string): string | null {- const dotGit = join(projectPath, '.git');- let stat: ReturnType<typeof statSync>;- try {- stat = statSync(dotGit);- } catch {- return null;- }- if (stat.isDirectory()) return dotGit;- if (!stat.isFile()) return null;- let pointer: string;- try {- pointer = readFileSync(dotGit, 'utf-8');- } catch {- return null;- }- const match = /^gitdir:\s*(.+)$/m.exec(pointer.trim());- if (!match) return null;- const target = match[1].trim();- return isAbsolute(target) ? target : resolve(projectPath, target);-}--/**- * Resolve the shared common git dir, where `config` lives. A linked worktree's- * gitdir holds a `commondir` file pointing at the main `.git` (relative to the- * gitdir, occasionally absolute); a primary checkout has no `commondir` and is- * its own common dir. Returns `gitDir` unchanged on any read/parse failure.- */-function resolveCommonDir(gitDir: string): string {- const pointer = join(gitDir, 'commondir');- let contents: string;- try {- contents = readFileSync(pointer, 'utf-8').trim();- } catch {- return gitDir;- }- if (contents.length === 0) return gitDir;- return isAbsolute(contents) ? contents : resolve(gitDir, contents);-}--/**- * Parse `[remote "origin"] url = ...` out of a git-config INI blob.- * Tolerates indented values, comments, quoted values, and CRLF line- * endings. Returns the first matching `url` line in the `[remote- * "origin"]` section, or `null` if absent.- *- * Exported for testing — production callers go through- * `readCanonicalGitHubRemoteUrl`. Aligned with the sibling parsers in- * `packages/server/src/share/git-context.ts` and- * `packages/cli/src/github/folder-validator.ts` — a cross-package parser- * parity contract.- */-export function extractOriginUrl(configBlob: string): string | null {- let inOriginSection = false;- for (const rawLine of configBlob.split(/\r?\n/)) {- const line = stripCommentAndTrim(rawLine);- if (line.length === 0) continue;- if (line.startsWith('[')) {- // Match `[remote "origin"]` with arbitrary internal whitespace and- // either single or double quotes (git accepts both).- inOriginSection = /^\[\s*remote\s+["']origin["']\s*\]$/.test(line);- continue;- }- if (!inOriginSection) continue;- const m = /^url\s*=\s*(.+)$/.exec(line);- if (!m) continue;- return unquote(m[1]);- }- return null;-}--function stripCommentAndTrim(line: string): string {- // git-config treats `;` and `#` as comment markers. Quoted segments- // are out of scope for the remote.origin case so a naive split is fine.- const indexes = [line.indexOf('#'), line.indexOf(';')].filter((i) => i >= 0);- if (indexes.length === 0) return line.trim();- const idx = Math.min(...indexes);- return line.slice(0, idx).trim();-}--function unquote(value: string): string {- const trimmed = value.trim();- if (- (trimmed.startsWith('"') && trimmed.endsWith('"')) ||- (trimmed.startsWith("'") && trimmed.endsWith("'"))- ) {- return trimmed.slice(1, -1);- }- return trimmed;-}diff --git a/packages/desktop/src/main/read-head-branch.test.ts b/packages/desktop/src/main/read-head-branch.test.tsindex ad72fd593..5a8599f7d 100644Binary files a/packages/desktop/src/main/read-head-branch.test.ts and b/packages/desktop/src/main/read-head-branch.test.ts differdiff --git a/packages/desktop/src/main/read-head-branch.ts b/packages/desktop/src/main/read-head-branch.tsindex 36162f287..223ed37aa 100644--- a/packages/desktop/src/main/read-head-branch.ts+++ b/packages/desktop/src/main/read-head-branch.ts@@ -9,14 +9,10 @@* through to the branch-switch dialog (branches differ); a graceful fail* must collapse to silent dispatch so a single broken clone never blocks* a share-receive.- *- * Parse semantics mirror `readGitHeadBranch` in- * `packages/server/src/share/git-context.ts`. Re-implemented here (rather- * than imported) because desktop main does not depend on server.*/-import { existsSync, readFileSync, statSync } from 'node:fs';-import { isAbsolute, join, resolve } from 'node:path';+import { isAbsolute, resolve } from 'node:path';+import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';/*** Outcome of reading `<projectPath>/.git/HEAD`.@@ -43,64 +39,6 @@ const FAILURE: HeadBranchInfo = {detached: false,};-/**- * Parse a `.git/HEAD` contents blob. Pure — separated so the regex semantics- * are unit-testable without filesystem fixtures.- *- * Accepted inputs:- * - `ref: refs/heads/<branch>\n?` → `{currentBranch, null, false}`- * Branch names may contain `/` (e.g. `feat/foo`); the regex captures- * everything after `refs/heads/`.- * - 40-char lowercase hex SHA → `{null, <short7>, true}`- *- * Anything else (empty, malformed, partial SHA, mixed-case) collapses to the- * graceful-fail sentinel.- */-export function parseGitHead(contents: string): HeadBranchInfo {- const trimmed = contents.trim();- if (trimmed.length === 0) return FAILURE;- const refMatch = /^ref:\s+refs\/heads\/(.+)$/.exec(trimmed);- if (refMatch) {- const branch = refMatch[1].trim();- if (branch.length === 0) return FAILURE;- return { currentBranch: branch, headSha: null, detached: false };- }- const shaMatch = /^([0-9a-f]{40})$/.exec(trimmed);- if (shaMatch) {- return { currentBranch: null, headSha: shaMatch[1].slice(0, 7), detached: true };- }- return FAILURE;-}--/**- * Resolve the absolute `.git` directory for a project. Handles both the- * common directory layout and worktrees (where `.git` is a file containing- * `gitdir: <path>`). Mirrors the helpers in `git-remote.ts` and- * `git-context.ts`. Returns `null` on any I/O or parse failure.- */-function resolveGitDir(projectPath: string): string | null {- const dotGit = join(projectPath, '.git');- let stat: ReturnType<typeof statSync>;- try {- stat = statSync(dotGit);- } catch {- return null;- }- if (stat.isDirectory()) return dotGit;- if (!stat.isFile()) return null;- let pointer: string;- try {- pointer = readFileSync(dotGit, 'utf-8');- } catch {- return null;- }- const match = /^gitdir:\s*(.+)$/m.exec(pointer.trim());- if (!match) return null;- const target = match[1].trim();- const resolved = isAbsolute(target) ? target : resolve(projectPath, target);- return existsSync(resolved) ? resolved : null;-}-/*** Reject paths that aren't safe to read from a fresh IPC payload:* non-absolute paths, paths with NUL bytes, or paths whose resolved form@@ -126,14 +64,15 @@ function isSafeProjectPath(projectPath: string): boolean {*/export function readHeadBranch(projectPath: string): HeadBranchInfo {if (!isSafeProjectPath(projectPath)) return FAILURE;- const gitDir = resolveGitDir(projectPath);- if (gitDir === null) return FAILURE;- const headPath = join(gitDir, 'HEAD');- let contents: string;- try {- contents = readFileSync(headPath, 'utf-8');- } catch {- return FAILURE;+ const inspection = inspectGitRepository(projectPath);+ if (inspection.kind !== 'repository') return FAILURE;++ const head = inspection.repository.readHead();+ if (head.kind === 'branch') {+ return { currentBranch: head.branch, headSha: null, detached: false };}- return parseGitHead(contents);+ if (head.kind === 'detached') {+ return { currentBranch: null, headSha: head.oid.slice(0, 7), detached: true };+ }+ return FAILURE;}diff --git a/packages/desktop/tests/main/git-config-parser-parity.test.ts b/packages/desktop/tests/main/git-config-parser-parity.test.tsdeleted file mode 100644index 15971e806..000000000--- a/packages/desktop/tests/main/git-config-parser-parity.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { describe, expect, test } from 'bun:test';-import { extractOriginUrl as extractFromCli } from '../../../cli/src/github/folder-validator';-import { extractOriginUrl as extractFromServer } from '../../../server/src/share/git-context';-import { extractOriginUrl as extractFromDesktop } from '../../src/main/git-remote';--/**- * Cross-package contract test for `[remote "origin"]` parsing.- *- * Three production sites duplicate this parser (server, desktop, CLI) to- * avoid a server↔CLI dependency cycle. A regex divergence here previously- * caused the server to reject configs with whitespace after the opening- * bracket while the other two accepted them. This sync guard ensures all- * three return identical output for a shared fixture set so a bug fix to- * one copy can't silently fail to propagate.- *- * If extracting to a shared core helper becomes feasible (no cycle, no- * extra public surface), this test can be deleted — the consolidated- * implementation will be its own contract.- */--interface Fixture {- readonly name: string;- readonly input: string;- readonly expected: string | null;-}--const FIXTURES: readonly Fixture[] = [- {- name: 'canonical HTTPS origin',- input: '[remote "origin"]\n\turl = https://github.com/owner/repo.git\n',- expected: 'https://github.com/owner/repo.git',- },- {- name: 'SSH origin',- input: '[remote "origin"]\n\turl = [email protected]:owner/repo.git\n',- expected: '[email protected]:owner/repo.git',- },- {- name: 'whitespace after opening bracket — `[ remote "origin"]`',- input: '[ remote "origin" ]\n\turl = https://github.com/owner/repo.git\n',- expected: 'https://github.com/owner/repo.git',- },- {- name: 'single-quoted section header',- input: "[remote 'origin']\n\turl = https://github.com/owner/repo.git\n",- expected: 'https://github.com/owner/repo.git',- },- {- name: 'inline comment after URL',- input: '[remote "origin"]\n\turl = https://github.com/o/r.git ; legacy origin\n',- expected: 'https://github.com/o/r.git',- },- {- name: 'CRLF line endings',- input: '[remote "origin"]\r\n\turl = https://github.com/o/r.git\r\n',- expected: 'https://github.com/o/r.git',- },- {- name: 'quoted URL value',- input: '[remote "origin"]\n\turl = "https://github.com/o/r.git"\n',- expected: 'https://github.com/o/r.git',- },- {- name: 'absent origin section',- input:- '[core]\n\tbare = false\n[remote "upstream"]\n\turl = https://github.com/forky/spoon.git\n',- expected: null,- },- {- name: 'empty blob',- input: '',- expected: null,- },- {- name: 'origin section with no url line',- input: '[remote "origin"]\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n',- expected: null,- },-];--describe('git-config `[remote "origin"]` parser parity', () => {- for (const fixture of FIXTURES) {- test(fixture.name, () => {- const desktopResult = extractFromDesktop(fixture.input);- const cliResult = extractFromCli(fixture.input);- const serverResult = extractFromServer(fixture.input);-- expect(desktopResult).toBe(fixture.expected);- expect(cliResult).toBe(fixture.expected);- expect(serverResult).toBe(fixture.expected);-- // Cross-implementation equality — if any pair diverges, fail loudly- // even when the expected fixture might already be the wrong value.- expect(desktopResult).toBe(cliResult);- expect(cliResult).toBe(serverResult);- });- }-});diff --git a/packages/server/src/git-dirty.ts b/packages/server/src/git-dirty.tsindex 7af7f9a6f..99a9709b1 100644--- a/packages/server/src/git-dirty.ts+++ b/packages/server/src/git-dirty.ts@@ -38,7 +38,7 @@ export async function dirtyFilesOverlapWith(): Promise<DirtyOverlapResult> {const { git } = createGitInstance(cwd);- const [dirtyList, changed] = await Promise.all([+ const [dirtyResult, changedResult] = await Promise.allSettled([listPorcelainPaths(git),// Two-dot diff — all files differing between HEAD and targetRef, in either// direction. Three-dot (`HEAD...targetRef`) resolves to merge-base..targetRef@@ -47,6 +47,14 @@ export async function dirtyFilesOverlapWith(listNames(git, ['diff', '--name-only', `HEAD..${targetRef}`]),]);+ // A missing target ref rejects the diff. Wait for the status process too so+ // callers can safely tear down or replace the repository after this returns.+ if (changedResult.status === 'rejected') throw changedResult.reason;+ if (dirtyResult.status === 'rejected') throw dirtyResult.reason;++ const dirtyList = dirtyResult.value;+ const changed = changedResult.value;+const dirty = new Set(dirtyList);if (dirty.size === 0) return { conflicts: false, files: [] };diff --git a/packages/server/src/head-watcher.test.ts b/packages/server/src/head-watcher.test.tsindex 83c6dbd2f..8900aa628 100644--- a/packages/server/src/head-watcher.test.ts+++ b/packages/server/src/head-watcher.test.ts@@ -1,11 +1,10 @@-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { execSync } from 'node:child_process';import { mkdirSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';-import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';-import { readBranchFromHead, startHeadWatcher, watchedGitFile } from './head-watcher';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { readProjectHeadState, startHeadWatcher, watchedGitFile } from './head-watcher';let tmpDir: string;@@ -17,74 +16,74 @@ afterEach(async () => {await rm(tmpDir, { recursive: true, force: true });});-describe('resolveGitDir', () => {- test('returns .git path when .git is a directory', () => {- const projectRoot = resolve(tmpDir, 'project');- mkdirSync(resolve(projectRoot, '.git'), { recursive: true });-- const result = resolveGitDir(projectRoot);- expect(result).toBe(resolve(projectRoot, '.git'));- });-- test('resolves worktree .git pointer file', () => {- const projectRoot = resolve(tmpDir, 'worktree');- const realGitDir = resolve(tmpDir, 'real-git');- mkdirSync(projectRoot, { recursive: true });- mkdirSync(realGitDir, { recursive: true });-- // .git is a file with gitdir: pointer- writeFileSync(resolve(projectRoot, '.git'), `gitdir: ${realGitDir}\n`);-- const result = resolveGitDir(projectRoot);- expect(result).toBe(realGitDir);- });-- test('returns null when no .git exists', () => {- const projectRoot = resolve(tmpDir, 'no-git');- mkdirSync(projectRoot, { recursive: true });-- const result = resolveGitDir(projectRoot);- expect(result).toBeNull();- });-});--describe('readBranchFromHead', () => {+describe('readProjectHeadState', () => {test('reads branch name from symref HEAD', () => {- const gitDir = resolve(tmpDir, 'git');+ const projectRoot = resolve(tmpDir, 'project');+ const gitDir = resolve(projectRoot, '.git');mkdirSync(gitDir, { recursive: true });writeFileSync(resolve(gitDir, 'HEAD'), 'ref: refs/heads/main\n');- expect(readBranchFromHead(gitDir)).toBe('main');+ expect(readProjectHeadState(projectRoot)).toEqual({ branch: 'main', oid: null });});test('reads feature branch name', () => {- const gitDir = resolve(tmpDir, 'git');+ const projectRoot = resolve(tmpDir, 'project');+ const gitDir = resolve(projectRoot, '.git');mkdirSync(gitDir, { recursive: true });writeFileSync(resolve(gitDir, 'HEAD'), 'ref: refs/heads/feature/my-feature\n');- expect(readBranchFromHead(gitDir)).toBe('feature/my-feature');+ expect(readProjectHeadState(projectRoot)).toEqual({+ branch: 'feature/my-feature',+ oid: null,+ });});test('returns detached-<sha12> for raw SHA HEAD', () => {- const gitDir = resolve(tmpDir, 'git');+ const projectRoot = resolve(tmpDir, 'project');+ const gitDir = resolve(projectRoot, '.git');mkdirSync(gitDir, { recursive: true });const sha = 'abc123def456789012345678901234567890abcd';writeFileSync(resolve(gitDir, 'HEAD'), `${sha}\n`);- expect(readBranchFromHead(gitDir)).toBe('detached-abc123def456');+ expect(readProjectHeadState(projectRoot)).toEqual({+ branch: 'detached-abc123def456',+ oid: sha,+ });});test('returns null when .git/HEAD does not exist', () => {- const gitDir = resolve(tmpDir, 'nonexistent');- expect(readBranchFromHead(gitDir)).toBeNull();+ const projectRoot = resolve(tmpDir, 'project');+ mkdirSync(resolve(projectRoot, '.git'), { recursive: true });+ expect(readProjectHeadState(projectRoot)).toEqual({ branch: null, oid: null });});test('returns null for invalid HEAD content', () => {- const gitDir = resolve(tmpDir, 'git');+ const projectRoot = resolve(tmpDir, 'project');+ const gitDir = resolve(projectRoot, '.git');mkdirSync(gitDir, { recursive: true });writeFileSync(resolve(gitDir, 'HEAD'), 'invalid\n');- expect(readBranchFromHead(gitDir)).toBeNull();+ expect(readProjectHeadState(projectRoot)).toEqual({ branch: null, oid: null });+ });++ test('reads a linked worktree branch oid from the common packed refs', () => {+ const projectRoot = resolve(tmpDir, 'worktree');+ const commonDir = resolve(tmpDir, 'main', '.git');+ const gitDir = resolve(commonDir, 'worktrees', 'feature');+ mkdirSync(projectRoot, { recursive: true });+ mkdirSync(gitDir, { recursive: true });+ writeFileSync(resolve(projectRoot, '.git'), `gitdir: ${gitDir}\n`);+ writeFileSync(resolve(gitDir, 'commondir'), '../..\n');+ writeFileSync(resolve(gitDir, 'HEAD'), 'ref: refs/heads/feature/deep-inspection\n');+ writeFileSync(+ resolve(commonDir, 'packed-refs'),+ '0123456789abcdef0123456789abcdef01234567 refs/heads/feature/deep-inspection\n',+ );++ expect(readProjectHeadState(projectRoot)).toEqual({+ branch: 'feature/deep-inspection',+ oid: '0123456789abcdef0123456789abcdef01234567',+ });});});diff --git a/packages/server/src/head-watcher.ts b/packages/server/src/head-watcher.tsindex db7e15e35..ed6e3d33f 100644--- a/packages/server/src/head-watcher.ts+++ b/packages/server/src/head-watcher.ts@@ -8,9 +8,10 @@* A timeout cap prevents indefinite batching (e.g., long rebase).*/-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import {+ discoverGitRepository,+ type GitRepository,+} from '@inkeep/open-knowledge-core/git-repository';import { getLogger } from './logger.ts';const log = getLogger('head-watcher');@@ -52,56 +53,29 @@ const WATCHED_FILES = new Set(['HEAD', 'MERGE_HEAD', 'ORIG_HEAD', 'index.lock'])// ─── Helpers ─────────────────────────────────────────────────────────────────-/** Read current HEAD SHA, or null if unreadable. */-function readHeadSha(gitDir: string): string | null {- try {- const headContent = readFileSync(resolve(gitDir, 'HEAD'), 'utf-8').trim();- // HEAD may be a ref (ref: refs/heads/main) or a detached SHA- if (headContent.startsWith('ref: ')) {- const refPath = resolve(gitDir, headContent.slice(5));- try {- return readFileSync(refPath, 'utf-8').trim();- } catch {- // Ref file may not exist (empty repo)- // Try packed-refs- try {- const packed = readFileSync(resolve(gitDir, 'packed-refs'), 'utf-8');- const refName = headContent.slice(5);- const line = packed.split('\n').find((l) => l.endsWith(` ${refName}`));- if (line) return line.split(' ')[0];- } catch {- // No packed-refs- }- return null;- }- }- // Detached HEAD — the content is the SHA- return headContent.length >= 40 ? headContent.slice(0, 40) : null;- } catch {- return null;- }+export interface ProjectHeadState {+ readonly branch: string | null;+ readonly oid: string | null;}-/**- * Read the branch name from .git/HEAD.- *- * Returns the branch name (e.g. "main") for a symref,- * "detached-<sha12>" for a raw SHA, or null if unreadable.- */-export function readBranchFromHead(gitDir: string): string | null {- try {- const headContent = readFileSync(resolve(gitDir, 'HEAD'), 'utf-8').trim();- if (headContent.startsWith('ref: refs/heads/')) {- return headContent.slice('ref: refs/heads/'.length);- }- // Detached HEAD — raw SHA- if (headContent.length >= 40) {- return `detached-${headContent.slice(0, 12)}`;- }- return null;- } catch {- return null;+function readRepositoryHeadState(repository: GitRepository): ProjectHeadState {+ const head = repository.readHead();+ if (head.kind === 'detached') {+ return { branch: `detached-${head.oid.slice(0, 12)}`, oid: head.oid };}+ if (head.kind !== 'branch') return { branch: null, oid: null };++ const ref = repository.readRef(head.ref);+ const oid = ref.kind === 'present' && ref.value.kind === 'oid' ? ref.value.oid : null;+ return { branch: head.branch, oid };+}++/** Read the current branch label and resolved HEAD oid without throwing. */+export function readProjectHeadState(projectRoot: string): ProjectHeadState {+ const inspected = discoverGitRepository(projectRoot);+ return inspected.kind === 'repository'+ ? readRepositoryHeadState(inspected.repository)+ : { branch: null, oid: null };}// ─── Backends ────────────────────────────────────────────────────────────────@@ -207,12 +181,13 @@ export async function startHeadWatcher(onBatchEnd: OnBatchEnd,opts: { forceBackend?: 'parcel' | 'chokidar' } = {},): Promise<HeadWatcherHandle> {- const resolvedGitDir = resolveGitDir(projectRoot);- if (!resolvedGitDir) {+ const inspected = discoverGitRepository(projectRoot);+ if (inspected.kind !== 'repository') {// No .git/ to watch — skip attachment without erroringreturn { unsubscribe: async () => {}, getLastKnownBranch: () => null };}- const gitDir: string = resolvedGitDir;+ const repository = inspected.repository;+ const gitDir = repository.gitDir;let inBatch = false;let quietTimer: ReturnType<typeof setTimeout> | null = null;@@ -234,9 +209,10 @@ export async function startHeadWatcher(timeoutTimer = null;}- const newHead = readHeadSha(gitDir);+ const head = readRepositoryHeadState(repository);+ const newHead = head.oid;const headMoved = oldHead !== newHead;- const newBranch = readBranchFromHead(gitDir);+ const newBranch = head.branch;// Classify batch kindlet batchKind: BatchKind;@@ -291,7 +267,7 @@ export async function startHeadWatcher(// the post-move SHA and report `headMoved: false` for a genuine move —// silently defeating upstream-import detection + author attribution. Only// seed when we have no baseline yet (first event in an empty repo).- if (oldHead === null) oldHead = readHeadSha(gitDir);+ if (oldHead === null) oldHead = readRepositoryHeadState(repository).oid;const beginPromise = (async () => {try {await onBatchBegin({ trigger });@@ -339,8 +315,9 @@ export async function startHeadWatcher(// Read initial state AFTER the watcher is active to avoid missing events// that occur between the read and the subscription completing.- oldHead = readHeadSha(gitDir);- lastKnownBranch = readBranchFromHead(gitDir);+ const initialHead = readRepositoryHeadState(repository);+ oldHead = initialHead.oid;+ lastKnownBranch = initialHead.branch;log.info({ gitDir, backend }, 'watching for HEAD changes');diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 1fed1fc11..3b4aebc61 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -197,7 +197,7 @@ export {INSTALLED_AGENTS_SCHEMES,type InstalledAgentScheme,} from './handoff-api.ts';-export { readBranchFromHead } from './head-watcher.ts';+export { type ProjectHeadState, readProjectHeadState } from './head-watcher.ts';export {createStreamingErrorWriter,errorResponse,diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 9dffdd283..b9a347245 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -100,7 +100,7 @@ import type {ProbeTokenStore,PushPermission,} from './github-permissions.ts';-import { type HeadWatcherHandle, readBranchFromHead, startHeadWatcher } from './head-watcher.ts';+import { type HeadWatcherHandle, readProjectHeadState, startHeadWatcher } from './head-watcher.ts';import { createLiveDerivedIndexExtension } from './live-derived-index.ts';import { getLogger } from './logger.ts';import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';@@ -3290,12 +3290,11 @@ export function createServer(options: ServerOptions): ServerInstance {// Reset branch-scoped state to match THIS project's current HEAD before// anything reads/writes it. `persistence.activeBranch` and the// `BacklinkIndex.activeBranch` are mutable state; in single-process test- // runners (bun test) these leak across test files, so a prior test that+ // runners these leak across test files, so a prior test that// triggered `switchReconciledBaseScope` leaves state at the wrong branch// for the next server's reads. Detecting the actual HEAD here and// normalizing both scopes in lock-step closes the leak.- const gitDirForInit = resolveGitDir(projectDir);- const startupBranch = gitDirForInit ? (readBranchFromHead(gitDirForInit) ?? 'main') : 'main';+ const startupBranch = readProjectHeadState(projectDir).branch ?? 'main';switchReconciledBaseScope(startupBranch);backlinkIndex.switchBranch(startupBranch);@@ -3540,10 +3539,7 @@ export function createServer(options: ServerOptions): ServerInstance {const currentBranch = getActiveBranch();// Read new branch from HEAD (already updated by git at onBatchBegin time)// so the park subject can carry both ends of the switch.- const gitDir = resolveGitDir(projectDir);- const newBranch = gitDir- ? (readBranchFromHead(gitDir) ?? currentBranch)- : currentBranch;+ const newBranch = readProjectHeadState(projectDir).branch ?? currentBranch;const docs: ParkableDoc[] = [];for (const [docName, document] of hocuspocus.documents) {if (isReservedForUserTree(docName)) continue;diff --git a/packages/server/src/share/git-context.test.ts b/packages/server/src/share/git-context.test.tsindex 11d55f975..6a45a08c3 100644--- a/packages/server/src/share/git-context.test.ts+++ b/packages/server/src/share/git-context.test.ts@@ -1,7 +1,7 @@-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, relative, resolve } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';import {branchExistsOnOrigin,originGitHubHost,@@ -47,6 +47,8 @@ function seedRepo(}const CANONICAL_HEAD = 'ref: refs/heads/main\n';+const OID_A = 'a'.repeat(40);+const OID_B = 'b'.repeat(40);const CANONICAL_CONFIG_HTTPS ='[remote "origin"]\n\turl = https://github.com/inkeep/open-knowledge.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n';@@ -340,34 +342,33 @@ describe('branchExistsOnOrigin', () => {});test('returns true when a loose ref exists', () => {- seedRepo(dir, { branchRefs: { main: 'abc123\n' } });+ seedRepo(dir, { branchRefs: { main: `${OID_A}\n` } });expect(branchExistsOnOrigin(dir, 'main')).toBe(true);});test('returns false when no ref file exists', () => {- seedRepo(dir, { branchRefs: { main: 'abc123\n' } });+ seedRepo(dir, { branchRefs: { main: `${OID_A}\n` } });expect(branchExistsOnOrigin(dir, 'feature-x')).toBe(false);});test('returns true for a packed-refs entry', () => {seedRepo(dir, {- packedRefs:- '# pack-refs with: peeled fully-peeled sorted\nabc123 refs/remotes/origin/main\ndef456 refs/remotes/origin/develop\n',+ packedRefs: `# pack-refs with: peeled fully-peeled sorted\n${OID_A} refs/remotes/origin/main\n${OID_B} refs/remotes/origin/develop\n`,});expect(branchExistsOnOrigin(dir, 'develop')).toBe(true);});test('returns false for an absent packed-refs entry', () => {seedRepo(dir, {- packedRefs: '# pack-refs with: peeled fully-peeled sorted\nabc123 refs/remotes/origin/main\n',+ packedRefs: `# pack-refs with: peeled fully-peeled sorted\n${OID_A} refs/remotes/origin/main\n`,});expect(branchExistsOnOrigin(dir, 'feature-x')).toBe(false);});test('returns true when the branch is loose AND packed (loose wins)', () => {seedRepo(dir, {- branchRefs: { main: 'abc123\n' },- packedRefs: '# pack-refs with: peeled fully-peeled sorted\ndef456 refs/remotes/origin/main\n',+ branchRefs: { main: `${OID_A}\n` },+ packedRefs: `# pack-refs with: peeled fully-peeled sorted\n${OID_B} refs/remotes/origin/main\n`,});expect(branchExistsOnOrigin(dir, 'main')).toBe(true);});@@ -377,13 +378,13 @@ describe('branchExistsOnOrigin', () => {});test('handles branches with slashes in loose-ref form', () => {- seedRepo(dir, { branchRefs: { 'feat/sharing': 'abc\n' } });+ seedRepo(dir, { branchRefs: { 'feat/sharing': `${OID_A}\n` } });expect(branchExistsOnOrigin(dir, 'feat/sharing')).toBe(true);});test('handles branches with slashes via packed-refs', () => {seedRepo(dir, {- packedRefs: 'abc123 refs/remotes/origin/feat/sharing-virality-flow\n',+ packedRefs: `${OID_A} refs/remotes/origin/feat/sharing-virality-flow\n`,});expect(branchExistsOnOrigin(dir, 'feat/sharing-virality-flow')).toBe(true);});@@ -474,7 +475,7 @@ describe('linked-worktree common-dir resolution', () => {writeFileSync(join(commonDir, 'config'), CANONICAL_CONFIG_HTTPS, 'utf-8');const refDir = join(commonDir, 'refs', 'remotes', 'origin');mkdirSync(refDir, { recursive: true });- writeFileSync(join(refDir, 'feat-bar'), 'abc123\n', 'utf-8');+ writeFileSync(join(refDir, 'feat-bar'), `${OID_A}\n`, 'utf-8');// Linked-worktree git dir: per-worktree HEAD + a relative `commondir`// pointer, exactly as git writes it (`.git/worktrees/<name>/commondir`).const worktreeGitDir = join(commonDir, 'worktrees', 'wt');diff --git a/packages/server/src/share/git-context.ts b/packages/server/src/share/git-context.tsindex dc07eb86f..7a14910fd 100644--- a/packages/server/src/share/git-context.ts+++ b/packages/server/src/share/git-context.ts@@ -24,9 +24,11 @@* toast.*/-import { existsSync, readFileSync, statSync } from 'node:fs';-import { isAbsolute, join, resolve } from 'node:path';import { KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';+import {+ type GitRepository,+ inspectGitRepository,+} from '@inkeep/open-knowledge-core/git-repository';import { getLogger } from '../logger.ts';const log = getLogger('git-context');@@ -37,65 +39,9 @@ export type OriginResult =| { kind: 'no-remote' }| { kind: 'non-github' };-/**- * Resolve the absolute git directory for a project. Handles both the common- * `<project>/.git/` directory layout and worktrees where `<project>/.git`- * is a file containing `gitdir: <absolute-or-relative-path>`.- *- * For a linked worktree the returned dir holds per-worktree state (`HEAD`)- * but NOT `config` / `refs/remotes/` — those live in the shared common dir.- * Reads of those must go through `resolveCommonDir`; otherwise a- * worktree project reports `no-remote` even when origin is configured.- */-function resolveGitDir(projectDir: string): string | null {- const gitPath = resolve(projectDir, '.git');- if (!existsSync(gitPath)) return null;-- let stat: ReturnType<typeof statSync>;- try {- stat = statSync(gitPath);- } catch {- return null;- }-- if (stat.isDirectory()) return gitPath;-- if (stat.isFile()) {- let contents: string;- try {- contents = readFileSync(gitPath, 'utf-8');- } catch {- return null;- }- const match = /^gitdir:\s*(.+)$/m.exec(contents.trim());- if (!match) return null;- const rawTarget = match[1].trim();- const target = isAbsolute(rawTarget) ? rawTarget : resolve(projectDir, rawTarget);- return existsSync(target) ? target : null;- }-- return null;-}--/**- * Resolve the shared common git dir for `config` + `refs/remotes/` reads. In a- * linked worktree the git dir holds a `commondir` file pointing at the main- * `.git` (path is relative to the worktree git dir, occasionally absolute);- * the origin config and remote-tracking refs live there, not in the worktree- * git dir. For a non-worktree git dir there is no `commondir` file and the git- * dir itself is the common dir.- */-function resolveCommonDir(gitDir: string): string {- const pointer = join(gitDir, 'commondir');- if (!existsSync(pointer)) return gitDir;- let contents: string;- try {- contents = readFileSync(pointer, 'utf-8').trim();- } catch {- return gitDir;- }- if (contents.length === 0) return gitDir;- return isAbsolute(contents) ? contents : resolve(gitDir, contents);+function readRepository(projectDir: string): GitRepository | null {+ const result = inspectGitRepository(projectDir);+ return result.kind === 'repository' ? result.repository : null;}/**@@ -103,67 +49,8 @@ function resolveCommonDir(gitDir: string): string {* a detached HEAD (raw SHA), a missing HEAD file, or any read failure.*/export function readGitHeadBranch(projectDir: string): string | null {- const gitDir = resolveGitDir(projectDir);- if (!gitDir) return null;- const headPath = join(gitDir, 'HEAD');- if (!existsSync(headPath)) return null;- let head: string;- try {- head = readFileSync(headPath, 'utf-8');- } catch {- return null;- }- const match = /^ref:\s*refs\/heads\/(.+)$/.exec(head.trim());- return match ? match[1] : null;-}--/**- * Strip git-config inline comments (`;` or `#`) and surrounding whitespace.- * `;` and `#` are both valid comment characters in git's `*.config` grammar.- */-function stripCommentAndTrim(line: string): string {- const hashIdx = line.indexOf('#');- const semiIdx = line.indexOf(';');- let cutAt = -1;- if (hashIdx >= 0 && semiIdx >= 0) cutAt = Math.min(hashIdx, semiIdx);- else if (hashIdx >= 0) cutAt = hashIdx;- else if (semiIdx >= 0) cutAt = semiIdx;- return (cutAt === -1 ? line : line.slice(0, cutAt)).trim();-}--/**- * Extract the first `url = ...` value from the `[remote "origin"]` section- * of a git config file. Returns null when the section is absent, has no- * `url` line, or the config is malformed.- */-export function extractOriginUrl(configContents: string): string | null {- let inOriginRemote = false;- for (const rawLine of configContents.split(/\r?\n/)) {- const line = stripCommentAndTrim(rawLine);- if (line.length === 0) continue;- if (line.startsWith('[')) {- // Match `[remote "origin"]` with arbitrary internal whitespace and- // either single or double quotes (git accepts both). Kept in sync- // with the sibling parsers in- // `packages/desktop/src/main/git-remote.ts` and- // `packages/cli/src/github/folder-validator.ts` — see- // `packages/desktop/tests/main/git-config-parser-parity.test.ts`.- inOriginRemote = /^\[\s*remote\s+["']origin["']\s*\]$/.test(line);- continue;- }- if (!inOriginRemote) continue;- const match = /^url\s*=\s*(.+)$/.exec(line);- if (!match) continue;- let value = match[1].trim();- if (- (value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))- ) {- value = value.slice(1, -1);- }- if (value.length > 0) return value;- }- return null;+ const head = readRepository(projectDir)?.readHead();+ return head?.kind === 'branch' ? head.branch : null;}/** Parsed origin repo: normalized host + owner/repo path segments. */@@ -223,31 +110,13 @@ function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {return null;}-/**- * Shared `.git/config` → origin-URL pipeline for the two public origin- * readers: resolve the git dir, read `config`, extract the origin URL,- * and classify it as github (owner/repo) or not. Returns null when there is- * no readable origin URL. Centralizing the read here keeps future- * config-resolution changes (worktree config, `[includeIf]`, error handling)- * in one place instead of drifting across two callers.- */+/** Read and classify the configured origin shared by the two public readers. */function readParsedOrigin(projectDir: string,): { originUrl: string; github: ParsedOriginRepo | null } | null {- const gitDir = resolveGitDir(projectDir);- if (!gitDir) return null;- // Origin config lives in the common dir, which differs from `gitDir` for a- // linked worktree (where `gitDir` has no `config` of its own).- const configPath = join(resolveCommonDir(gitDir), 'config');- if (!existsSync(configPath)) return null;- let configContents: string;- try {- configContents = readFileSync(configPath, 'utf-8');- } catch {- return null;- }- const originUrl = extractOriginUrl(configContents);- if (!originUrl) return null;+ const origin = readRepository(projectDir)?.readRemoteUrl('origin');+ if (origin?.kind !== 'configured') return null;+ const originUrl = origin.url;return { originUrl, github: parseGitHubOriginUrl(originUrl) };}@@ -346,29 +215,5 @@ function labelFromNonGitHubUrl(url: string): string {* the retry succeeds. Acceptable by contract.*/export function branchExistsOnOrigin(projectDir: string, branch: string): boolean {- const gitDir = resolveGitDir(projectDir);- if (!gitDir) return false;- // Remote-tracking refs + packed-refs live in the common dir, shared across- // worktrees — not in a linked worktree's own git dir.- const commonDir = resolveCommonDir(gitDir);-- const loosePath = join(commonDir, 'refs', 'remotes', 'origin', branch);- if (existsSync(loosePath)) return true;-- const packedPath = join(commonDir, 'packed-refs');- if (!existsSync(packedPath)) return false;- let packed: string;- try {- packed = readFileSync(packedPath, 'utf-8');- } catch {- return false;- }- const target = `refs/remotes/origin/${branch}`;- for (const rawLine of packed.split(/\r?\n/)) {- const line = rawLine.trim();- if (line.length === 0 || line.startsWith('#') || line.startsWith('^')) continue;- const parts = line.split(/\s+/);- if (parts.length === 2 && parts[1] === target) return true;- }- return false;+ return readRepository(projectDir)?.readRef(`refs/remotes/origin/${branch}`).kind === 'present';}diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.tsindex 0311542df..b6a9eb70b 100644--- a/packages/server/src/sync-engine.ts+++ b/packages/server/src/sync-engine.ts@@ -18,6 +18,7 @@ import {import { tmpdir } from 'node:os';import { join, relative, resolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';+import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';import type { CC1Broadcaster } from './cc1-broadcast.ts';import { getLocalDir } from './config/paths.ts';@@ -262,23 +263,11 @@ function jitteredMs(seconds: number): number {* repo whose refs happen to be packed.*/function isUnbornHead(projectDir: string): boolean {- try {- const headPath = join(projectDir, '.git', 'HEAD');- if (!existsSync(headPath)) return false;- const headContent = readFileSync(headPath, 'utf-8').trim();- const match = /^ref:\s+(refs\/.+)$/.exec(headContent);- if (!match) return false;- const refName = match[1] as string;- if (existsSync(join(projectDir, '.git', refName))) return false;- const packedRefsPath = join(projectDir, '.git', 'packed-refs');- if (existsSync(packedRefsPath)) {- const packed = readFileSync(packedRefsPath, 'utf-8');- if (new RegExp(`^[0-9a-f]+\\s+${refName}$`, 'm').test(packed)) return false;- }- return true;- } catch {- return false;- }+ const inspected = inspectGitRepository(projectDir);+ if (inspected.kind !== 'repository') return false;+ const head = inspected.repository.readHead();+ if (head.kind !== 'branch') return false;+ return inspected.repository.readRef(head.ref).kind === 'absent';}// ─── Backoff thresholds ──────────────────────────────────────────────────────