The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Reduce background Git processes for session metadata (#515)
Deeb98f168fb42c
diff --git a/cli/src/lib/agentProject.spec.ts b/cli/src/lib/agentProject.spec.tsindex 6de724a90..07c201004 100644--- a/cli/src/lib/agentProject.spec.ts+++ b/cli/src/lib/agentProject.spec.ts@@ -1,5 +1,5 @@import { execFileSync } from 'node:child_process'-import { mkdtemp, mkdir, rm, realpath, writeFile } from 'node:fs/promises'+import { appendFile, mkdtemp, mkdir, rm, realpath, symlink, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'@@ -58,6 +58,100 @@ describe('owning-machine project metadata', () => {expect(await agentProject('/tmp/unsafe\n')).toBeNull()})+ it('discovers a missing historical folder when it becomes a checkout again', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-missing-')); roots.push(root)+ const cwd = join(root, 'checkout')+ const reader = createAgentProjectReader()+ expect(await reader.read(cwd, 0)).toMatchObject({ cwd, root: null, branch: null })+ await writeFile(cwd, 'not a directory')+ expect(await reader.read(cwd, 20_000)).toMatchObject({ cwd, root: null, branch: null })+ await rm(cwd); await mkdir(cwd)+ execFileSync('git', ['-C', cwd, 'init', '-b', 'returned'], { stdio: 'pipe' })+ expect(await reader.read(cwd, 40_000)).toMatchObject({ cwd, root: await realpath(cwd), branch: 'returned' })+ })++ it('keeps the repository identity through symlinked and nested worktree paths', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-paths-')); roots.push(root)+ const repo = join(root, 'main repository'); await mkdir(repo)+ const git = (...args: string[]) => execFileSync('git', ['-C', repo, ...args], { stdio: 'pipe' })+ git('init', '-b', 'main')+ git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'initial')+ const linked = join(root, 'linked'); git('worktree', 'add', '-b', 'topic', linked)+ await mkdir(join(linked, 'nested'))+ const alias = join(root, 'alias'); await symlink(linked, alias, 'dir')+ const reader = createAgentProjectReader()+ for (const cwd of [linked, join(linked, 'nested'), alias, join(alias, 'nested')]) {+ expect(await reader.read(cwd)).toMatchObject({ cwd, name: 'main repository', root: await realpath(linked), branch: 'topic', worktree: true })+ }+ const mainAlias = join(root, 'main alias'); await symlink(repo, mainAlias, 'dir')+ expect(await reader.read(mainAlias)).toMatchObject({ cwd: mainAlias, root: await realpath(repo), branch: 'main' })+ expect(await reader.read(mainAlias)).not.toHaveProperty('worktree')+ })++ it('retains separate path reads when a symlink resolves to a newline in the repository name', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-newline-')); roots.push(root)+ const repo = join(root, 'repository\nname'); await mkdir(repo)+ execFileSync('git', ['-C', repo, 'init', '-b', 'main'], { stdio: 'pipe' })+ const alias = join(root, 'alias'); await symlink(repo, alias, 'dir')+ expect(await createAgentProjectReader().read(alias)).toMatchObject({ cwd: alias, name: 'repository\nname', root: await realpath(repo), branch: 'main' })+ })++ it('uses exact branch keys and the last config value, including empty and valueless overrides', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-config-')); roots.push(root)+ const branch = 'Topic/a.b+(review)'+ const marker = `branch.${branch}.harness`+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'pipe' })+ git('init', '-b', branch)+ const included = join(root, 'included config')+ git('config', '--file', included, 'remote.origin.url', '[email protected]:Org/Included.git')+ git('config', '--file', included, marker, 'placeholder')+ git('config', 'include.path', included)+ git('config', '--add', 'remote.origin.url', 'https://user:[email protected]/Org/Current.git?token=secret')+ const reader = createAgentProjectReader()+ expect(await reader.read(root)).toMatchObject({ branch, remote: 'github.com/org/current', branchPending: true })+ git('config', '--add', marker, '')+ reader.forget(root)+ expect(await reader.read(root)).not.toHaveProperty('branchPending')+ git('config', '--add', marker, 'placeholder')+ reader.forget(root)+ expect(await reader.read(root)).toHaveProperty('branchPending', true)+ await appendFile(join(root, '.git', 'config'), `\n[branch "${branch}"]\nharness\n[remote "origin"]\nurl\n`)+ reader.forget(root)+ const cleared = await reader.read(root)+ expect(cleared).toMatchObject({ branch, remote: null })+ expect(cleared).not.toHaveProperty('branchPending')+ })++ it('honours linked-worktree config overrides without changing the shared checkout', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-worktree-config-')); roots.push(root)+ const repo = join(root, 'main'); await mkdir(repo)+ const git = (...args: string[]) => execFileSync('git', ['-C', repo, ...args], { stdio: 'pipe' })+ git('init', '-b', 'main')+ git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'initial')+ git('config', 'remote.origin.url', '[email protected]:Org/Main.git')+ git('config', 'extensions.worktreeConfig', 'true')+ const linked = join(root, 'linked')+ git('worktree', 'add', '-b', 'topic', linked)+ git('config', 'branch.topic.harness', 'placeholder')+ execFileSync('git', ['-C', linked, 'config', '--worktree', 'remote.origin.url', '[email protected]:Org/Linked.git'])+ execFileSync('git', ['-C', linked, 'config', '--worktree', 'branch.topic.harness', 'named'])+ const reader = createAgentProjectReader()+ const project = await reader.read(linked)+ expect(project).toMatchObject({ branch: 'topic', remote: 'github.com/org/linked', worktree: true })+ expect(project).not.toHaveProperty('branchPending')+ expect(await reader.read(repo)).toMatchObject({ branch: 'main', remote: 'github.com/org/main' })+ })++ it('retains metadata when duplicate config values exceed the combined output bound', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-project-large-config-')); roots.push(root)+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'pipe' })+ git('init', '-b', 'main')+ await appendFile(join(root, '.git', 'config'), '\n[remote "origin"]\n' ++ `url = https://example.invalid/${'x'.repeat(1000)}\n`.repeat(20) ++ 'url = [email protected]:Org/Current.git\n[branch "main"]\nharness = placeholder\n')+ expect(await createAgentProjectReader().read(root)).toMatchObject({ remote: 'github.com/org/current', branchPending: true })+ })+it('checks metadata without running Git again for unchanged historical folders', async () => {const root = await mkdtemp(join(tmpdir(), 'harness-v2-project-cache-')); roots.push(root)let calls = 0diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.tsindex e09d44c13..d723f8103 100644--- a/cli/src/lib/agentProject.ts+++ b/cli/src/lib/agentProject.ts@@ -35,16 +35,65 @@ export function canonicalRepository(raw: string | null): string | null {}/** Bounded subprocesses, no shell, network, or repository mutation. */+async function runGit(cwd: string, args: string[]): Promise<string | null> {+ const environment = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (environment as NodeJS.ProcessEnv)[key]+ const { stdout } = await exec('git', ['-C', cwd, ...args], {+ timeout: 1500, maxBuffer: 16 * 1024, encoding: 'utf8',+ env: environment,+ })+ return stdout.trim() || null+}+async function git(cwd: string, args: string[]): Promise<string | null> {+ return runGit(cwd, args).catch(() => null)+}++/** Read the two config values in one Git process. Git still resolves includes,+ * worktree config and precedence; the last matching value wins, as with --get. */+async function projectConfig(cwd: string, branch: string | null) {+ const marker = branch && !branch.startsWith('Detached ') ? `branch.${branch}.harness` : null+ const keys = ['remote.origin.url', ...(marker ? [marker] : [])]+ const pattern = `^(${keys.map(key => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})$`+ let output: string | null+ try { output = await runGit(cwd, ['config', '--null', '--get-regexp', pattern]) }+ catch (error) {+ if ((error as { code?: string | number }).code === 1) return { remote: null, pending: false }+ // A large set of duplicate values can exceed the combined output bound.+ // Keep the individual reads as a fallback so metadata remains available.+ return { remote: await git(cwd, ['config', '--get', 'remote.origin.url']),+ pending: marker !== null && await git(cwd, ['config', '--get', marker]) === 'placeholder' }+ }+ const values = new Map<string, string | null>()+ for (const record of output?.split('\0') ?? []) {+ if (!record) continue+ // -z separates records with NUL and each key from its value with a newline.+ // A valueless entry has no newline and overrides an earlier value too.+ const separator = record.indexOf('\n')+ const key = separator < 0 ? record : record.slice(0, separator)+ values.set(key, separator < 0 ? null : record.slice(separator + 1).trim() || null)+ }+ return { remote: values.get('remote.origin.url') ?? null, pending: marker !== null && values.get(marker) === 'placeholder' }+}++/** One discovery process for both paths. Absolute output preserves linked+ * worktree names even when cwd is a subdirectory or a symlink. */+async function repositoryPaths(cwd: string): Promise<{ root: string; common: string | null } | null> {try {- const environment = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (environment as NodeJS.ProcessEnv)[key]- const { stdout } = await exec('git', ['-C', cwd, ...args], {- timeout: 1500, maxBuffer: 16 * 1024, encoding: 'utf8',- env: environment,- })- return stdout.trim() || null- } catch { return null }+ if (!(await stat(cwd)).isDirectory()) return null+ } catch (error) {+ // Historical sessions can point at deleted temporary folders. Other stat+ // failures still defer to Git rather than asserting that a checkout is gone.+ if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return null+ }+ const output = await git(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])+ if (!output) return null+ const paths = output.split('\n')+ if (paths.length === 2 && paths.every(isAbsolute)) return { root: paths[0], common: paths[1] }+ // Older Git prints an unrecognised --path-format flag literally. Ambiguous+ // output (including a newline in a physical path) retains the separate reads.+ const root = await git(cwd, ['rev-parse', '--show-toplevel'])+ return root ? { root, common: await git(root, ['rev-parse', '--git-common-dir']) } : null}// Only four folders run Git at once, including cache refreshes.@@ -54,18 +103,15 @@ async function inspect(cwd: string): Promise<AgentProject> {if (running >= 4) await new Promise<void>(resolve => waiting.push(resolve))else running++try {- const root = await git(cwd, ['rev-parse', '--show-toplevel'])- if (!root) return { name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }- const remote = await git(cwd, ['config', '--get', 'remote.origin.url'])+ const paths = await repositoryPaths(cwd)+ if (!paths) return { name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }+ const { root, common } = paths// A checkout on no branch still says where it is, as the desktop's own reader does.const branch = await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD'])?? await git(cwd, ['rev-parse', '--short', 'HEAD']).then(sha => sha && `Detached ${sha}`)- const common = await git(root, ['rev-parse', '--git-common-dir'])+ const { remote, pending } = await projectConfig(cwd, branch)// A linked worktree is named for its repository, not its folder.const main = common && basename(common) === '.git' ? dirname(resolve(root, common)) : root- const pending = branch && !branch.startsWith('Detached ')- ? await git(cwd, ['config', '--get', `branch.${branch}.harness`]) === 'placeholder'- : falsereturn {name: basename(main), cwd, root, remote: canonicalRepository(remote), branch,...(main !== root ? { worktree: true as const } : {}), ...(pending ? { branchPending: true as const } : {}),