Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): honour the operator's safe.directory in hardened Git reads (#7584)
garrytan7274c5617ca6
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 2bdb63853d..68db880258 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -18,7 +18,7 @@ See [generations](generations.md).- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696). #6865: the per-path eligibility (scope, `sync.exclude`, `sync.include_hidden`, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported `loadSyncEligibility(engine, context, opts?, company?)`, which the unindexed-file detector shares.-- `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr`/`check-ignore` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is a third wrapper: it spawns async, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.+- `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr`/`check-ignore` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is a third wrapper: it spawns async, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`. #7584: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`, via `git-env.ts` `envSafeDirectories` / `safeDirectoryEnv`) as environment config, so a source repository owned by another user reads once the operator allows it; `gitChildEnv` carries the environment entries the same way. Test: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH).- `src/core/persistence/sync-git-stream.ts` — the managed-sync reconcile's Git level reads (#6712), all through `hardenedGitStream` (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. `readTreeLevel` (`ls-tree -r -z <commit> -- <scope>`: blobs plus symlinks and gitlinks with their mode), `readIndexLevel` (`ls-files -s -z`, the index only; a conflicted path keeps its highest stage) and `readRenameHints` (`diff-tree -r -z --no-renames`: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw `SyncTreeReadIncomplete` (code `reconcile_read_incomplete`) unless Git exited 0, was not signalled and its output ended at a NUL. `readBlobs` reads contents through one `cat-file --batch`, leaving out missing, oversized and over-total objects. `probeDirtiness` is the batched `hardenedPathDirty` (`Dp`): per batch of 2,000 paths one `hash-object --no-filters --stdin-paths` and one `check-attr -z --stdin`, presence and bytes from `readSyncFile`; verdicts in order `untracked`, `staged` (index and tree differ in OID or mode, a non-zero stage, or one side missing), `deleted`, `unknown` (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then `clean` (raw OID equals the tree with the executable bit matching), `clean_eol` (only `text`/`eol` set and the CRLF-folded bytes hash to the tree), `clean_lfs` (a valid pointer whose sha256 and size match the bytes) or `modified`; another filter, `working-tree-encoding`, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are `unknown`, never clean. Tests: `test/hardened-git-stream-6712.test.ts` (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while `git status`/`git diff` on the same checkout do). Working mode: `probeDirtiness(..., { working: true })` never reads the index (a path with no file is `deleted`, a present file outside the tree `untracked` with its raw OID, every other present file judged from its bytes against the tree through the same `clean_eol`/`clean_lfs` domains), so a staged edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). `hashWorkingLevel` hashes every path of a working round that way with hash-then-restat (a path whose bigint `lstat` moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: `WorkingStatCache` is plain JSON (`{v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}`), an entry is written only for a stable stat whose `mtime` and `ctime` are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most `WORKING_STAT_CACHE_MAX_ENTRIES` (100,000) entries are kept in path order. `workingChanged(cache, paths)` is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero `ctime`, a missing cache or a moved root all read as changed, never as unchanged. `parseWorkingStatCache` validates a serialized copy (junk is null, so everything reads changed); `rememberWorkingStatCache`/`recallWorkingStatCache` keep up to 64 caches per process. Working-mode tests: `test/sync-working-level-6712.test.ts` (probe 41, on the Git reads and on a managed PGLite pass), `test/sync-working-stat-cache-6712.test.ts` (probe 42); the probe 28 marker test also runs `hashWorkingLevel`.- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.diff --git a/src/core/git-env.ts b/src/core/git-env.tsindex 851d255545..fedaf040e2 100644--- a/src/core/git-env.ts+++ b/src/core/git-env.ts@@ -4,7 +4,8 @@* `<root>`. 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.+ * `SSH_AUTH_SOCK`, proxies) pass through, and so do the operator's environment+ * `safe.directory` entries (#7584); `extra` wins over all of them.*//** `git rev-parse --local-env-vars` (Git 2.55): the variables that locate or reconfigure one repository. */@@ -21,10 +22,32 @@ const LOCAL = new Set<string>(GIT_LOCAL_ENV_VARS);*/export const GIT_READ_ENV: NodeJS.ProcessEnv = { GIT_OPTIONAL_LOCKS: '0' };+/**+ * #7584: the `safe.directory` entries the operator set through `GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_<n>` / `GIT_CONFIG_VALUE_<n>`,+ * in order. Only this key survives a scrub: it relaxes Git's ownership check for directories the operator names and cannot run+ * code or reach the network, so carrying it lets a repository owned by another user be read the way plain `git` reads it.+ */+export function envSafeDirectories(source: NodeJS.ProcessEnv = process.env): string[] {+ const count = Number(source.GIT_CONFIG_COUNT);+ const values: string[] = [];+ for (let i = 0; Number.isInteger(count) && i < count; i++) {+ if (source[`GIT_CONFIG_KEY_${i}`]?.toLowerCase() === 'safe.directory') values.push(source[`GIT_CONFIG_VALUE_${i}`] ?? '');+ }+ return values;+}++/** `safe.directory` values as command-scope config in the environment, in order (an empty value resets the list, as in Git). */+export function safeDirectoryEnv(values: readonly string[]): NodeJS.ProcessEnv {+ if (!values.length) return {};+ const env: NodeJS.ProcessEnv = { GIT_CONFIG_COUNT: String(values.length) };+ values.forEach((value, i) => { env[`GIT_CONFIG_KEY_${i}`] = 'safe.directory'; env[`GIT_CONFIG_VALUE_${i}`] = value; });+ return env;+}+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 };+ return { ...env, ...safeDirectoryEnv(envSafeDirectories(source)), ...extra };}diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsindex 8e3259cf9e..02adb53ae7 100644--- a/src/core/hardened-git.ts+++ b/src/core/hardened-git.ts@@ -20,16 +20,42 @@ import { lstatSync } from 'node:fs';import { once } from 'node:events';import type { Writable } from 'node:stream';import { join } from 'node:path';+import { envSafeDirectories, gitChildEnv, safeDirectoryEnv } from './git-env.ts';export const HARDENED_GIT_ARGS: readonly string[] = ['--no-pager', '--no-optional-locks', '--no-replace-objects','-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false','-c', 'submodule.recurse=false', '-c', 'protocol.allow=never', '-c', 'credential.helper=','-c', 'maintenance.auto=false', '-c', 'gc.auto=0'];+const OPERATOR_CONFIG_TTL_MS = 30_000;+let operatorConfig: { key: string; at: number; values: string[] } | null = null;++/**+ * #7584: the `safe.directory` entries in the operator's system and global Git config, in Git's order, read from `/` so no+ * repository's config takes part. Re-read every 30 s, so a running server picks up an edit without a restart.+ */+function operatorConfigSafeDirectories(): string[] {+ const key = ['HOME', 'XDG_CONFIG_HOME', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM', 'GIT_CONFIG_NOSYSTEM', 'PATH'].map(name => process.env[name] ?? '').join('\0');+ if (operatorConfig?.key === key && Date.now() - operatorConfig.at < OPERATOR_CONFIG_TTL_MS) return operatorConfig.values;+ const run = spawnSync('git', ['config', '--includes', '--show-scope', '-z', '--get-all', 'safe.directory'],+ { cwd: '/', env: { ...gitChildEnv(), LC_ALL: 'C' }, stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' });+ const fields = run.status === 0 ? run.stdout.toString('utf8').split('\0') : [];+ const values: string[] = [];+ for (let i = 0; i + 1 < fields.length; i += 2) if (fields[i] === 'system' || fields[i] === 'global') values.push(fields[i + 1]!);+ operatorConfig = { key, at: Date.now(), values };+ return values;+}++/**+ * System and global config stay off and every `GIT_*` variable is dropped, except the operator's `safe.directory` entries+ * (system, global, then environment, as Git orders them), carried as environment config (#7584). They relax only Git's+ * ownership check for a repository owned by another user, which the operator allowed for their own `git` too.+ */export function hardenedGitEnvironment(): NodeJS.ProcessEnv {const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));return { ...env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_OPTIONAL_LOCKS: '0',- GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', LC_ALL: 'C' };+ GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', LC_ALL: 'C',+ ...safeDirectoryEnv([...operatorConfigSafeDirectories(), ...envSafeDirectories()]) };}export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable'; status?: number };diff --git a/test/hardened-git-safe-directory-7584.test.ts b/test/hardened-git-safe-directory-7584.test.tsnew file mode 100644index 0000000000..736223b089--- /dev/null+++ b/test/hardened-git-safe-directory-7584.test.ts@@ -0,0 +1,98 @@+/**+ * #7584: a source repository owned by another user. Git refuses it ("dubious ownership") unless the operator allows the+ * directory with `safe.directory` in system or global config or the `GIT_CONFIG_*` environment. The hardened reads that sync+ * uses scrub all three, so sync failed with "HEAD does not name a commit" even after the operator allowed it. Now only the+ * `safe.directory` entries are carried: every other key in those places stays out.+ *+ * Ownership by another user is forced with Git's own `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper first on+ * PATH, because the hardened environment drops every `GIT_*` variable a test could set.+ */+import { describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { hardenedGitStream, hardenedGitSync } from '../src/core/hardened-git.ts';+import { gitChildEnv } from '../src/core/git-env.ts';+import { withEnv } from './helpers/with-env.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';++const LIMITS = { timeoutMs: 10_000, maxBytes: 1024 * 1024 };+const head = (root: string) => hardenedGitSync(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], LIMITS);+const ignored = (root: string) => hardenedGitSync(root, ['check-ignore', '--', 'a.md'], LIMITS);++async function setup() {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-7584-'));+ const root = join(dir, 'repo');+ execFileSync('mkdir', ['-p', root]);+ await makeGitFixture(root);+ const realGit = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();+ const shim = join(dir, 'bin');+ execFileSync('mkdir', ['-p', shim]);+ writeFileSync(join(shim, 'git'), `#!/bin/sh\nGIT_TEST_ASSUME_DIFFERENT_OWNER=1 exec "${realGit}" "$@"\n`);+ chmodSync(join(shim, 'git'), 0o755);+ const excludes = join(dir, 'excludes');+ writeFileSync(excludes, '*.md\n');+ const empty = join(dir, 'empty-config');+ writeFileSync(empty, '');+ const config = (name: string, safe: string) => {+ const file = join(dir, name);+ writeFileSync(file, `[safe]\n\tdirectory = ${safe}\n[core]\n\texcludesFile = ${excludes}\n`);+ return file;+ };+ const base = { PATH: `${shim}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_SYSTEM: empty, GIT_CONFIG_NOSYSTEM: undefined,+ GIT_CONFIG_COUNT: undefined, GIT_CONFIG_KEY_0: undefined, GIT_CONFIG_VALUE_0: undefined, GIT_CONFIG_KEY_1: undefined, GIT_CONFIG_VALUE_1: undefined };+ return { dir, root, excludes, config, base };+}++describe.skipIf(process.platform === 'win32')('#7584 hardened reads of a repository owned by another user', () => {+ test('without an allowance the hardened read is refused, as plain git refuses it', async () => {+ const { root, base } = await setup();+ await withEnv(base, () => {+ expect(head(root)).toEqual({ ok: false, reason: 'exit', status: 128 });+ });+ });++ test('a global safe.directory is honoured, and no other global key is read', async () => {+ const { root, config, base } = await setup();+ const global = config('global', root);+ await withEnv({ ...base, GIT_CONFIG_GLOBAL: global }, async () => {+ expect(execFileSync('git', ['-C', root, 'check-ignore', 'a.md'], { encoding: 'utf8', env: gitChildEnv() }).trim()).toBe('a.md');+ expect(head(root).ok).toBe(true);+ expect((await hardenedGitStream(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { ...LIMITS, onChunk: () => {} })).ok).toBe(true);+ expect(ignored(root)).toEqual({ ok: false, reason: 'exit', status: 1 });+ });+ });++ test('a system safe.directory is honoured, and no other system key is read', async () => {+ const { root, config, base } = await setup();+ await withEnv({ ...base, GIT_CONFIG_SYSTEM: config('system', root) }, () => {+ expect(head(root).ok).toBe(true);+ expect(ignored(root)).toEqual({ ok: false, reason: 'exit', status: 1 });+ });+ });++ test('a GIT_CONFIG_* safe.directory is honoured, and no other environment key is carried', async () => {+ const { root, excludes, base } = await setup();+ await withEnv({ ...base, GIT_CONFIG_COUNT: '2', GIT_CONFIG_KEY_0: 'core.excludesFile', GIT_CONFIG_VALUE_0: excludes,+ GIT_CONFIG_KEY_1: 'safe.directory', GIT_CONFIG_VALUE_1: root }, () => {+ expect(head(root).ok).toBe(true);+ expect(ignored(root)).toEqual({ ok: false, reason: 'exit', status: 1 });+ });+ });++ test('an allowance for another directory does not open this one', async () => {+ const { dir, root, config, base } = await setup();+ await withEnv({ ...base, GIT_CONFIG_GLOBAL: config('global', join(dir, 'elsewhere')) }, () => {+ expect(head(root)).toEqual({ ok: false, reason: 'exit', status: 128 });+ });+ });+});++test('#7584 gitChildEnv carries the environment safe.directory entries and drops every other GIT_CONFIG key', () => {+ const source = { PATH: '/usr/bin', GIT_CONFIG_COUNT: '3', GIT_CONFIG_KEY_0: 'core.fsmonitor', GIT_CONFIG_VALUE_0: '/tmp/x',+ GIT_CONFIG_KEY_1: 'Safe.Directory', GIT_CONFIG_VALUE_1: '/srv/notes', GIT_CONFIG_KEY_2: 'core.hooksPath', GIT_CONFIG_VALUE_2: '/tmp/h',+ GIT_CONFIG_KEY_3: 'safe.directory', GIT_CONFIG_VALUE_3: '/beyond-count' };+ expect(gitChildEnv({}, source)).toEqual({ PATH: '/usr/bin', GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: '/srv/notes' });+ expect(gitChildEnv({}, { PATH: '/usr/bin', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: '/srv/notes' })).toEqual({ PATH: '/usr/bin' });+});diff --git a/test/helpers/git-hermetic-preload.ts b/test/helpers/git-hermetic-preload.tsindex 8e0011526c..428375a10f 100644--- a/test/helpers/git-hermetic-preload.ts+++ b/test/helpers/git-hermetic-preload.ts@@ -48,6 +48,7 @@ for (const name of ['spawn', 'spawnSync'] as const) {const kept = gitChildEnv({}, process.env);for (const key of Object.keys(process.env)) if (!(key in kept)) delete process.env[key];+Object.assign(process.env, kept);const base = Number(process.env.GIT_CONFIG_COUNT ?? '0') || 0;const existingKeys: string[] = [];