Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(door): keep pathspecs literal per path so hooks never inherit GIT_LITERAL_PATHSPECS (#7759)
garrytan85a73e40e466
diff --git a/src/core/git-env.ts b/src/core/git-env.tsindex fedaf040e2..50da7a603a 100644--- a/src/core/git-env.ts+++ b/src/core/git-env.ts@@ -3,6 +3,8 @@* repository-locating variables are dropped so `git -C <root>` always works on* `<root>`. Every Git spawn under* `src/core` builds its env here (guarded by `test/git-env-guard.test.ts`).+ * #7759: Git's global pathspec switches are dropped too, so a pathspec gbrain+ * builds means what it says and a hook or helper Git starts for gbrain sees none.* Transport and credential variables (`GIT_SSH_COMMAND`, `GIT_ASKPASS`,* `SSH_AUTH_SOCK`, proxies) pass through, and so do the operator's environment* `safe.directory` entries (#7584); `extra` wins over all of them.@@ -13,7 +15,16 @@ export const GIT_LOCAL_ENV_VARS = ['GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONF'GIT_OBJECT_DIRECTORY', 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_INDEX_FILE','GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_COMMON_DIR', 'GIT_NAMESPACE'] as const;-const LOCAL = new Set<string>(GIT_LOCAL_ENV_VARS);+/** Git's global pathspec switches; GIT_LITERAL_PATHSPECS is what `git --literal-pathspecs` exports to every hook and child. */+export const GIT_PATHSPEC_ENV_VARS = ['GIT_LITERAL_PATHSPECS', 'GIT_GLOB_PATHSPECS', 'GIT_NOGLOB_PATHSPECS', 'GIT_ICASE_PATHSPECS'] as const;++const DROPPED = new Set<string>([...GIT_LOCAL_ENV_VARS, ...GIT_PATHSPEC_ENV_VARS]);++/**+ * #7759: each path as a literal pathspec. Use this instead of the global `--literal-pathspecs` flag, which Git exports+ * as GIT_LITERAL_PATHSPECS=1 to hooks and children, where a hook's glob pathspec then silently matches nothing.+ */+export const literalPathspecs = (paths: readonly string[]): string[] => paths.map(path => `:(literal)${path}`);/*** Extra env for a Git call that only reads (diff, ls-files, cat-file, rev-parse, status): `GIT_OPTIONAL_LOCKS=0` stops Git@@ -47,7 +58,7 @@ export function safeDirectoryEnv(values: readonly string[]): NodeJS.ProcessEnv {export function gitChildEnv(extra: NodeJS.ProcessEnv = {}, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {};for (const [key, value] of Object.entries(source)) {- if (!LOCAL.has(key) && !/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key)) env[key] = value;+ if (!DROPPED.has(key) && !/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key)) env[key] = value;}return { ...env, ...safeDirectoryEnv(envSafeDirectories(source)), ...extra };}diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex 6759a799e3..3db5da516e 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -29,7 +29,7 @@ import { appendFileSync, existsSync, mkdtempSync, readFileSync, realpathSync, reimport { tmpdir } from 'node:os';import { isAbsolute, join, relative, resolve } from 'node:path';import { execFileSync } from '../spawn.ts';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, durableSsrfFlags } from '../git-transport.ts';import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesystemRootFor, type ManagedFilesystemRoot } from '../persistence/filesystem-guard.ts';import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';@@ -397,7 +397,7 @@ function stagedPaths(root: string): string[] {/** The index entries under `rel` as `ls-files -s` records, so a failed commit can put them back exactly. */function indexEntries(root: string, rel: string[]): string[] {- return git(root, ['--literal-pathspecs', 'ls-files', '-s', '-z', '--', ...rel]).stdout.split('\0').filter(Boolean);+ return git(root, ['ls-files', '-s', '-z', '--', ...literalPathspecs(rel)]).stdout.split('\0').filter(Boolean);}/**@@ -436,7 +436,7 @@ function commitPaths(root: string, rel: string[], message: string, scope: Commitdocs: 'docs/guides/shared-checkout-git.md#outcomes' } });}const before = indexEntries(root, rel);- const add = withIndexRetry(root, ['--literal-pathspecs', 'add', '-A', '--', ...rel], 'git add');+ const add = withIndexRetry(root, ['add', '-A', '--', ...literalPathspecs(rel)], 'git add');if (add.code !== 0) {throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');}@@ -444,9 +444,11 @@ function commitPaths(root: string, rel: string[], message: string, scope: Commitconst paths = withRenamePartners(root, rel);const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');- if (git(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...paths]).code === 0) return null;+ if (git(root, ['diff', '--cached', '--quiet', '--', ...literalPathspecs(paths)]).code === 0) return null;const env = { [COMMIT_VIA_ENV]: scope.lockPath, ...(scope.markHeld ? { [COMMIT_LOCK_ENV]: scope.lockPath } : {}) };- const commit = withIndexRetry(root, ['--literal-pathspecs', 'commit', '--only', '-m', message, '--', ...paths], 'git commit', env);+ // #7759: literal per path, never git's global --literal-pathspecs: Git exports that to the commit's hooks, where a+ // guard's glob pathspec ('*.json') then matches nothing and lets the commit through.+ const commit = withIndexRetry(root, ['commit', '--only', '-m', message, '--', ...literalPathspecs(paths)], 'git commit', env);if (commit.code !== 0) {throw opError('git_unavailable', `git commit failed in ${root}; the paths were unstaged again and keep their bytes.`,`${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);@@ -507,7 +509,7 @@ function notePending(root: string, paths: string[]): void {function dirtyPaths(root: string, paths: string[]): Set<string> {const out = new Set<string>();for (let i = 0; i < paths.length; i += 500) {- const entries = git(root, ['--literal-pathspecs', 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...paths.slice(i, i + 500)]).stdout.split('\0');+ const entries = git(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--', ...literalPathspecs(paths.slice(i, i + 500))]).stdout.split('\0');for (let j = 0; j < entries.length; j++) {if (entries[j].length < 4) continue;out.add(entries[j].slice(3));@@ -706,7 +708,7 @@ function integrate(root: string, local: string, remote: string): Integration {interface TreeEntry { mode: string; type: string; sha: string }function treeEntry(root: string, commit: string, path: string): TreeEntry | null {- for (const line of git(root, ['--literal-pathspecs', 'ls-tree', '-z', commit, '--', path]).stdout.split('\0')) {+ for (const line of git(root, ['ls-tree', '-z', commit, '--', ...literalPathspecs([path])]).stdout.split('\0')) {const tab = line.indexOf('\t');if (tab === -1 || line.slice(tab + 1) !== path) continue;const [mode, type, sha] = line.slice(0, tab).split(' ');@@ -742,7 +744,7 @@ function supersededPaths(root: string, ours: string, theirs: string, merged: Merif (explicit?.has(path) || merged.structural.includes(path) || path.includes('\n') || !blobConflict(root, base, ours, theirs, path)) return false;const remote = treeEntry(root, theirs, path);if (!remote) return false;- const commits = git(root, ['--literal-pathspecs', 'log', '--format=%H', '-n', String(MAX_SUPERSEDED_HISTORY), ours, '--', path]).stdout.split('\n').filter(Boolean);+ const commits = git(root, ['log', '--format=%H', '-n', String(MAX_SUPERSEDED_HISTORY), ours, '--', ...literalPathspecs([path])]).stdout.split('\n').filter(Boolean);const blobs = git(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], { input: commits.map(c => `${c}:${path}\n`).join('') }).stdout.split('\n').slice(0, commits.length).map(line => (line.endsWith(' blob') ? line.split(' ')[0] : null));const held = [treeEntry(root, ours, path)?.sha ?? null, ...blobs];diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex ee40f9c1a4..a040058648 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -8,7 +8,7 @@ import { readFix } from '../ops/op-fix.ts';import type { GitCommitNote } from './effect-model.ts';import { persistenceHome } from './identity.ts';import { nativeFileTarget } from './native-file-target.ts';-import { gitChildEnv } from '../git-env.ts';+import { gitChildEnv, literalPathspecs } from '../git-env.ts';import type { Action } from '../agent-output.ts';import type { NativeLockHandle } from './native-lock.ts';import { proveIndexLockAbandoned, reclaimIndexLock, type IndexLockReclaim } from './index-lock-reclaim.ts';@@ -62,18 +62,19 @@ export interface GitEffectOwner {export interface GitSession { root: string; hooks: string; signal?: AbortSignal; timeoutMs: number; owner?: GitEffectOwner; indexFile?: string }-const gitArgs = (session: GitSession, args: string[], literal: boolean) =>- [...(literal ? ['--literal-pathspecs'] : []), '-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args];+/** #7759: no global --literal-pathspecs (Git would export it to every hook and child); pathspecs pass through literalPathspecs. */+const gitArgs = (session: GitSession, args: string[]) =>+ ['-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args];const gitOptions = (session: GitSession) => ({ timeout: session.timeoutMs, termGraceMs: GIT_TERM_GRACE_MS, maxBuffer: 1024 * 1024, signal: session.signal });const sessionEnv = (session: GitSession) => session.indexFile ? { ...GIT_ENV, GIT_INDEX_FILE: session.indexFile } : GIT_ENV;-function run(session: GitSession, args: string[], literal = true) {- return execFileBounded('git', gitArgs(session, args, literal), { ...gitOptions(session), env: gitChildEnv(sessionEnv(session)) });+function run(session: GitSession, args: string[]) {+ return execFileBounded('git', gitArgs(session, args), { ...gitOptions(session), env: gitChildEnv(sessionEnv(session)) });}/** A read-only git step whose stdout is raw bytes (a tree object); null when git exits non-zero. */export async function gitBytes(session: GitSession, args: string[]): Promise<Buffer | null> {- const { error, stdout } = await execFileBounded('git', gitArgs(session, args, true), { ...gitOptions(session), env: gitChildEnv(sessionEnv(session)), maxBuffer: 256 * 1024 * 1024, encoding: 'buffer' });+ const { error, stdout } = await execFileBounded('git', gitArgs(session, args), { ...gitOptions(session), env: gitChildEnv(sessionEnv(session)), maxBuffer: 256 * 1024 * 1024, encoding: 'buffer' });if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',`A git command in the canonical checkout did not finish within ${Math.round(session.timeoutMs / 1000)} seconds or could not start.`);return error ? null : stdout;@@ -142,9 +143,9 @@ async function indexLockError(session: GitSession, stderr: string, mayReclaim: b{ detail: lock, fix: staleLockFix(session.root, lock, why) });}-export async function git(session: GitSession, args: string[], literal = true): Promise<{ stdout: string; stderr: string; code: number }> {+export async function git(session: GitSession, args: string[]): Promise<{ stdout: string; stderr: string; code: number }> {for (let reclaimed = false; ; reclaimed = true) {- const { error, stdout, stderr } = await run(session, args, literal);+ const { error, stdout, stderr } = await run(session, args);if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',`A git command in the canonical checkout did not finish within ${Math.round(session.timeoutMs / 1000)} seconds or could not start.`);const code = error?.code as number ?? 0;@@ -168,16 +169,16 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{const root = session.root;const path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');relativePath = relative(root, path).split(sep).join('/');- const tracked = await git(session, ['ls-files', '-z', '--error-unmatch', '--', relativePath]);+ const tracked = await git(session, ['ls-files', '-z', '--error-unmatch', '--', ...literalPathspecs([relativePath])]);if (tracked.code !== 0 && tracked.code !== 1) throw gitFailure('Cannot inspect the canonical Git target.', `git ls-files failed for ${relativePath}.`);- const changed = await git(session, ['status', '--porcelain', '--untracked-files=all', '--', relativePath]);+ const changed = await git(session, ['status', '--porcelain', '--untracked-files=all', '--', ...literalPathspecs([relativePath])]);if (changed.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git status failed for ${relativePath}.`);if (changed.stdout.trim()) {if (tracked.code === 0 || existsSync(path)) {- const add = await git(session, ['add', '-A', '--', relativePath]);+ const add = await git(session, ['add', '-A', '--', ...literalPathspecs([relativePath])]);if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for ${relativePath}.`);}- const diff = await git(session, ['diff', '--cached', '--quiet', '--', relativePath]);+ const diff = await git(session, ['diff', '--cached', '--quiet', '--', ...literalPathspecs([relativePath])]);if (diff.code === 1) return { path: relativePath, state: 'changed' };if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for ${relativePath}.`);return { path: relativePath, state: 'unchanged' };@@ -192,8 +193,8 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{parent = dirname(parent);}const scope = relative(root, parent).split(sep).join('/') || '.';- const deleted = await git(session, ['diff', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', scope]);- const staged = await git(session, ['diff', '--cached', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', scope]);+ const deleted = await git(session, ['diff', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', ...literalPathspecs([scope])]);+ const staged = await git(session, ['diff', '--cached', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', ...literalPathspecs([scope])]);if (deleted.code !== 0 || staged.code !== 0) throw gitFailure('Cannot inspect canonical Git deletions.', `git diff could not list the deletions under ${scope}.`);for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {if (existsSync(join(root, entry))) continue;@@ -213,10 +214,10 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{* as `git_target_ignored` naming the rule (`detail`), so the effect parks at once with the cause instead of looping.*/async function refuseIgnoredTarget(session: GitSession, relativePath: string): Promise<void> {- const status = await git(session, ['status', '--porcelain', '--ignored=matching', '--untracked-files=all', '--', relativePath]);+ const status = await git(session, ['status', '--porcelain', '--ignored=matching', '--untracked-files=all', '--', ...literalPathspecs([relativePath])]);if (status.code !== 0 || !status.stdout.startsWith('!! ')) return;- // check-ignore takes no literal pathspecs; it only names the rule for the message.- const matched = await run(session, ['check-ignore', '-v', '--', relativePath], false);+ // check-ignore refuses pathspec magic and reads a path literally except a leading ':', which ./ keeps literal; it only names the rule.+ const matched = await run(session, ['check-ignore', '-v', '--', relativePath.startsWith(':') ? `./${relativePath}` : relativePath]);throw ignoredTargetError(relativePath, matched.error ? '.gitignore' : matched.stdout.split('\t')[0]!.replace(/^(.*?):(\d+):/, '$1:$2: '));}@@ -285,7 +286,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si}const paths = [...new Set(normalized.values())];const list = async (args: string[]) => {- const out = paths.length ? await git(session, [...args, '--', ...paths]) : { stdout: '', code: 0 };+ const out = paths.length ? await git(session, [...args, '--', ...literalPathspecs(paths)]) : { stdout: '', code: 0 };if (out.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git ${args[0]} failed for this group of ${paths.length} file(s).`);return out.stdout;};@@ -313,9 +314,9 @@ export async function commitGitTargets(root: string, relativePaths: string[], sielse results.set(requested, { git: 'unchanged' });}if (staged.length) {- const add = await git(session, ['add', '-A', '--', ...new Set(staged)]);+ const add = await git(session, ['add', '-A', '--', ...literalPathspecs([...new Set(staged)])]);if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for this group of ${new Set(staged).size} file(s).`);- const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...new Set(staged)]);+ const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...literalPathspecs([...new Set(staged)])]);if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for this group of ${new Set(staged).size} file(s).`);const indexed = new Set(diff.stdout.split('\0').filter(Boolean));for (const [requested, path] of normalized) {@@ -326,10 +327,10 @@ export async function commitGitTargets(root: string, relativePaths: string[], si}if (removed.size) {const removals = [...removed];- const rm = await git(session, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...removals]);+ const rm = await git(session, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...literalPathspecs(removals)]);if (rm.code !== 0) throw gitFailure('Cannot stage the canonical Git target removal.', `git rm --cached failed for this group of ${removals.length} removed file(s).`);- const kept = await git(session, [...NO_FSCACHE, 'ls-files', '-z', '--', ...removals]);- const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...removals]);+ const kept = await git(session, [...NO_FSCACHE, 'ls-files', '-z', '--', ...literalPathspecs(removals)]);+ const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...literalPathspecs(removals)]);if (kept.code !== 0 || diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target removal.', `git ls-files or git diff --cached failed for this group of ${removals.length} removed file(s).`);const still = new Set(kept.stdout.split('\0').filter(Boolean));const indexed = new Set(diff.stdout.split('\0').filter(Boolean));@@ -347,7 +348,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], siconst noted = new Map<string, GitCommitNote>();for (const c of changed) { const note = notes?.get(c.requested); if (note && !noted.has(c.path)) noted.set(c.path, note); }const message = commitMessage(commitPaths, noted).flatMap(paragraph => ['-m', paragraph]);- const result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...commitPaths]);+ const result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...literalPathspecs(commitPaths)]);const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);for (const c of changed) results.set(c.requested, outcome);diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 1574a98772..d26bdbca2f 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -42,6 +42,7 @@ import { createHash, randomBytes } from 'node:crypto';import { closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { join, relative, resolve, sep } from 'node:path';import type { Notice } from '../agent-output.ts';+import { literalPathspecs } from '../git-env.ts';import { OperationError, opError } from '../ops/contract.ts';import { commitMessage, git, gitBytes, gitFailure, gitStepTimeoutMs, ignoredTargetError, reclaimAbandonedIndexLock, withSession, type GitSession } from './effect-git.ts';import type { GitCommitNote } from './effect-model.ts';@@ -347,8 +348,9 @@ async function refuseIgnored(session: GitSession, root: string, fresh: Target[])const candidates = new Set(await ignoreCandidates(root, fresh.map(target => target.rel)));const asked = fresh.filter(target => candidates.has(target.rel));if (!asked.length) return;- // check-ignore takes no literal pathspecs; -n prints one line per path, in order, so no path is parsed back.- const matched = await git(session, ['check-ignore', '-v', '-n', '--', ...asked.map(target => target.rel)], false);+ // check-ignore refuses pathspec magic and reads a path literally except a leading ':', which ./ keeps literal; -n prints one+ // line per path, in order, so no path is parsed back.+ const matched = await git(session, ['check-ignore', '-v', '-n', '--', ...asked.map(target => target.rel.startsWith(':') ? `./${target.rel}` : target.rel)]);if (matched.code !== 0 && matched.code !== 1) throw gitFailure('Cannot inspect the canonical Git target.', `git check-ignore failed for ${asked.length} file(s).`);const lines = matched.stdout.split('\n');asked.forEach((target, i) => {@@ -391,7 +393,7 @@ const indexSignature = (index: string) => {/** The index entries of the targets, keyed by path relative to the root; the signature is read first, so a later match proves no rewrite. */async function readIndex(session: GitSession, index: string, targets: Target[]): Promise<IndexSnapshot> {const signature = indexSignature(index);- const listed = await git(session, ['ls-files', '-s', '-z', '--', ...targets.map(target => target.rel)]);+ const listed = await git(session, ['ls-files', '-s', '-z', '--', ...literalPathspecs(targets.map(target => target.rel))]);if (listed.code !== 0) throw gitFailure('Cannot read the canonical Git index.', `git ls-files failed for ${targets.length} file(s).`);const entries = new Map<string, string>();for (const record of listed.stdout.split('\0')) {@@ -412,10 +414,10 @@ async function readIndex(session: GitSession, index: string, targets: Target[]):async function replacedEntries(session: GitSession, commit: string, targets: Target[]): Promise<Map<string, string>> {const entries = new Map<string, string>();for (const target of targets) {- const last = await git(session, ['rev-list', '-1', commit, '--', target.rel]);+ const last = await git(session, ['rev-list', '-1', commit, '--', ...literalPathspecs([target.rel])]);const changed = last.stdout.trim();if (last.code !== 0 || !changed) continue;- const listed = await git(session, ['ls-tree', '-z', `${changed}^`, '--', target.rel]);+ const listed = await git(session, ['ls-tree', '-z', `${changed}^`, '--', ...literalPathspecs([target.rel])]);if (listed.code !== 0) continue;for (const record of listed.stdout.split('\0')) {const tab = record.indexOf('\t');diff --git a/test/git-literal-pathspec-hooks-7759.test.ts b/test/git-literal-pathspec-hooks-7759.test.tsnew file mode 100644index 0000000000..2932402345--- /dev/null+++ b/test/git-literal-pathspec-hooks-7759.test.ts@@ -0,0 +1,243 @@+/**+ * #7759: the door keeps its own paths literal per path (`:(literal)<path>`), never with git's global+ * `--literal-pathspecs` flag, which git exports to every hook and child process as GIT_LITERAL_PATHSPECS=1.+ * Protects:+ * - a repository pre-commit guard that selects files by glob pathspec refuses `gbrain git commit-push` exactly as it+ * refuses a plain git commit (red before: the guard's '*.json' matched nothing, so a JSON file with conflict+ * markers was committed and pushed); the refusal leaves HEAD, the index and the remote as they were;+ * - no hook of a commit-push, and no child of the persistence door (clean filter, receive-pack), sees+ * GIT_LITERAL_PATHSPECS, also when gbrain's own environment sets it; the door's session runs no repository hook;+ * - files literally named with glob characters or a leading colon commit alone, never the files their glob or magic+ * reading matches, through commit-push, the Git effect and the plumbing door.+ * Seams: none; real repositories and a bare remote, the real CLI for commit-push.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { commitAndPush } from '../src/core/git/commit-push.ts';+import { commitGitTargets, pushGitRoot } from '../src/core/persistence/effect-git.ts';+import { commitThroughDoor } from '../src/core/persistence/git-door.ts';+import { hashFile } from '../src/core/persistence/large-file.ts';+import { gitChildEnv, GIT_PATHSPEC_ENV_VARS } from '../src/core/git-env.ts';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';++const env = gitChildEnv();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();+const dirs: string[] = [];+const scratch = (name: string) => { const dir = realpathSync(mkdtempSync(join(tmpdir(), `gbrain-7759-${name}-`))); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function put(root: string, path: string, body: string): void {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), body);+}+function script(path: string, body: string): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `#!/bin/sh\n${body}`);+ chmodSync(path, 0o755);+}++/** A checkout on main with `files` committed, its own core.hooksPath outside the worktree (a global one cannot hide it), and optionally a bare origin. */+function checkout(files: Record<string, string>, remote: boolean): { root: string; bare: string | null; hooks: string; log: string } {+ const dir = scratch('repo');+ const root = join(dir, 'work');+ git(dir, 'init', '-q', '-b', 'main', root);+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'core.hooksPath', join(dir, 'hooks'));+ for (const [path, body] of Object.entries({ 'seed.md': 'seed\n', ...files })) put(root, path, body);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');+ let bare: string | null = null;+ if (remote) {+ bare = join(dir, 'origin.git');+ git(dir, 'init', '-q', '--bare', '-b', 'main', bare);+ git(root, 'remote', 'add', 'origin', bare);+ git(root, 'push', '-q', '-u', 'origin', 'main');+ }+ return { root, bare, hooks: join(dir, 'hooks'), log: join(dir, 'hooks.log') };+}+const logLines = (log: string) => existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean) : [];+const commitPaths = (root: string, rev = 'HEAD') => git(root, 'show', '--name-only', '--format=', '-z', rev).split('\0').filter(Boolean).sort();+const cli = (root: string, args: string[], extra: Record<string, string> = {}) =>+ runCli(['git', 'commit-push', '--path', root, '--json', ...args], { home: scratch('home'), env: { GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1', ...extra } });++const CONFLICTED = '{\n<<<<<<< ours\n "a": 1\n=======\n "a": 2\n>>>>>>> theirs\n}\n';++/** The issue's guard: lists staged JSON files by glob pathspec and refuses any that holds conflict markers. */+function installGlobGuard(hooks: string, log: string): void {+ script(join(hooks, 'pre-commit'), `files=$(git diff --cached --name-only -- '*.json' '*.jsonl')+echo "pre-commit files=[$(echo $files)]" >> '${log}'+for f in $files; do+ if git show ":$f" | grep -qE '^(<<<<<<<|=======|>>>>>>>)'; then echo "pre-commit guard: conflict markers in $f" >&2; exit 1; fi+done+exit 0+`);+}++test('gitChildEnv drops Git\'s global pathspec switches; a caller may still set one explicitly', () => {+ const source = { ...Object.fromEntries(GIT_PATHSPEC_ENV_VARS.map(key => [key, '1'])), PATH: '/usr/bin' };+ expect(gitChildEnv({}, source)).toEqual({ PATH: '/usr/bin' });+ expect(gitChildEnv({ GIT_LITERAL_PATHSPECS: '1' }, source)).toEqual({ PATH: '/usr/bin', GIT_LITERAL_PATHSPECS: '1' });+});++describe('a glob-pathspec pre-commit guard holds for gbrain git commit-push', () => {+ test('a plain git commit and the door commit both refuse; nothing reaches HEAD, the index or the remote', async () => {+ const { root, bare, hooks, log } = checkout({}, true);+ installGlobGuard(hooks, log);+ put(root, 'bad.json', CONFLICTED);+ const head = git(root, 'rev-parse', 'HEAD');+ git(root, 'add', 'bad.json');+ expect(() => git(root, 'commit', '-m', 'plain')).toThrow();+ git(root, 'reset', '-q', '--', 'bad.json');++ const refused = await cli(root, ['-m', 'bad', '--', 'bad.json']);+ expect(refused.exitCode).toBe(1);+ const envelope = JSON.parse(refused.stdout) as { code: string; message: string; suggestion: string };+ expect(envelope.code).toBe('git_unavailable');+ expect(envelope.message).toContain('git commit failed');+ expect(envelope.suggestion).toContain('pre-commit guard: conflict markers in bad.json');+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(bare!, 'rev-parse', 'main')).toBe(head);+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('?? bad.json');+ expect(logLines(log)).toEqual(['pre-commit files=[bad.json]', 'pre-commit files=[bad.json]']);++ put(root, 'good.json', '{ "a": 1 }\n');+ const pushed = await cli(root, ['-m', 'good', '--', 'good.json']);+ expect(pushed.exitCode).toBe(0);+ expect(JSON.parse(pushed.stdout)).toMatchObject({ outcome: 'pushed', confirmed: 'push', paths: ['good.json'] });+ expect(commitPaths(bare!, 'main')).toEqual(['good.json']);+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('?? bad.json');+ });++ test('a checkout with no remote refuses too and commits nothing', async () => {+ const { root, hooks, log } = checkout({}, false);+ installGlobGuard(hooks, log);+ put(root, 'notes/bad.jsonl', CONFLICTED);+ const head = git(root, 'rev-parse', 'HEAD');+ const refused = await cli(root, ['-m', 'bad', '--', 'notes/bad.jsonl']);+ expect(refused.exitCode).toBe(1);+ expect(JSON.parse(refused.stdout)).toMatchObject({ code: 'git_unavailable' });+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('?? notes/bad.jsonl');+ expect(logLines(log)).toEqual(['pre-commit files=[notes/bad.jsonl]']);+ });+});++describe('no hook or door child sees GIT_LITERAL_PATHSPECS', () => {+ const probe = (log: string, name: string) => `echo "${name} \${GIT_LITERAL_PATHSPECS-unset}" >> '${log}'\n`;++ for (const inherited of [undefined, '1']) {+ test(`commit-push hooks${inherited ? ' when gbrain\'s own environment sets it' : ''}; a post-commit hook's :(literal) pathspec works`, async () => {+ const { root, bare, hooks, log } = checkout({ 'tracked.txt': 'v1\n' }, true);+ for (const name of ['pre-commit', 'commit-msg', 'pre-push']) script(join(hooks, name), probe(log, name));+ script(join(hooks, 'post-commit'), `${probe(log, 'post-commit')}echo regenerated >> tracked.txt+git add -- ':(literal)tracked.txt' && echo "post-commit add ok" >> '${log}'+`);+ put(root, 'notes/a.md', 'a\n');+ const result = await cli(root, ['-m', 'add a', '--', 'notes/a.md'], inherited ? { GIT_LITERAL_PATHSPECS: inherited } : {});+ expect(result.exitCode).toBe(0);+ expect(JSON.parse(result.stdout)).toMatchObject({ outcome: 'pushed', paths: ['notes/a.md'] });+ expect(commitPaths(bare!, 'main')).toEqual(['notes/a.md']);+ expect(logLines(log)).toEqual(['pre-commit unset', 'commit-msg unset', 'post-commit unset', 'post-commit add ok', 'pre-push unset']);+ expect(git(root, 'status', '--porcelain')).toBe('M tracked.txt');+ });+ }++ /** A clean filter on *.md that records what its process inherited, and repository hooks that would record a run. */+ function doorProbes(root: string, hooks: string, log: string): void {+ const filter = join(dirname(root), 'clean-probe');+ script(filter, `${probe(log, 'clean')}exec cat\n`);+ git(root, 'config', 'filter.probe.clean', filter);+ put(root, '.gitattributes', '*.md filter=probe\n');+ git(root, 'add', '.gitattributes'); git(root, 'commit', '-qm', 'attributes');+ for (const name of ['pre-commit', 'commit-msg', 'post-commit', 'reference-transaction']) script(join(hooks, name), probe(log, `hook ${name}`));+ }++ test('the Git effect and its push, also when gbrain\'s own environment sets it; the session runs no repository hook', async () => {+ const { root, bare, hooks, log } = checkout({}, true);+ doorProbes(root, hooks, log);+ const receive = join(dirname(root), 'receive-probe');+ script(receive, `${probe(log, 'receive-pack')}exec git-receive-pack "$@"\n`);+ git(root, 'config', 'remote.origin.receivepack', receive);+ for (const inherited of [undefined, '1']) {+ rmSync(log, { force: true });+ put(root, 'notes/a.md', `a ${inherited ?? 'none'}\n`);+ await withEnv({ GIT_LITERAL_PATHSPECS: inherited }, async () => {+ expect((await commitGitTargets(root, ['notes/a.md'])).get('notes/a.md')).toEqual({ git: 'committed' });+ expect(await pushGitRoot(root)).toEqual({ push: 'committed' });+ });+ expect(git(bare!, 'show', 'main:notes/a.md')).toBe(`a ${inherited ?? 'none'}`);+ const lines = logLines(log);+ expect(lines.filter(line => line.startsWith('hook '))).toEqual([]);+ expect([...new Set(lines)]).toEqual(['clean unset', 'receive-pack unset']);+ }+ });++ test('the plumbing door commit, also when gbrain\'s own environment sets it; no repository hook runs', async () => {+ const { root, hooks, log } = checkout({ 'notes/a.md': 'a\n' }, false);+ doorProbes(root, hooks, log);+ for (const inherited of [undefined, '1']) {+ rmSync(log, { force: true });+ put(root, 'notes/a.md', `a ${inherited ?? 'none'}\n`);+ await withEnv({ GIT_LITERAL_PATHSPECS: inherited }, async () => {+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: hashFile(join(root, 'notes/a.md')) }])).toBe(git(root, 'rev-parse', 'HEAD'));+ });+ expect(git(root, 'show', 'HEAD:notes/a.md')).toBe(`a ${inherited ?? 'none'}`);+ expect([...new Set(logLines(log))]).toEqual(['clean unset']);+ expect(git(root, 'status', '--porcelain')).toBe('');+ }+ });+});++describe('paths named with glob characters or a leading colon match literally', () => {+ /** Each literal name has a decoy its glob or pathspec-magic reading would match instead. */+ const LITERAL = ['*.md', 'a?.md', '[x].md', ':lead.md', 'd/*.md'];+ const DECOYS = ['ab.md', 'x.md', 'lead.md', 'd/y.md'];+ const seed = Object.fromEntries([...LITERAL, ...DECOYS, ':gone.md', 'gone.md'].map(path => [path, `${path} v1\n`]));+ /** Edits every literal name and decoy, adds `new[1].md` beside the decoy `new1.md`, and removes `:gone.md`; returns the paths to commit. */+ function edit(root: string): string[] {+ for (const path of [...LITERAL, ...DECOYS]) put(root, path, `${path} v2\n`);+ put(root, 'new[1].md', 'new\n'); put(root, 'new1.md', 'decoy\n');+ unlinkSync(join(root, ':gone.md'));+ return [...LITERAL, 'new[1].md', ':gone.md'];+ }+ const leftOver = (root: string) => execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all'], { encoding: 'utf8', env }).split('\n').filter(Boolean).sort();+ const DECOYS_LEFT = [' M ab.md', ' M d/y.md', ' M lead.md', ' M x.md', '?? new1.md'];+ const COMMITTED = ['*.md', ':gone.md', ':lead.md', '[x].md', 'a?.md', 'd/*.md', 'new[1].md'];+ const door = (root: string, paths: string[]) => commitThroughDoor(root, paths.map(path => ({ path: join(root, path), planned: hashFile(join(root, path)) })));++ test('commit-push', () => {+ const { root, bare } = checkout(seed, true);+ const paths = edit(root);+ expect(commitAndPush({ repo: root, cwd: root, paths, message: 'literal names' })).toMatchObject({ outcome: 'pushed', confirmed: 'push' });+ expect(commitPaths(bare!, 'main')).toEqual(COMMITTED);+ expect(git(bare!, 'show', 'main:*.md')).toBe('*.md v2');+ expect(leftOver(root)).toEqual(DECOYS_LEFT);+ });++ test('the Git effect', async () => {+ const { root } = checkout(seed, false);+ const paths = edit(root);+ const results = await commitGitTargets(root, paths);+ for (const path of paths) expect(results.get(path)).toEqual({ git: 'committed' });+ expect(commitPaths(root)).toEqual(COMMITTED);+ expect(leftOver(root)).toEqual(DECOYS_LEFT);+ });++ test('the plumbing door', async () => {+ const { root } = checkout(seed, false);+ expect(await door(root, edit(root))).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(commitPaths(root)).toEqual(COMMITTED);+ expect(git(root, 'show', 'HEAD::lead.md')).toBe(':lead.md v2');+ expect(leftOver(root)).toEqual(DECOYS_LEFT);+ });++ test('the plumbing door asks the ignore rules about a new colon-named file, not the decoy its magic reading names', async () => {+ const { root } = checkout({ '.gitignore': '*lead.md\n!:lead.md\n' }, false);+ put(root, ':lead.md', 'colon page\n');+ expect(await door(root, [':lead.md'])).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(commitPaths(root)).toEqual([':lead.md']);+ });+});