Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
6.7 KB
Raw Blame
/**
 * Wave 13 guard: every Git child process under `src/core` builds its env
 * through a helper that sanitizes the inherited Git environment (`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 that still need the helper (empty:
 * GBRA-75 approved its hunk for sync-git.ts, git-visible-files.ts, fence-repair/census.ts
 * and eval/drift-watch.ts in wave 13).
 */
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['"]|\b(execSync|exec)\(\s*[`'"]git[\s`'"]/g;
/** Files owned by another lane that still need the helper; each entry is a named hunk request. */
const PENDING = new Set<string>([]);

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 lineStart = source.lastIndexOf('\n', match.index!) + 1;
    if (/^\s*(\*|\/\/)/.test(source.slice(lineStart, match.index))) continue;
    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([]);
  expect(unscrubbedGitSpawns('x.ts', "execSync('git update-index -q --refresh', { cwd: root });")).toEqual(['x.ts:1']);
  expect(unscrubbedGitSpawns('x.ts', " * `execSync(`git -C ${path} ...`)` in a doc comment")).toEqual([]);
  expect(unscrubbedGitSpawns('x.ts', "execSync(`git ${args.join(' ')}`, { cwd: root });")).toEqual(['x.ts:1']);
  expect(unscrubbedGitSpawns('x.ts', "execSync(`git ${args.join(' ')}`, { env: gitChildEnv(), cwd: root });")).toEqual([]);
});

/**
 * #7793: Git exports a global pathspec switch (`--literal-pathspecs` and friends, or GIT_LITERAL_PATHSPECS and friends in a
 * spawn's env) to every hook, textconv and filter helper the command starts, so a pathspec gbrain builds is made literal
 * per path with `literalPathspecs` instead. `git-env.ts` names the switches to strip them from the environment, and a step may
 * pin one off (`GIT_GLOB_PATHSPECS: '0'`).
 */
const GLOBAL_PATHSPEC_SWITCH = /--(?:literal|glob|noglob|icase)-pathspecs\b|\bGIT_(?:LITERAL|GLOB|NOGLOB|ICASE)_PATHSPECS\b(?!\s*:\s*'0')/;

export function globalPathspecSwitches(path: string, source: string): string[] {
  return source.split('\n').flatMap((line, i) => /^\s*(\*|\/\/|\/\*)/.test(line) || !GLOBAL_PATHSPEC_SWITCH.test(line) ? [] : [`${path}:${i + 1}`]);
}

test('no Git call under src passes a global pathspec switch', () => {
  const offenders = files(join(ROOT, 'src')).flatMap(file => {
    const rel = relative(ROOT, file).split('\\').join('/');
    return rel === 'src/core/git-env.ts' ? [] : globalPathspecSwitches(rel, readFileSync(file, 'utf8'));
  });
  expect(offenders).toEqual([]);
});

test('the global-switch guard catches flags and env spellings and skips comments', () => {
  expect(globalPathspecSwitches('x.ts', "execFileSync('git', ['--literal-pathspecs', 'log', '-p'], opts);")).toEqual(['x.ts:1']);
  expect(globalPathspecSwitches('x.ts', "spawn('git', ['-C', root, '--glob-pathspecs', 'ls-files']);")).toEqual(['x.ts:1']);
  expect(globalPathspecSwitches('x.ts', "const env = gitChildEnv({ GIT_LITERAL_PATHSPECS: '1' });")).toEqual(['x.ts:1']);
  expect(globalPathspecSwitches('x.ts', "const env = { GIT_GLOB_PATHSPECS: '0', GIT_ICASE_PATHSPECS: '0' };")).toEqual([]);
  expect(globalPathspecSwitches('x.ts', "const a = 1;\nargs.push('--icase-pathspecs');")).toEqual(['x.ts:2']);
  expect(globalPathspecSwitches('x.ts', "// never --literal-pathspecs here\n/** or GIT_LITERAL_PATHSPECS */\n * nor --noglob-pathspecs")).toEqual([]);
  expect(globalPathspecSwitches('x.ts', "git(root, ['ls-tree', '--', ...literalPathspecs(paths)]);")).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 });
});