Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(record-origin): take config.lock before reading the config, keep its mode and a symlinked config
garrytan9cf70687fc9f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e720911af2..821c6f24a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes-- `src/core/url-source-origin.ts`: on a managed brain each apply runs inside `withTopologyLocks` and `lockTopologyRows` (a held lock or a running refresh refuses `source_busy`); `--remote --apply` writes the clone-time lock-down (`lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`) into the checkout's `.git/config` with `git config --file` before the row, into the repository's shared config (`--git-common-dir`, so a linked worktree is covered), then reads back the values Git uses there and refuses `write_failed`, naming the key, when a worktree-scoped or included setting overrides one; a source already recorded as remote whose checkout lacks the lock-down gets it (`recorded`, with no `lfs_tracked` refusal even when its files now use git-lfs), and one that has it stays `already_recorded`; each key's existing values are removed before its one value is written, so one that holds several values gets the one clone-time value, and the keys go to a copy held as Git's `config.lock` that is renamed over the config in one step, so a failure part way leaves it as it was; a throw is reported per id as `write_failed`, saying whether the checkout already got all or part of the lock-down, and the batch continues. The committed-attributes read splits each `ls-tree -z` record at its first tab, reads only blobs, and ignores comment lines; a declared-only filter refuses `lfs_tracked` with its own wording. An unborn HEAD with an empty index counts as no committed attributes. The top-level comparison realpath-normalizes both sides. `lfs_unknown` reasons name the cause from Git's own error: checkout missing, not its own repository's top level (an enclosing repository, or none), owned by another user (`safe.directory`), or a Git read failed (for example a corrupt `.git`).+- `src/core/url-source-origin.ts`: on a managed brain each apply runs inside `withTopologyLocks` and `lockTopologyRows` (a held lock or a running refresh refuses `source_busy`); `--remote --apply` writes the clone-time lock-down (`lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`) into the checkout's `.git/config` with `git config --file` before the row, into the repository's shared config (`--git-common-dir`, so a linked worktree is covered), then reads back the values Git uses there and refuses `write_failed`, naming the key, when a worktree-scoped or included setting overrides one; a source already recorded as remote whose checkout lacks the lock-down gets it (`recorded`, with no `lfs_tracked` refusal even when its files now use git-lfs), and one that has it stays `already_recorded`; each key's existing values are removed before its one value is written, so one that holds several values gets the one clone-time value, and like Git, it takes `config.lock` beside the config's real path, copies the config into it (mode kept) and renames it over the config in one step, so a failure part way leaves it as it was; a throw is reported per id as `write_failed`, saying whether the checkout already got the lock-down, and the batch continues. The committed-attributes read splits each `ls-tree -z` record at its first tab, reads only blobs, and ignores comment lines; a declared-only filter refuses `lfs_tracked` with its own wording. An unborn HEAD with an empty index counts as no committed attributes. The top-level comparison realpath-normalizes both sides. `lfs_unknown` reasons name the cause from Git's own error: checkout missing, not its own repository's top level (an enclosing repository, or none), owned by another user (`safe.directory`), or a Git read failed (for example a corrupt `.git`).- `src/core/hardened-git.ts`: `rev-parse --git-common-dir` joins the read-only allow-list, so the lock-down finds a linked worktree's shared config.- `src/core/persistence/topology-clone.ts`: a managed clone or reclone takes the source config it clones with from its locked admission read, not from the read before it took its locks.- `src/core/behavior-change-notice.ts`: one row for the changed `record-origin` behavior.diff --git a/src/core/url-source-origin.ts b/src/core/url-source-origin.tsindex 3ac7f3a368..8e7a486e93 100644--- a/src/core/url-source-origin.ts+++ b/src/core/url-source-origin.ts@@ -18,7 +18,7 @@* canonical manifest, and converting the checkout rewrites its files, which this does not do. Without git-lfs files a* clone with these settings has the same tracked bytes, so the stored manifest needs no change.*/-import { existsSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { closeSync, existsSync, fchmodSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, dirname, join, resolve } from 'node:path';import type { BrainEngine } from './engine.ts';import { execFileSync } from './spawn.ts';@@ -115,22 +115,25 @@ function lockDownGaps(root: string): string[] {/*** Writes the clone-time lock-down (`LFS_OFF_CLONE_CONFIG`) into the repository's shared config (`--git-common-dir`, so a linked* worktree's repository gets it too), without running Git in the checkout, then reads back what Git uses there and throws when a- * worktree-scoped or included setting still overrides a key. The keys are written to a copy held as Git's own `config.lock` and- * renamed over the config in one step, so a failure part way leaves the config as it was; each key's existing values are removed+ * worktree-scoped or included setting still overrides a key. Like Git, it takes `config.lock` beside the config's real path+ * first, copies the config into it (mode kept), writes the keys there and renames it over the config in one step, so a failure part way leaves the config as it was; each key's existing values are removed* before its one value is written, so a key that held several ends with the clone-time value. `progress` says how far it got:* `written` once the config holds every key.*/function lockDownCheckout(root: string, progress: { state: 'none' | 'written' | 'done' }): void {const commonDir = hardenedGitSync(root, ['rev-parse', '--git-common-dir'], GIT_LIMITS);if (!commonDir.ok) throw new Error(`Git could not locate the repository of ${root}.`);- const file = join(resolve(root, commonDir.stdout.toString('utf8').replace(/\n$/, '')), 'config');+ const file = realpathSync(join(resolve(root, commonDir.stdout.toString('utf8').replace(/\n$/, '')), 'config'));const staged = `${file}.lock`;- try { writeFileSync(staged, readFileSync(file), { flag: 'wx', mode: statSync(file).mode & 0o777 }); }+ let lock: number;+ try { lock = openSync(staged, 'wx'); }catch (error) {if ((error as { code?: string }).code === 'EEXIST') throw new Error(`${staged} exists, so another Git process is writing that config (or one stopped and left the file).`);throw error;}try {+ try { fchmodSync(lock, statSync(file).mode & 0o7777); writeFileSync(lock, readFileSync(file)); }+ finally { closeSync(lock); }const options = { cwd: dirname(file), env: hardenedGitEnvironment(), stdio: 'pipe', timeout: GIT_LIMITS.timeoutMs } as const;for (const [key, value] of LOCK_DOWN) {try { execFileSync('git', ['config', '--file', staged, '--unset-all', key], options); }diff --git a/test/url-source-origin.test.ts b/test/url-source-origin.test.tsindex 9e0aa2f07c..17204f4097 100644--- a/test/url-source-origin.test.ts+++ b/test/url-source-origin.test.ts@@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { randomUUID } from 'node:crypto';import * as childProcess from 'node:child_process';import { execFileSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { tmpdir } from 'node:os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -432,6 +432,22 @@ for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const)expect(existsSync(join(root, '.git', 'config.lock'))).toBe(false);}), 60_000);+ test('the lock-down keeps a group-writable config mode and a symlinked config, as Git does', () => brain(async home => {+ const root = defaultCloneDir('source-a');+ repoAt(root, { 'example.md': 'Canonical\n' });+ const target = join(home, 'shared-config');+ writeFileSync(target, readFileSync(join(root, '.git', 'config')));+ chmodSync(target, 0o664);+ rmSync(join(root, '.git', 'config'));+ symlinkSync(target, join(root, '.git', 'config'));+ await insert('source-a', root, URL_CONFIG);+ expect((await recordSourceOrigin(engine, ['source-a'], { origin: 'remote', apply: true, remote: false })).results[0]).toMatchObject({ status: 'recorded' });+ expect(lstatSync(join(root, '.git', 'config')).isSymbolicLink()).toBe(true);+ expect(statSync(target).mode & 0o777).toBe(0o664);+ expect(localConfig(root, 'core.hooksPath')).toBe('/dev/null');+ expect(existsSync(`${target}.lock`) || existsSync(join(root, '.git', 'config.lock'))).toBe(false);+ }), 60_000);+test('a config.lock another Git process holds refuses the lock-down write_failed and leaves both files alone', () => brain(async () => {const root = defaultCloneDir('source-a');repoAt(root, { 'example.md': 'Canonical\n' });