Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(git): Git children drop inherited repository-locating variables; checkout discovery stops at a foreign world-writable ancestor (CSO G4, G3)
time-attack9a6af2b209a0
diff --git a/src/core/bootstrap/status.ts b/src/core/bootstrap/status.tsindex f330621366..288ac6207b 100644--- a/src/core/bootstrap/status.ts+++ b/src/core/bootstrap/status.ts@@ -49,6 +49,7 @@ import {GBRAIN_HOOK_MARKER_KEY,GBRAIN_HOOK_MARKER_VALUE,} from './host-specs.ts';+import { gitChildEnv } from '../git-env.ts';// ---------------------------------------------------------------------------// The phase list [D5] — single TS source of truth@@ -100,6 +101,7 @@ interface PhaseSpec {export function gitOriginUrl(ws: string): string | null {try {const out = execFileSync('git', ['-C', ws, 'remote', 'get-url', 'origin'], {+ env: gitChildEnv(),stdio: ['ignore', 'pipe', 'ignore'],timeout: 5_000,})diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 3f44bdace8..d407de7e8d 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -66,6 +66,7 @@ import {startResolveIpcServer,} from '../context/resolve-ipc.ts';import { assembleTurnContext } from '../context/turn-context.ts';+import { gitChildEnv } from '../git-env.ts';// ---------------------------------------------------------------------------// Types@@ -326,6 +327,7 @@ export function checkWritebackContract(ws: string): VerifyCheck {function trackedWorkspaceFiles(ws: string): { files: string[]; via: 'git' | 'fallback' } {try {const out = execFileSync('git', ['-C', ws, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], {+ env: gitChildEnv(),stdio: ['ignore', 'pipe', 'ignore'],timeout: 15_000,maxBuffer: 16 * 1024 * 1024,@@ -393,6 +395,7 @@ function checkMcpJsonHygiene(ws: string): VerifyCheck {if (!existsSync(join(ws, '.mcp.json'))) return { id, ok: true, detail: 'no .mcp.json in the workspace' };try {execFileSync('git', ['-C', ws, 'ls-files', '--error-unmatch', '.mcp.json'], {+ env: gitChildEnv(),stdio: 'ignore', timeout: 5_000,});} catch {diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 98ad753385..da31340346 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -50,6 +50,7 @@ import { readFix } from './ops/op-fix.ts';// Bundled into the --compile binary as the fallback taxonomy for repos that// don't ship their own — see resolveFilingRules().import filingRulesDoc from '../../skills/_brain-filing-rules.json';+import { gitChildEnv } from './git-env.ts';export { execFileBounded, type BoundedExecOptions } from './bounded-child-exec.ts';@@ -392,7 +393,7 @@ function patchResolverFile(repoPath: string, dryRun: boolean): { status: StepStafunction gitDirPath(repoPath: string, rel: string): string {try {const p = execFileSync('git', ['-C', repoPath, 'rev-parse', '--git-path', rel], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();if (p) return isAbsolute(p) ? p : join(repoPath, p);} catch { /* fall through to the classic layout */ }@@ -408,7 +409,7 @@ function resolveHooksDir(repoPath: string): { dir: string; tracked: boolean } {let hooksPath = '';try {hooksPath = execFileSync('git', ['-C', repoPath, 'config', '--get', 'core.hooksPath'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();} catch { /* unset — normal */ }if (hooksPath) {@@ -503,7 +504,7 @@ function durabilityProbeFailure(detail: string): OperationError {/** A git probe that does not block the event loop. Exit 1 is an unset key for `config --get`; every other failure throws. */async function gitProbe(repoPath: string, args: string[]): Promise<string> {const { error, stdout } = await execFileBounded('git', ['-C', repoPath, ...args],- { timeout: 10_000, env: { ...process.env, ...GIT_ENV, LC_ALL: 'C', LANGUAGE: 'C' } });+ { timeout: 10_000, env: gitChildEnv({ ...GIT_ENV, LC_ALL: 'C', LANGUAGE: 'C' }) });if (!error) return stdout.trim();if (error.code === 1 && args[0] === 'config' && args[1] === '--get') return '';const status = typeof error.code === 'number' ? `exit ${error.code}` : typeof error.code === 'string' && /^[A-Z_]+$/.test(error.code) ? error.code : 'no exit status';@@ -562,7 +563,7 @@ export function commitWriteThroughFile(try {const rel = relative(repoPath, absPath);if (!rel || rel.startsWith('..') || isAbsolute(rel)) return false;- const gitOpts = { stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV } } as const;+ const gitOpts = { stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }) } as const;execFileSync('git', ['-C', repoPath, 'add', '--', rel], gitOpts);execFileSync('git', ['-C', repoPath, 'commit', '-m', `gbrain: ${action} ${slug}`, '--', rel], gitOpts);return true;@@ -646,19 +647,19 @@ function gitConfigGet(repoPath: string, key: string, localOnly = false): stringtry {const scope = localOnly ? ['--local'] : [];return execFileSync('git', ['-C', repoPath, 'config', ...scope, '--get', key], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();} catch { return ''; }}function gitConfigSet(repoPath: string, key: string, value: string): void {execFileSync('git', ['-C', repoPath, 'config', key, value], {- stdio: 'ignore', timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: 'ignore', timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),});}function gitConfigUnset(repoPath: string, key: string): void {try {execFileSync('git', ['-C', repoPath, 'config', '--unset-all', key], {- stdio: 'ignore', timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: 'ignore', timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),});} catch { /* not set */ }}@@ -666,7 +667,7 @@ function gitConfigUnset(repoPath: string, key: string): void {function remoteHost(repoPath: string): string {try {const url = execFileSync('git', ['-C', repoPath, 'remote', 'get-url', 'origin'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();return new URL(url).hostname || 'github.com';} catch { return 'github.com'; }@@ -950,7 +951,7 @@ function isGitRepo(repoPath: string): boolean {function resolveRepoRoot(path: string): string {try {return execFileSync('git', ['-C', path, 'rev-parse', '--show-toplevel'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();} catch {throw new Error(`not a git repo: ${path}`);@@ -960,7 +961,7 @@ function resolveRepoRoot(path: string): string {export function currentBranch(repoPath: string): string {try {return execFileSync('git', ['-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();} catch { return 'HEAD'; }}@@ -968,7 +969,7 @@ export function currentBranch(repoPath: string): string {function headSha(repoPath: string): string {try {return execFileSync('git', ['-C', repoPath, 'rev-parse', 'HEAD'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();} catch { return ''; }}@@ -1066,9 +1067,9 @@ function commitScaffolding(repoPath: string, branch: string, redact: (s: string)const resolver = findResolverFile(repoPath);if (resolver) paths.push(relative(repoPath, resolver));try {- execFileSync('git', ['-C', repoPath, 'add', '--', ...paths], { stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV } });+ execFileSync('git', ['-C', repoPath, 'add', '--', ...paths], { stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }) });const staged = execFileSync('git', ['-C', repoPath, 'diff', '--cached', '--name-only'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();if (!staged) return { status: 'ok', detail: 'scaffolding already committed' };// #3925: suppress hooks on THIS commit. Step 3 already installed the@@ -1080,10 +1081,10 @@ function commitScaffolding(repoPath: string, branch: string, redact: (s: string)// push below the ONLY push for the scaffolding commit; every later// operator/agent commit still fires the hook normally.execFileSync('git', ['-C', repoPath, '-c', 'core.hooksPath=/dev/null', 'commit', '-m', 'chore(gbrain): install brain durability scaffolding'], {- stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV },+ stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),});execFileSync('git', ['-C', repoPath, ...['-c', 'http.followRedirects=false'], 'push', 'origin', `HEAD:${branch}`], {- stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000, env: { ...process.env, ...GIT_ENV_AUTH },+ stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000, env: gitChildEnv({ ...GIT_ENV_AUTH }),});return { status: 'fixed', detail: 'committed + pushed durability scaffolding' };} catch (e) {@@ -1095,7 +1096,7 @@ function headMatchesOrigin(repoPath: string, branch: string): boolean {try {const local = headSha(repoPath);const remote = execFileSync('git', ['-C', repoPath, 'rev-parse', `origin/${branch}`], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();return !!local && local === remote;} catch { return false; }diff --git a/src/core/bun-floor.ts b/src/core/bun-floor.tsindex 151c8a597c..f6a4820f02 100644--- a/src/core/bun-floor.ts+++ b/src/core/bun-floor.ts@@ -25,6 +25,7 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import { VERSION } from '../version.ts';import { BUN_VERSION_RE, bunVersionMeets, compareBunVersions } from './runtime-version.ts';+import { gitChildEnv } from './git-env.ts';/** Exit code of a `gbrain upgrade` refused for the Bun floor (sysexits EX_CONFIG). */export const BUN_FLOOR_EXIT_CODE = 78;@@ -64,7 +65,7 @@ function git(repoRoot: string, args: string[], timeout = 10_000): string {stdio: ['ignore', 'pipe', 'ignore'],timeout,maxBuffer: PACKAGE_BODY_LIMIT + 1,- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },+ env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0' }),});}diff --git a/src/core/context/compiled-core.ts b/src/core/context/compiled-core.tsindex d652cb9bf2..21788f13b1 100644--- a/src/core/context/compiled-core.ts+++ b/src/core/context/compiled-core.ts@@ -9,10 +9,11 @@ import { appendFileSync, existsSync, readFileSync } from 'node:fs';import { dirname, isAbsolute, join, relative, resolve } from 'node:path';import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';import { resolveGbrainHome } from '../gbrain-home.ts';+import { gitChildEnv } from '../git-env.ts';function git(cwd: string, args: string[]): string | null {try {- return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ return execFileSync('git', args, { env: gitChildEnv(), cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();} catch {return null;}diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex a92ff4d82c..6c9a8b9ee2 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -19,6 +19,7 @@ import { relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';import { deletePageThrough, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';+import { gitChildEnv } from '../git-env.ts';export const DERIVED_WRITE_THROUGH_KEYS = {extract_atoms: 'cycle.extract_atoms.write_through',@@ -37,7 +38,7 @@ export async function derivedWriteThroughEnabled(engine: BrainEngine, phase: keyfunction gitIgnores(root: string, filePath: string): boolean {try {- execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relative(root, filePath)], { stdio: 'ignore' });+ execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relative(root, filePath)], { env: gitChildEnv(), stdio: 'ignore' });return true;} catch {return false;diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.tsindex 98335c5cda..f38dfef682 100644--- a/src/core/embed-stale-images.ts+++ b/src/core/embed-stale-images.ts@@ -18,6 +18,7 @@ import type { BrainEngine } from './engine.ts';import { importImageFile } from './import-file.ts';import { safeChunksFilter } from './search/safe-chunks.ts';import { serr } from './console-prefix.ts';+import { gitChildEnv } from './git-env.ts';export interface StaleImageSweepResult {candidates: number;@@ -91,7 +92,7 @@ function locateSourceFile(root: string, sourcePath: string, gitRoots: Map<stringif (existsSync(direct)) return direct;if (!gitRoots.has(root)) {try {- gitRoots.set(root, execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());+ gitRoots.set(root, execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());} catch { gitRoots.set(root, null); }}const gitRoot = gitRoots.get(root);diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 91e7a113e9..e440a908e8 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -60,6 +60,7 @@ import { withPageTierKept } from '../trust/fence-append.ts';import { recordTaintEdges } from '../trust/taint.ts';import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';import type { TaintInput, WriteTrust } from '../trust/tier.ts';+import { gitChildEnv } from '../git-env.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -179,7 +180,7 @@ export function gitPathState(repoPath: string, filePath: string): FactFenceGitPaconst status = execFileSync('git',['-C', repoPath, 'status', '--porcelain=v1', '--untracked-files=all', '--', rel],- { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: process.env },+ { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv() },);const lines = status.split('\n').filter((l) => l.length > 0);if (lines.length === 0) return 'clean';diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 08ba247b81..772bd0628b 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -25,6 +25,7 @@ import { gbrainPath } from '../config.ts';import type { WriteRequest } from '../persistence/model.ts';import { DELETION_INVENTORY, OUT_OF_REACH_RESIDUALS, type InventoryEntry } from '../deletion-inventory.ts';import type { PurgePlan, PurgeTarget } from './purge.ts';+import { gitChildEnv } from '../git-env.ts';export type StoreCount = Record<string, number>;export type StoreStatus = 'deleted' | 'would_remove' | 'retained_inactive' | 'unverified' | 'out_of_reach' | 'out_of_scope' | 'not_present' | 'incomplete';@@ -131,7 +132,7 @@ export async function gitResidualCommits(root: string, paths: readonly string[],const needles = [escapeFenceCell(claim).toLowerCase(), claim.toLowerCase()];return new Promise(resolve => {const child = spawn('git', ['-C', root, '--literal-pathspecs', 'log', '--all', '--format=commit %H %cI', '-p', '--no-color', '--no-ext-diff', '--', ...paths],- { stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' } });+ { stdio: ['ignore', 'pipe', 'ignore'], env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1' }) });const commits: Array<{ commit: string; committed_at: string }> = [];let current: { commit: string; committed_at: string } | null = null, bytes = 0, tail = '', bounded: string | null = null;const timer = setTimeout(() => { bounded = 'deadline'; child.kill('SIGKILL'); }, limits.ms);diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.tsindex c9ca9669a1..c817cb5edb 100644--- a/src/core/fence-repair/repair-io.ts+++ b/src/core/fence-repair/repair-io.ts@@ -51,6 +51,7 @@ import { clearCandidateParts } from './census-store.ts';import { legacyCommitStep, recordUncommittedFenceRepair } from './uncommitted.ts';import type { FenceRepairReceipt } from './receipt.ts';import type { FenceCtx, FencePage } from './types.ts';+import { gitChildEnv } from '../git-env.ts';export type FenceRepairMode = 'managed' | 'legacy' | 'db' | 'mirror';@@ -69,7 +70,7 @@ export interface FenceSource {}function inGit(root: string): boolean {- try { execFileSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], { stdio: 'ignore' }); return true; } catch { return false; }+ try { execFileSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], { env: gitChildEnv(), stdio: 'ignore' }); return true; } catch { return false; }}/**diff --git a/src/core/fence-repair/uncommitted.ts b/src/core/fence-repair/uncommitted.tsindex a3111686a8..cf5aed43ae 100644--- a/src/core/fence-repair/uncommitted.ts+++ b/src/core/fence-repair/uncommitted.ts@@ -18,6 +18,7 @@ import type { BrainEngine } from '../engine.ts';import { shellQuote } from '../agent-output.ts';import type { FenceRepairReceipt } from './receipt.ts';import { fenceRepairCommitSubject } from './receipt.ts';+import { gitChildEnv } from '../git-env.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -52,9 +53,9 @@ export async function recordUncommittedFenceRepair(engine: Exec, notice: Uncommifunction committed(root: string, path: string): boolean {if (!existsSync(root)) return true;try {- const status = execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all', '--', path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });+ const status = execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all', '--', path], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });if (status.trim()) return false;- execFileSync('git', ['-C', root, 'ls-files', '--error-unmatch', '--', path], { stdio: 'ignore' });+ execFileSync('git', ['-C', root, 'ls-files', '--error-unmatch', '--', path], { env: gitChildEnv(), stdio: 'ignore' });return true;} catch {return false;diff --git a/src/core/git-checkout.ts b/src/core/git-checkout.tsindex c67b80e6a9..72dbc8dc30 100644--- a/src/core/git-checkout.ts+++ b/src/core/git-checkout.ts@@ -10,9 +10,13 @@* not inherit those failures, so this reads only the filesystem:** - `not_git`: no `.git` entry (directory or gitdir file) at the directory or- * any ancestor, and no `GIT_DIR` in the environment.- * - `git`: a `.git` entry exists at or above the directory (or `GIT_DIR` is- * set); whether Git can use it is the Git probe's question.+ * any ancestor below the first world-writable ancestor owned by someone else+ * (POSIX). Git refuses a repository found there ("dubious ownership"), and+ * any local user can plant one in a shared directory such as `/tmp` (CSO G3).+ * An inherited `GIT_DIR` is not trusted: every Git spawn drops it+ * (`git-env.ts`, CSO G4), so it can't make a plain directory a checkout.+ * - `git`: a `.git` entry exists at or above the directory, within that+ * boundary; whether Git can use it is the Git probe's question.* - `unknown`: the directory itself is missing or not a directory, or a* lookup failed for any reason other than absence (EACCES, ELOOP, I/O).* Callers treat it like a failed Git probe.@@ -21,16 +25,18 @@* boundary); this reports `git` there and the Git probe then fails, which* callers treat as unavailable: fail closed, never "not a checkout".*/-import { lstatSync, statSync } from 'node:fs';+import { lstatSync, statSync, type Stats } from 'node:fs';import { dirname, join, resolve } from 'node:path';export type GitCheckoutClass = 'git' | 'not_git' | 'unknown';-export function classifyGitCheckout(dir: string, env: NodeJS.ProcessEnv = process.env): GitCheckoutClass {- if (env.GIT_DIR) return 'git';+export function classifyGitCheckout(dir: string, stat: (path: string) => Pick<Stats, 'uid' | 'mode' | 'isDirectory'> = statSync): GitCheckoutClass {let current = resolve(dir);+ let owner: number;try {- if (!statSync(current).isDirectory()) return 'unknown';+ const start = stat(current);+ if (!start.isDirectory()) return 'unknown';+ owner = start.uid;} catch {return 'unknown';}@@ -45,5 +51,12 @@ export function classifyGitCheckout(dir: string, env: NodeJS.ProcessEnv = procesconst parent = dirname(current);if (parent === current) return 'not_git';current = parent;+ if (process.platform === 'win32') continue;+ try {+ const ancestor = stat(current);+ if (ancestor.uid !== owner && (ancestor.mode & 0o002) !== 0) return 'not_git';+ } catch {+ return 'unknown';+ }}}diff --git a/src/core/git-env.ts b/src/core/git-env.tsnew file mode 100644index 0000000000..630836eac6--- /dev/null+++ b/src/core/git-env.ts@@ -0,0 +1,25 @@+/**+ * The environment for a Git child process (CSO G4, wave 13). A gbrain started+ * from a Git hook, or under a shell that exported `GIT_DIR`, inherits Git's+ * repository-locating variables; passed on, they make `git -C <root>` read and+ * write the repository they name instead of `<root>`, so a commit meant for a+ * brain checkout can land in another repository. Every Git spawn under+ * `src/core` builds its env here (guarded by `test/git-env-guard.test.ts`).+ * Transport and credential variables (`GIT_SSH_COMMAND`, `GIT_ASKPASS`,+ * `SSH_AUTH_SOCK`, proxies) pass through; `extra` wins over both.+ */++/** `git rev-parse --local-env-vars` (Git 2.55): the variables that locate or reconfigure one repository. */+export const GIT_LOCAL_ENV_VARS = ['GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',+ '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);++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;+ }+ return { ...env, ...extra };+}diff --git a/src/core/git-first-commit.ts b/src/core/git-first-commit.tsindex 9402d20460..e8debc3cee 100644--- a/src/core/git-first-commit.ts+++ b/src/core/git-first-commit.ts@@ -13,6 +13,7 @@import { execFileSync } from 'child_process';import { realpathSync } from 'fs';import { relative } from 'path';+import { gitChildEnv } from './git-env.ts';export interface GitFirstCommitDates {/** The first-commit date for a file under the repo, if git recorded one. */@@ -22,7 +23,7 @@ export interface GitFirstCommitDates {export function gitFirstCommitDates(dir: string): GitFirstCommitDates | null {try {const git = (args: string[], cwd: string) => execFileSync('git', ['-C', cwd, ...args],- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024, timeout: 120_000 });+ { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024, timeout: 120_000 });const top = git(['rev-parse', '--show-toplevel'], dir).trim();if (git(['rev-parse', '--is-shallow-repository'], top).trim() === 'true') return null;const dates = new Map<string, Date>();diff --git a/src/core/git-head.ts b/src/core/git-head.tsindex 1e29983bce..8c035bf03f 100644--- a/src/core/git-head.ts+++ b/src/core/git-head.ts@@ -23,6 +23,7 @@* ~/.claude/plans/system-instruction-you-are-working-eager-bird.md.*/import { execFileSync } from 'node:child_process';+import { gitChildEnv } from './git-env.ts';export type GitHeadProbe = (localPath: string) => string | null;// `null` distinguishes probe error from known-dirty (false). Doctor treats@@ -36,6 +37,7 @@ export type GitCleanProbe = (localPath: string, ignoreUntracked?: boolean) => boconst DEFAULT_HEAD_PROBE: GitHeadProbe = (localPath) => {try {const out = execFileSync('git', ['-C', localPath, 'rev-parse', 'HEAD'], {+ env: gitChildEnv(),encoding: 'utf8',timeout: 5000,stdio: ['ignore', 'pipe', 'ignore'],@@ -56,6 +58,7 @@ const DEFAULT_CLEAN_PROBE: GitCleanProbe = (localPath, ignoreUntracked) => {const args = ['-C', localPath, 'status', '--porcelain'];if (ignoreUntracked) args.push('--untracked-files=no');const out = execFileSync('git', args, {+ env: gitChildEnv(),encoding: 'utf8',timeout: 5000,stdio: ['ignore', 'pipe', 'ignore'],diff --git a/src/core/git-remote.ts b/src/core/git-remote.tsindex 4d9ec9afdb..943d59c0e8 100644--- a/src/core/git-remote.ts+++ b/src/core/git-remote.ts@@ -20,6 +20,7 @@ import { lstatSync, existsSync, readdirSync } from 'fs';import { join } from 'path';import { isInternalUrl } from './url-safety.ts';import { execFileBounded } from './bounded-child-exec.ts';+import { gitChildEnv } from './git-env.ts';/*** Git CLI accepts two flag positions:@@ -250,7 +251,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): vexecFileSync('git', args, {stdio: ['ignore', 'pipe', 'pipe'],timeout: opts.timeoutMs ?? 600_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});} catch (e) {throw new GitOperationError(@@ -279,7 +280,7 @@ export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; sigconst argv = ['-C', repoPath, ...durableSsrfFlags(), 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];const run = await execFileBounded('git', argv, {timeout: opts.timeoutMs ?? 300_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),signal: opts.signal,});if (!run.error) return;@@ -320,7 +321,7 @@ export function fetchRemote(repoPath: string, branch: string, opts: { timeoutMs?execFileSync('git', args, {stdio: ['ignore', 'pipe', 'pipe'],timeout: opts.timeoutMs ?? 30_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});} catch (e) {throw new GitOperationError(@@ -364,7 +365,7 @@ export function validateRepoState(const out = execFileSync('git', ['-C', repoPath, 'remote', 'get-url', 'origin'], {stdio: ['ignore', 'pipe', 'pipe'],timeout: 10_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});remoteUrl = out.toString().trim();} catch {@@ -379,7 +380,7 @@ export function validateRepoState(execFileSync('git', ['-C', repoPath, 'rev-parse', '--git-dir'], {stdio: ['ignore', 'pipe', 'pipe'],timeout: 10_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});return 'healthy';} catch {@@ -409,7 +410,7 @@ export function isInsideGitRepo(path: string): boolean {execFileSync('git', ['-C', path, 'rev-parse', '--show-toplevel'], {stdio: ['ignore', 'pipe', 'pipe'],timeout: 10_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});return true;} catch {@@ -434,7 +435,7 @@ function emptyTreeOid(path: string): string {input: '',stdio: ['pipe', 'pipe', 'pipe'],timeout: 10_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();}@@ -464,7 +465,7 @@ export function hasTrackedContent(path: string): boolean {const out = execFileSync('git', ['-C', path, 'rev-parse', '--verify', 'HEAD:./'], {stdio: ['ignore', 'pipe', 'pipe'],timeout: 10_000,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});return out.toString().trim() !== emptyTreeOid(path);} catch {@@ -510,7 +511,7 @@ function runGit({stdio: ['ignore', 'pipe', 'pipe'],timeout: opts.timeoutMs ?? 120_000,- env: { ...process.env, ...(opts.env ?? GIT_ENV) },+ env: gitChildEnv({ ...(opts.env ?? GIT_ENV) }),},);return out.toString().trim();@@ -532,14 +533,14 @@ export function isWorkingTreeDirty(repoPath: string): boolean {export function detectDefaultBranch(repoPath: string): string {try {const sym = execFileSync('git', ['-C', repoPath, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();if (sym.startsWith('origin/')) return sym.slice('origin/'.length);if (sym) return sym;} catch { /* origin/HEAD not set — fall through */ }try {const cur = execFileSync('git', ['-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();if (cur && cur !== 'HEAD') return cur;} catch { /* detached or no commits */ }@@ -551,7 +552,7 @@ function rebaseInProgress(repoPath: string): boolean {for (const name of ['rebase-merge', 'rebase-apply']) {try {const p = execFileSync('git', ['-C', repoPath, 'rev-parse', '--git-path', name], {- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),}).toString().trim();const abs = p.startsWith('/') ? p : join(repoPath, p);if (existsSync(abs)) return true;@@ -603,14 +604,14 @@ export function divergenceSafePull(// Abort any half-applied rebase so the tree is never left mid-rebase.try {execFileSync('git', ['-C', repoPath, 'rebase', '--abort'], {- stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV },+ stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),});} catch { /* best-effort */ }// If state STILL remains, try once more, then report regardless.if (rebaseInProgress(repoPath)) {try {execFileSync('git', ['-C', repoPath, 'rebase', '--abort'], {- stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV },+ stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),});} catch { /* best-effort */ }}@@ -646,7 +647,7 @@ export function pushProbe(execFileSync('git',['-C', repoPath, ...durableSsrfFlags(), 'push', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--dry-run', 'origin', `HEAD:${branch}`],- { stdio: ['ignore', 'pipe', 'pipe'], timeout: opts.timeoutMs ?? 60_000, env: { ...process.env, ...GIT_ENV_AUTH } },+ { stdio: ['ignore', 'pipe', 'pipe'], timeout: opts.timeoutMs ?? 60_000, env: gitChildEnv({ ...GIT_ENV_AUTH }) },);return { ok: true };} catch (e) {diff --git a/src/core/harness/install.ts b/src/core/harness/install.tsindex 32b250f745..3154408d9d 100644--- a/src/core/harness/install.ts+++ b/src/core/harness/install.ts@@ -18,6 +18,7 @@ import { assertNoSymlinks, checkedRoot, confinedPath, sha256, privateWrite } froimport { installSharedSkillsConnection } from './shared-skills.ts';import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';import { harnessSharedSkillsRoot } from './status.ts';+import { gitChildEnv } from '../git-env.ts';export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean }@@ -46,7 +47,7 @@ function nativeEntry(path: string, format: string, name: string): unknown {/** The Git working tree whose next commit would include `path`, or null when it is ignored or outside every tree. */function committingGitTree(path: string): string | null {const git = (args: string[]) => execFileSync('git', ['-C', dirname(path), ...args],- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV } }).trim();+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }) }).trim();let tree: string;try { tree = git(['rev-parse', '--show-toplevel']); } catch { return null; }try { git(['check-ignore', '-q', '--', path]); return null; } catch { return tree; }diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex 7d4616182b..6ae803b3fa 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -6,6 +6,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';/** An index lock younger than this is contention; an older one is reported as stale. */const INDEX_LOCK_GRACE_MS = 10 * 60 * 1000;@@ -32,7 +33,7 @@ const GIT_ENV = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_GLOB_Pasync function run(root: string, hooks: string, args: string[], signal?: AbortSignal) {return execFileBounded('git', ['--literal-pathspecs', '-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {- timeout: 20_000, maxBuffer: 1024 * 1024, signal, env: { ...process.env, ...GIT_ENV },+ timeout: 20_000, maxBuffer: 1024 * 1024, signal, env: gitChildEnv(GIT_ENV),});}diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.tsindex b310636203..6c82ea2f12 100644--- a/src/core/persistence/sync-blobs.ts+++ b/src/core/persistence/sync-blobs.ts@@ -8,6 +8,7 @@* `git show` per entry.*/import { execFileSync } from 'node:child_process';+import { gitChildEnv } from '../git-env.ts';/** The sync read bound (`readSyncFile`): bigger files are held without being read. */export const SYNC_READ_BOUND = 10 * 1024 ** 2;@@ -16,7 +17,7 @@ export interface TreeBlob { oid: string; size: number }function git(gitRoot: string, args: string[], input?: string, maxBuffer = 32 * 1024 ** 2): Buffer {return execFileSync('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, ...args],- { timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });+ { env: gitChildEnv(), timeout: 60_000, maxBuffer, stdio: ['pipe', 'pipe', 'pipe'], ...(input !== undefined ? { input } : {}) });}/** Blob id and size of Git paths at a commit, in chunked `ls-tree` calls (never one process per file). */diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 13ec5b41ce..27af9b4d9c 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -23,6 +23,7 @@ import { assertManagedSyncActive } from './sync-authority.ts';import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds } from './sync-holds.ts';import { readBlobContents, readTreeBlobs } from './sync-blobs.ts';+import { gitChildEnv } from '../git-env.ts';/** The page an import takes over from its previous origin: a Git rename, or a file that replaced a vanished origin at the same slug. */export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }@@ -49,7 +50,7 @@ export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gisource: { last_commit: string | null; config: Record<string, unknown> }; }export function syncGit(root: string, args: string[]): string {return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],- { encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });+ { env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });}/*** A sync file or root failed a confinement or identity check. These helpersdiff --git a/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.tsindex da6132e3f6..d4e5890d4d 100644--- a/src/core/persistence/topology-filesystem.ts+++ b/src/core/persistence/topology-filesystem.ts@@ -8,6 +8,7 @@ import { opError, OperationError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { durableSsrfFlags, GIT_ENV, GIT_SSRF_SUBCOMMAND_FLAGS, parseRemoteUrl } from '../git-remote.ts';import { persistenceHome } from './identity.ts';+import { gitChildEnv } from '../git-env.ts';export { flushDirectory as flushTopologyDirectory } from '../fs-durable.ts';const recoveryFix=(why:string):Action=>readFix(why,{argv:['gbrain','sources','writer','status','--json']});@@ -71,7 +72,7 @@ export async function cloneTopologyCheckout(url:string,destination:string,maxBytconst base=join(persistenceHome(),'empty-hooks');mkdirSync(base,{recursive:true,mode:0o700});const hooks=mkdtempSync(join(base,'clone-'));const child=spawn('git',[...durableSsrfFlags(),'-c',`core.hooksPath=${hooks}`, 'clone',...GIT_SSRF_SUBCOMMAND_FLAGS,'--depth=1','--',url,destination],- {stdio:['ignore','ignore','ignore'],detached:process.platform!=='win32',env:{...process.env,...GIT_ENV}});+ {stdio:['ignore','ignore','ignore'],detached:process.platform!=='win32',env:gitChildEnv({ ...GIT_ENV })});let failure:unknown,check:Promise<void>|undefined,stopping:Promise<void>|undefined,abandon=()=>{};const stop=(error:unknown)=>{failure??=error;diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 462a5c049f..79d24c1b3d 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -37,6 +37,7 @@ import { isPhysicalRootMetadata } from './physical-root-record.ts';import { startPersistenceConsumer } from './service.ts';import { lockTopologyPrincipal, lockTopologyRows, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';import { ACTIVE_REFRESH_STATES_SQL, CHECKOUT_EFFECT_KINDS_SQL, type WorktreeRefreshState } from './worktree-refresh-schema.ts';+import { gitChildEnv } from '../git-env.ts';export interface WorktreeRefreshRow {id: string; worktree_id: string; source_ids: string[]; principal_id: string; owner_epoch: string | number;@@ -83,7 +84,7 @@ async function withGit<T>(run: (git: (args: string[], timeoutMs?: number) => Protry {return await run(async (args, timeoutMs = 30_000) => {const { error, stdout, stderr } = await execFileBounded('git', ['-c', 'core.quotepath=false', '-c', `core.hooksPath=${hooks}`, ...args],- { timeout: timeoutMs, maxBuffer: 32 * 1024 ** 2, env: { ...process.env, ...GIT_ENV } });+ { timeout: timeoutMs, maxBuffer: 32 * 1024 ** 2, env: gitChildEnv(GIT_ENV) });const timedOut = !!error && (error.killed || typeof error.code !== 'number');return { stdout, stderr, code: error ? (typeof error.code === 'number' ? error.code : -1) : 0, timedOut };});diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsindex 3eecf383e4..e5b32de76f 100644--- a/src/core/repair/frontmatter.ts+++ b/src/core/repair/frontmatter.ts@@ -59,6 +59,7 @@ import { canonicalRepairFields, confinedRepairTarget, managedRepairRoot, prepareimport { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import type { PageSnapshot } from '../page-state/types.ts';import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';+import { gitChildEnv } from '../git-env.ts';type Mode = 'managed' | 'legacy';type RepairClass = 'safe' | 'interpretive';@@ -210,7 +211,7 @@ async function sourceRoots(engine: BrainEngine, scope: RepairScope, residuals: Rfunction markdownFiles(root: string): string[] {let paths: string[];try {- paths = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'ignore'] })+ paths = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { env: gitChildEnv(), encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'ignore'] }).split('\0').filter(Boolean);} catch {paths = (readdirSync(root, { recursive: true }) as string[]).map(path => path.split('\\').join('/'));diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.tsindex 7b8f3fe636..09577ca9db 100644--- a/src/core/repair/slug-conflicts.ts+++ b/src/core/repair/slug-conflicts.ts@@ -79,6 +79,7 @@ import { CONTENT_REPAIR_ACTOR, CONTENT_REPAIR_HOLD_CODE, contentRepairCommitSubjimport { contentPreviewArgv } from '../content-repair/hold-fix.ts';import { lineDiff } from './frontmatter.ts';import { repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairPlanOptions, type RepairResult, type RepairScope } from './core.ts';+import { gitChildEnv } from '../git-env.ts';type Tier = 'deterministic' | 'llm';type DeterministicRule = 'absent_page' | 'different_type';@@ -145,7 +146,7 @@ export function titleTokens(title: string): Set<string> {function checkoutSlugs(root: string): Set<string> {let paths: string[];try {- paths = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'ignore'] }).split('\0').filter(Boolean);+ paths = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { env: gitChildEnv(), encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'ignore'] }).split('\0').filter(Boolean);} catch {paths = (readdirSync(root, { recursive: true }) as string[]).map(path => path.split('\\').join('/'));}diff --git a/src/core/repo-visibility.ts b/src/core/repo-visibility.tsindex e6dbf26ae4..e050f7a7c3 100644--- a/src/core/repo-visibility.ts+++ b/src/core/repo-visibility.ts@@ -39,6 +39,7 @@ import { dirname, join } from 'node:path';import { ensureGbrainHome } from './gbrain-home.ts';import { durableSsrfFlags } from './git-remote.ts';import { isCredentialInjectingProxy } from './execution-env.ts';+import { gitChildEnv } from './git-env.ts';// ── Subprocess seam (canonical home; bootstrap/repo.ts re-exports) ─────────@@ -59,7 +60,7 @@ export const defaultRunner: ExecRunner = async (argv: string[]): Promise<ExecResstdout: 'pipe',stderr: 'pipe',stdin: 'ignore',- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },+ env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0' }),});const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(),diff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.tsindex 7af39032f0..4bd3a79036 100644--- a/src/core/shared-skills/migration-export.ts+++ b/src/core/shared-skills/migration-export.ts@@ -23,6 +23,7 @@ import type { Page } from '../types.ts';import { slugifyPath } from '../sync.ts';import { assertPackagedSkillSource } from './setup-source-policy.ts';import { approvedSchemaIdentity, loadActivePackForEngine, type ApprovedSchemaIdentity } from '../schema-pack/engine-resolution.ts';+import { gitChildEnv } from '../git-env.ts';export interface DatabaseContentExportOptions {root: string;@@ -257,7 +258,7 @@ export async function exportDatabaseContent(ctx: OperationContext, options: DataprivateWrite(target, content);}verifyFiles(receipt.staging_root, hashes, true);- const enclosing = spawnSync('git', ['-C', receipt.staging_root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ const enclosing = spawnSync('git', ['-C', receipt.staging_root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 });if (enclosing.status === 0) {throw opError('local_conflict', 'The export would claim an enclosing Git worktree. Choose a destination outside existing repositories.',`${root} lies inside an existing Git worktree; pass --content-root a path outside any repository.`);diff --git a/src/core/shared-skills/setup.ts b/src/core/shared-skills/setup.tsindex 1cbf517fa8..7e38f96404 100644--- a/src/core/shared-skills/setup.ts+++ b/src/core/shared-skills/setup.ts@@ -11,6 +11,7 @@ import { DEFAULT_SHARED_PACK_ID, packagedSharedSkillPolicy, packagedSharedSkillsimport { publicationEnabled, setSharedSkillPolicy } from './policy.ts';import type { BrainEngine } from '../engine.ts';import { assertPackagedSkillSource, sharedSkillSourcePolicy } from './setup-source-policy.ts';+import { gitChildEnv } from '../git-env.ts';export async function isNewContentDatabase(engine: BrainEngine): Promise<boolean> {const [row] = await engine.executeRaw<{ fresh: boolean }>("SELECT to_regclass('public.pages') IS NULL AND to_regclass('public.config') IS NULL AND to_regclass('public.persistence_brain') IS NULL AS fresh");@@ -80,7 +81,7 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Shreceipt.root = source.local_path;receipt.repository_kind = source.local_path ? 'content_directory' : 'db_only';if (source.local_path) {- const git = spawnSync('git', ['-C', source.local_path, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ const git = spawnSync('git', ['-C', source.local_path, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 });if (git.status === 0 && resolve(git.stdout.trim()) === resolve(source.local_path)) receipt.repository_kind = 'git';}receipt.pending_actions = [sourcePolicy.reason];@@ -127,7 +128,7 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Shreceipt.root = root;receipt.owned_root = prior?.owned_root ?? (!existingRoot && (!!options.fresh || !!options.root));receipt.fresh_root_activation = prior?.fresh_root_activation ?? (!existingRoot && !!options.fresh);- const gitProbe = existsSync(join(root, '.git')) ? spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 }) : null;+ const gitProbe = existsSync(join(root, '.git')) ? spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 }) : null;receipt.repository_kind = gitProbe?.status === 0 && resolve(gitProbe.stdout.trim()) === root ? 'git' : 'content_directory';const existed = existsSync(root);if (prior?.root && prior.root !== root) {@@ -176,13 +177,13 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Shthrow opError('local_conflict', 'Git initialization is allowed only in a newly owned empty content directory.',`${root} is not a new empty directory gbrain created; run gbrain init without --git and initialize Git there yourself if the user wants it.`);}- const git = spawnSync('git', ['init', '--quiet', root], { encoding: 'utf8', timeout: 15_000 });+ const git = spawnSync('git', ['init', '--quiet', root], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 });if (!git.error && git.status === 0) receipt.repository_kind = 'git';else receipt.pending_actions.push('Git initialization was unavailable; install Git and explicitly initialize this content directory later.');}if (receipt.repository_kind === 'content_directory' && !receipt.pending_actions.length) receipt.pending_actions.push('Optional: initialize Git explicitly; configure an off-host backup separately.');if (receipt.owned_root && receipt.repository_kind === 'content_directory') {- const enclosing = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ const enclosing = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { env: gitChildEnv(), encoding: 'utf8', timeout: 15_000 });if (enclosing.status === 0 && resolve(enclosing.stdout.trim()) !== root) {throw opError('local_conflict', 'The new content directory is inside another Git worktree. Choose a separate root or explicitly initialize Git here; setup will not claim its parent repository.',`${root} is inside the Git worktree ${enclosing.stdout.trim()}. Pass --content-root a path outside any repository, or add --git so the content directory gets its own repository.`);diff --git a/src/core/skill-fix-gates.ts b/src/core/skill-fix-gates.tsindex d813c83336..75ec2c18d7 100644--- a/src/core/skill-fix-gates.ts+++ b/src/core/skill-fix-gates.ts@@ -28,6 +28,7 @@import { execFileSync } from 'node:child_process';import { dirname } from 'node:path';+import { gitChildEnv } from './git-env.ts';// ---------------------------------------------------------------------------// Code-fence guard@@ -76,6 +77,7 @@ export type WorkingTreeStatus = 'clean' | 'dirty' | 'not_a_repo';export function getWorkingTreeStatus(skillPath: string): WorkingTreeStatus {try {const out = execFileSync('git', ['status', '--porcelain', '--', skillPath], {+ env: gitChildEnv(),encoding: 'utf-8',stdio: ['ignore', 'pipe', 'ignore'],cwd: dirname(skillPath),diff --git a/src/core/skillopt/apply-edits.ts b/src/core/skillopt/apply-edits.tsindex cc12ec155a..423a868793 100644--- a/src/core/skillopt/apply-edits.ts+++ b/src/core/skillopt/apply-edits.ts@@ -28,6 +28,7 @@ import * as fs from 'node:fs';import { execFileSync } from 'node:child_process';import { dirname } from 'node:path';import type { EditOp, EditResult, EditRejectionReason } from './types.ts';+import { gitChildEnv } from '../git-env.ts';// ─── Public API ───────────────────────────────────────────────────────────@@ -289,12 +290,13 @@ export function getWorkingTreeStatusForFile(filePath: string): 'clean' | 'dirty'const cwd = dirname(filePath);// First check we're in a repo.try {- execFileSync('git', ['rev-parse', '--git-dir'], { cwd, stdio: 'pipe' });+ execFileSync('git', ['rev-parse', '--git-dir'], { env: gitChildEnv(), cwd, stdio: 'pipe' });} catch {return 'not_a_repo';}// Then check status on this specific file.const out = execFileSync('git', ['status', '--porcelain', '--', filePath], {+ env: gitChildEnv(),cwd,encoding: 'utf8',stdio: 'pipe',diff --git a/src/core/skillpack/bundle.ts b/src/core/skillpack/bundle.tsindex 9098b57e2e..7551344220 100644--- a/src/core/skillpack/bundle.ts+++ b/src/core/skillpack/bundle.ts@@ -12,6 +12,7 @@ import { join, dirname, isAbsolute, resolve } from 'path';import { fileURLToPath } from 'url';import { parseMarkdown } from '../markdown.ts';+import { gitChildEnv } from '../git-env.ts';export interface BundleManifest {name: string;@@ -374,7 +375,7 @@ export function changedSlugsSinceVersion(const probe = spawnSync('git',['-C', gbrainRoot, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`],- { encoding: 'utf-8' },+ { env: gitChildEnv(), encoding: 'utf-8' },);if (probe.status !== 0) continue;@@ -390,7 +391,7 @@ export function changedSlugsSinceVersion('--','skills/',],- { encoding: 'utf-8' },+ { env: gitChildEnv(), encoding: 'utf-8' },);if (log.status !== 0) return null;diff --git a/src/core/skillpack/endorse.ts b/src/core/skillpack/endorse.tsindex 3237371e4e..f6a696dbd8 100644--- a/src/core/skillpack/endorse.ts+++ b/src/core/skillpack/endorse.ts@@ -28,6 +28,7 @@ import {type EndorsementsFile,type RegistryTier,} from './registry-schema.ts';+import { gitChildEnv } from '../git-env.ts';export interface EndorseOptions {/** Absolute path to a clone of the registry repo. */@@ -185,14 +186,16 @@ export function runEndorse(opts: EndorseOptions): EndorseResult {let commitSha: string | null = null;try {execFileSync('git', ['-C', opts.registryRepoRoot, 'add', 'endorsements.json'], {+ env: gitChildEnv(),encoding: 'utf-8',});execFileSync('git',['-C', opts.registryRepoRoot, 'commit', '-m', `endorse: ${opts.packName} -> ${tier}`],- { encoding: 'utf-8' },+ { env: gitChildEnv(), encoding: 'utf-8' },);commitSha = execFileSync('git', ['-C', opts.registryRepoRoot, 'rev-parse', '--short', 'HEAD'], {+ env: gitChildEnv(),encoding: 'utf-8',}).trim();} catch (err) {@@ -206,6 +209,7 @@ export function runEndorse(opts: EndorseOptions): EndorseResult {if (opts.push) {try {execFileSync('git', ['-C', opts.registryRepoRoot, 'push', 'origin', 'HEAD'], {+ env: gitChildEnv(),encoding: 'utf-8',});pushed = true;diff --git a/src/core/skillpack/remote-source.ts b/src/core/skillpack/remote-source.tsindex 9ddbf2a0c3..bfc7e49460 100644--- a/src/core/skillpack/remote-source.ts+++ b/src/core/skillpack/remote-source.ts@@ -29,6 +29,7 @@ import { isAbsolute, join, resolve } from 'path';import { gbrainPath } from '../config.ts';import { GIT_SSRF_FLAGS, RemoteUrlError, cloneRepo, parseRemoteUrl } from '../git-remote.ts';import { extractTarball, fileSha256 } from './tarball.ts';+import { gitChildEnv } from '../git-env.ts';/** Kinds of third-party source we accept. */export type ResolvedSourceKind = 'git' | 'tarball' | 'local';@@ -149,7 +150,7 @@ function resolveRemoteHead(url: string, branch: string | undefined): string {try {const output = execFileSync('git', argv, {encoding: 'utf-8',- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },+ env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0' }),timeout: 60_000,});const firstLine = output.split('\n').find((l) => l.trim().length > 0);@@ -237,6 +238,7 @@ function resolveGitSource(let cloneSha: string;try {cloneSha = execFileSync('git', ['rev-parse', 'HEAD'], {+ env: gitChildEnv(),cwd: stageDir,encoding: 'utf-8',timeout: 30_000,diff --git a/src/core/source-health.ts b/src/core/source-health.tsindex e7c15ffe16..8cb2500ecd 100644--- a/src/core/source-health.ts+++ b/src/core/source-health.ts@@ -27,6 +27,7 @@ import { parseSourceConfig, type SourceRow } from './sources-load.ts';import { isSourceUnchangedSinceSync } from './git-head.ts';import { resolveHoursEnv } from './env-number.ts';import { isSyncDisabledConfig } from './sync-policy.ts';+import { gitChildEnv } from './git-env.ts';export interface SourceMetrics {source_id: string;@@ -123,6 +124,7 @@ export function newestCommitMs(localPath: string | null): number | null {if (!localPath) return null;try {const out = execFileSync('git', ['-C', localPath, 'log', '-1', '--format=%ct'], {+ env: gitChildEnv(),encoding: 'utf8',timeout: 10_000,stdio: ['ignore', 'pipe', 'ignore'],@@ -151,6 +153,7 @@ export function commitTimeMs(localPath: string | null, sha: string | null): numbif (!localPath || !sha) return null;try {const out = execFileSync('git', ['-C', localPath, 'show', '-s', '--format=%ct', sha], {+ env: gitChildEnv(),encoding: 'utf8',timeout: 10_000,stdio: ['ignore', 'pipe', 'ignore'],diff --git a/src/core/sync-delta.ts b/src/core/sync-delta.tsindex 166eb81dde..1e35695064 100644--- a/src/core/sync-delta.ts+++ b/src/core/sync-delta.ts@@ -33,6 +33,7 @@*/import { execFileSync } from 'node:child_process';import { buildSyncManifest, type SyncManifest } from './sync.ts';+import { gitChildEnv } from './git-env.ts';/** Runs a git subcommand in `repoPath` and returns trimmed stdout (throws on failure). */export type GitRunner = (repoPath: string, args: string[]) => string;@@ -43,6 +44,7 @@ export type GitRunner = (repoPath: string, args: string[]) => string;// would ENOBUFS-crash the sync with no log line).const DEFAULT_GIT_RUNNER: GitRunner = (repoPath, args) =>execFileSync('git', ['-c', 'core.quotepath=false', '-C', repoPath, ...args], {+ env: gitChildEnv(),encoding: 'utf-8',timeout: 30_000,maxBuffer: 100 * 1024 * 1024,diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex 61b983765c..61266bedcb 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -6,6 +6,7 @@import { execFileSync } from 'child_process';import { parseDurationSeconds } from './sync-concurrency.ts';import { resolveStallAbortSecondsFromEnv } from './stall-env.ts';+import { gitChildEnv } from './git-env.ts';/*** #2828 full-sync reconcile safety-valve thresholds. A reconcile that would@@ -88,7 +89,7 @@ export function listEverCommittedPaths(repoPath: string): Set<string> | null {'git',['-C', repoPath, '-c', 'core.quotepath=off', 'log', '--all', '--no-renames','--diff-filter=A', '--format=', '--name-only'],- { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },+ { env: gitChildEnv(), encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },);} catch {return null;diff --git a/src/core/sync-upstream.ts b/src/core/sync-upstream.tsindex 2bf9040e01..f9d30fc09d 100644--- a/src/core/sync-upstream.ts+++ b/src/core/sync-upstream.ts@@ -13,6 +13,7 @@ import { statSync } from 'node:fs';import type { BrainEngine } from './engine.ts';import { ERROR_CATALOGUE } from './error-catalogue.ts';import { parseSourceConfig, sourceConfigHasRemoteUrl } from './sources-load.ts';+import { gitChildEnv } from './git-env.ts';export const UPSTREAM_OBSERVATION_MAX_AGE_HOURS = 24;@@ -23,7 +24,7 @@ export interface UpstreamObservation { checkedAt: Date; commit: string; behind:function git(root: string, args: string[]): string | null {try {- return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;+ return execFileSync('git', ['-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;} catch {return null;}diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 647ebce48c..e42b2d479a 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -75,6 +75,7 @@ import {type SecretFinding,} from './secret-scan.ts';import { shellQuote } from './mcp-registration.ts';+import { gitChildEnv } from './git-env.ts';// ── Types ───────────────────────────────────────────────────────────────────@@ -292,7 +293,7 @@ function git(stdio: ['ignore', 'pipe', 'pipe'],timeout: opts.timeoutMs ?? 60_000,maxBuffer: 64 * 1024 * 1024,- env: { ...process.env, ...(opts.auth ? GIT_ENV_AUTH : GIT_ENV) },+ env: gitChildEnv({ ...(opts.auth ? GIT_ENV_AUTH : GIT_ENV) }),}).toString();}@@ -310,7 +311,7 @@ function gitBuffer(root: string, args: string[], timeoutMs = 60_000): Buffer {stdio: ['ignore', 'pipe', 'pipe'],timeout: timeoutMs,maxBuffer: 64 * 1024 * 1024,- env: { ...process.env, ...GIT_ENV },+ env: gitChildEnv({ ...GIT_ENV }),});}diff --git a/test/git-checkout.test.ts b/test/git-checkout.test.tsindex 66f734b9a2..9fd86e6a5c 100644--- a/test/git-checkout.test.ts+++ b/test/git-checkout.test.ts@@ -1,44 +1,83 @@/** #6210 (fix wave 12, W1.1): the filesystem-only "is this a Git checkout" classifier. */import { afterEach, expect, test } from 'bun:test';-import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { classifyGitCheckout } from '../src/core/git-checkout.ts';+import { withEnv } from './helpers/with-env.ts';const dirs: string[] = [];const scratch = () => { const dir = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-git-checkout-'))); dirs.push(dir); return dir; };afterEach(() => { for (const dir of dirs.splice(0)) { try { chmodSync(dir, 0o755); } catch {} rmSync(dir, { recursive: true, force: true }); } });-const noGitDir = {} as NodeJS.ProcessEnv;test('a plain directory with no .git at or above it is not a checkout', () => {- expect(classifyGitCheckout(join(scratch()), noGitDir)).toBe('not_git');+ expect(classifyGitCheckout(join(scratch()))).toBe('not_git');});test('a .git directory or gitdir file at or above the directory makes it a checkout, whatever it contains', () => {const repo = scratch();mkdirSync(join(repo, '.git'));mkdirSync(join(repo, 'a', 'b'), { recursive: true });- expect(classifyGitCheckout(join(repo, 'a', 'b'), noGitDir)).toBe('git');+ expect(classifyGitCheckout(join(repo, 'a', 'b'))).toBe('git');const linked = scratch();writeFileSync(join(linked, '.git'), 'gitdir: /nowhere\n');- expect(classifyGitCheckout(linked, noGitDir)).toBe('git');+ expect(classifyGitCheckout(linked)).toBe('git');});-test('GIT_DIR in the environment defers to Git', () => {- expect(classifyGitCheckout(scratch(), { GIT_DIR: '/elsewhere/.git' })).toBe('git');+test('CSO G4: an inherited GIT_DIR does not make a plain directory a checkout', async () => {+ const other = scratch();+ mkdirSync(join(other, '.git'));+ const plain = scratch();+ await withEnv({ GIT_DIR: join(other, '.git') }, async () => { expect(classifyGitCheckout(plain)).toBe('not_git'); });+});++test.skipIf(process.platform === 'win32')('CSO G3: discovery stops at a world-writable ancestor owned by someone else', () => {+ const shared = scratch();+ mkdirSync(join(shared, '.git'));+ mkdirSync(join(shared, 'brain', 'notes'), { recursive: true });+ const foreign = (path: string) => {+ const real = statSync(path);+ return path === shared ? { uid: real.uid + 1, mode: real.mode | 0o1777, isDirectory: () => true } : real;+ };+ expect(classifyGitCheckout(join(shared, 'brain', 'notes'), foreign)).toBe('not_git');+ const sharedSameOwner = (path: string) => {+ const real = statSync(path);+ return path === shared ? { uid: real.uid, mode: real.mode | 0o1777, isDirectory: () => true } : real;+ };+ expect(classifyGitCheckout(join(shared, 'brain', 'notes'), sharedSameOwner)).toBe('git');+ const foreignNotWritable = (path: string) => {+ const real = statSync(path);+ return path === shared ? { uid: real.uid + 1, mode: (real.mode & ~0o002) | 0o755, isDirectory: () => true } : real;+ };+ expect(classifyGitCheckout(join(shared, 'brain', 'notes'), foreignNotWritable)).toBe('git');+ expect(classifyGitCheckout(join(shared, 'brain', 'notes'))).toBe('git');+});++const sudo = process.platform !== 'win32' && process.getuid?.() !== 0 && spawnSync('sudo', ['-n', 'true']).status === 0;+test.skipIf(!sudo)('CSO G3 on the real filesystem: a root-owned .git in a 1777 directory above a user directory is not this checkout', () => {+ const user = scratch();+ const shared = join(user, 'shared');+ mkdirSync(shared);+ try {+ expect(spawnSync('sudo', ['-n', 'sh', '-c', `mkdir "${shared}/.git" && chown root:root "${shared}" "${shared}/.git" && chmod 1777 "${shared}"`]).status).toBe(0);+ const brain = join(shared, 'brain');+ mkdirSync(brain);+ expect(classifyGitCheckout(brain)).toBe('not_git');+ } finally { spawnSync('sudo', ['-n', 'rm', '-rf', shared]); }});test('a missing directory or a file is unknown, never "not a checkout"', () => {const dir = scratch();- expect(classifyGitCheckout(join(dir, 'missing'), noGitDir)).toBe('unknown');+ expect(classifyGitCheckout(join(dir, 'missing'))).toBe('unknown');writeFileSync(join(dir, 'file'), 'x');- expect(classifyGitCheckout(join(dir, 'file'), noGitDir)).toBe('unknown');+ expect(classifyGitCheckout(join(dir, 'file'))).toBe('unknown');});test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('an unreadable parent is unknown', () => {const dir = scratch();mkdirSync(join(dir, 'locked', 'inner'), { recursive: true });chmodSync(join(dir, 'locked'), 0o000);- try { expect(classifyGitCheckout(join(dir, 'locked', 'inner'), noGitDir)).toBe('unknown'); }+ try { expect(classifyGitCheckout(join(dir, 'locked', 'inner'))).toBe('unknown'); }finally { chmodSync(join(dir, 'locked'), 0o755); }});diff --git a/test/git-env-guard.test.ts b/test/git-env-guard.test.tsnew file mode 100644index 0000000000..222f7aee17--- /dev/null+++ b/test/git-env-guard.test.ts@@ -0,0 +1,72 @@+/**+ * CSO G4 guard (wave 13): every Git child process under `src/core` builds its env+ * through a helper that drops Git's repository-locating variables (`gitChildEnv`,+ * or the stricter `backupGitEnv` / `hardenedGitEnvironment`). A new spawn that+ * inherits `process.env` (implicitly or with `...process.env`) fails here.+ * PENDING lists files owned by another lane; each is a named hunk request and+ * leaves the list once that lane adopts the helper.+ */+import { expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';++const ROOT = join(import.meta.dir, '..');+const HELPERS = /\benv\s*:\s*(?:\{\s*\.\.\.)?(gitChildEnv|backupGitEnv|hardenedGitEnvironment)\(/;+const SPAWN = /\b(spawnSync|spawn|execFileSync|execFileBounded|execFile)\(\s*['"]git['"]\s*,|\bBun\.spawn(Sync)?\(\s*\[\s*['"]git['"]/g;+/** GBRA-75 (wave 10) owns these; the hunk request adopts gitChildEnv after wave 10 merges. */+const PENDING = new Set(['src/core/sync-git.ts', 'src/core/git-visible-files.ts', 'src/core/fence-repair/census.ts']);++function files(dir: string, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) files(path, out);+ else if (name.endsWith('.ts') && !name.includes('.generated.')) out.push(path);+ }+ return out;+}++/** The call's full text from its opening parenthesis, skipping string and template contents. */+function callText(source: string, open: number): string {+ let depth = 0;+ for (let i = open; i < source.length; i++) {+ const c = source[i]!;+ if (c === '\'' || c === '"' || c === '`') {+ for (i++; i < source.length && source[i] !== c; i++) if (source[i] === '\\') i++;+ } else if (c === '(' || c === '[' || c === '{') depth++;+ else if (c === ')' || c === ']' || c === '}') { if (--depth === 0) return source.slice(open, i + 1); }+ }+ return source.slice(open);+}++export function unscrubbedGitSpawns(path: string, source: string): string[] {+ const found: string[] = [];+ for (const match of source.matchAll(SPAWN)) {+ const call = callText(source, source.indexOf('(', match.index!));+ const named = /,\s*([A-Za-z_$][\w$]*)\s*\)$/.exec(call)?.[1];+ const scrubbed = HELPERS.test(call) || (named !== undefined && new RegExp(`\\b${named}\\s*=\\s*\\{[^;]*${HELPERS.source}`).test(source));+ if (!scrubbed || /\.\.\.\s*process\.env\b/.test(call)) found.push(`${path}:${source.slice(0, match.index).split('\n').length}`);+ }+ return found;+}++test('every Git spawn under src/core scrubs repository-locating variables', () => {+ const offenders = files(join(ROOT, 'src/core')).flatMap(file => {+ const rel = relative(ROOT, file).split('\\').join('/');+ return PENDING.has(rel) ? [] : unscrubbedGitSpawns(rel, readFileSync(file, 'utf8'));+ });+ expect(offenders).toEqual([]);+});++test('the guard catches implicit and explicit process.env inheritance and accepts the helpers', () => {+ expect(unscrubbedGitSpawns('x.ts', "execFileSync('git', ['status'], { encoding: 'utf8' });")).toEqual(['x.ts:1']);+ expect(unscrubbedGitSpawns('x.ts', "spawnSync('git', ['status']);")).toEqual(['x.ts:1']);+ expect(unscrubbedGitSpawns('x.ts', "execFile('git', args, { env: { ...process.env, A: '1' } });")).toEqual(['x.ts:1']);+ expect(unscrubbedGitSpawns('x.ts', "Bun.spawn(['git', 'status'], { env: process.env });")).toEqual(['x.ts:1']);+ expect(unscrubbedGitSpawns('x.ts', "execFileSync('git', ['status'], { env: gitChildEnv({ A: ')' }) });")).toEqual([]);+ expect(unscrubbedGitSpawns('x.ts', "const opts = { stdio: 'ignore', env: gitChildEnv() };\nexecFileSync('git', ['add'], opts);")).toEqual([]);+ expect(unscrubbedGitSpawns('x.ts', "spawnSync('git', HARDENED, { env: hardenedGitEnvironment() });")).toEqual([]);+});++test('PENDING names only files that still need the hunk', () => {+ for (const rel of PENDING) expect({ rel, unscrubbed: unscrubbedGitSpawns(rel, readFileSync(join(ROOT, rel), 'utf8')).length > 0 }).toEqual({ rel, unscrubbed: true });+});diff --git a/test/persistence-effect-git-env.test.ts b/test/persistence-effect-git-env.test.tsnew file mode 100644index 0000000000..54b3bba935--- /dev/null+++ b/test/persistence-effect-git-env.test.ts@@ -0,0 +1,74 @@+/**+ * CSO G4 (wave 13): a gbrain started from a Git hook or a shell that exported Git's+ * repository-locating variables must still read and write only the checkout it was+ * asked about.+ * Protects: the Git effect (`commitGitTargets`), the classic write-through commit+ * (`commitWriteThroughFile`) and git-remote probes build their env through+ * `gitChildEnv`, so an inherited `GIT_DIR`/`GIT_WORK_TREE`/`GIT_INDEX_FILE` aimed at+ * another repository leaves that repository's HEAD and index untouched.+ * Seams: none; real repositories, the variables set on process.env for the test.+ */+import { afterEach, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';+import { commitWriteThroughFile } from '../src/core/brain-repo-durability.ts';+import { isWorkingTreeDirty, detectDefaultBranch } from '../src/core/git-remote.ts';+import { gitChildEnv, GIT_LOCAL_ENV_VARS } from '../src/core/git-env.ts';+import { withEnv } from './helpers/with-env.ts';++const roots: string[] = [];+const clean = gitChildEnv();+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: clean }).trim();+function repo(name: string, branch: string): string {+ const root = mkdtempSync(join(tmpdir(), `gbrain-git-env-${name}-`));+ roots.push(root);+ git(root, 'init', '-q', '-b', branch);+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, 'a.md'), `${name} first\n`);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', `${name} seed`);+ return root;+}+const inherit = (other: string) => ({ GIT_DIR: join(other, '.git'), GIT_WORK_TREE: other, GIT_INDEX_FILE: join(other, '.git', 'index') });+afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});+const state = (root: string) => ({ head: git(root, 'rev-parse', 'HEAD'), index: readFileSync(join(root, '.git', 'index')).toString('base64'), status: git(root, 'status', '--porcelain') });++test('gitChildEnv drops every repository-locating variable and keeps transport ones', () => {+ const source = Object.fromEntries([...GIT_LOCAL_ENV_VARS.map(key => [key, 'x']), ['GIT_CONFIG_KEY_0', 'core.hooksPath'], ['GIT_CONFIG_VALUE_0', '/tmp/h'],+ ['GIT_SSH_COMMAND', 'ssh -i key'], ['GIT_ASKPASS', '/bin/askpass'], ['SSH_AUTH_SOCK', '/run/agent'], ['PATH', '/usr/bin']]);+ expect(gitChildEnv({ GIT_TERMINAL_PROMPT: '0' }, source)).toEqual({ GIT_SSH_COMMAND: 'ssh -i key', GIT_ASKPASS: '/bin/askpass', SSH_AUTH_SOCK: '/run/agent', PATH: '/usr/bin', GIT_TERMINAL_PROMPT: '0' });+});++test('the Git effect commits into its own root under an inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE', async () => {+ const brain = repo('brain', 'main');+ const other = repo('other', 'trunk');+ writeFileSync(join(brain, 'a.md'), 'brain second\n');+ writeFileSync(join(other, 'a.md'), 'other uncommitted\n');+ const before = state(other);+ await withEnv(inherit(other), async () => {+ expect((await commitGitTargets(brain, ['a.md'])).get('a.md')).toEqual({ git: 'committed' });+ });+ expect(state(other)).toEqual(before);+ expect(git(brain, 'show', 'HEAD:a.md')).toBe('brain second');+ expect(git(brain, 'status', '--porcelain')).toBe('');+});++test('the classic write-through commit and git-remote probes stay on their own root', async () => {+ const brain = repo('brain', 'main');+ const other = repo('other', 'trunk');+ writeFileSync(join(brain, 'a.md'), 'brain second\n');+ writeFileSync(join(other, 'a.md'), 'other uncommitted\n');+ const before = state(other);+ await withEnv(inherit(other), async () => {+ expect(isWorkingTreeDirty(brain)).toBe(true);+ expect(detectDefaultBranch(brain)).toBe('main');+ expect(commitWriteThroughFile(brain, join(brain, 'a.md'), 'a')).toBe(true);+ expect(isWorkingTreeDirty(brain)).toBe(false);+ });+ expect(state(other)).toEqual(before);+ expect(git(brain, 'show', 'HEAD:a.md')).toBe('brain second');+});