Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: remote-added clone settings survive the managed reclone; install-hook leaves a hooks-off clone alone

garrytan039b0c4f9c66
diff --git a/src/commands/frontmatter-install-hook.ts b/src/commands/frontmatter-install-hook.ts
index 939c8867b8..b77c75a557 100644
--- a/src/commands/frontmatter-install-hook.ts
+++ b/src/commands/frontmatter-install-hook.ts
@@ -260,6 +260,9 @@ export async function runFrontmatterInstallHook(args: string[]): Promise<void> {
const where = join(target.root, '.githooks', 'pre-commit');
console.log(`[${src.id}] hook written at ${where}; core.hooksPath left unset — ${hooksPathBlocker(target.root)}`);
installed++;
+ } else if (result === 'skipped_hooks_off') {
+ console.log(`[${src.id}] skipped — ${hooksPathBlocker(target.root)}`);
+ skipped++;
} else if (result === 'skipped_existing') {
console.log(`[${src.id}] existing pre-commit hook found; pass --force to overwrite (.bak created)`);
skipped++;
@@ -332,7 +335,10 @@ function resolveHookTarget(localPath: string): HookTarget {
return { root, scope: rel ? `${rel}/` : '' };
}
-type InstallResult = 'installed' | 'installed_unwired' | 'skipped_existing' | 'unchanged';
+type InstallResult = 'installed' | 'installed_unwired' | 'skipped_existing' | 'skipped_hooks_off' | 'unchanged';
+
+/** The core.hooksPath a remote-added URL clone carries (git-remote.ts LFS_OFF_CLONE_CONFIG): hooks off on purpose. */
+const HOOKS_OFF = '/dev/null';
/**
* `.githooks/` and its `pre-commit` under `root`. Refuses a symlink at either
@@ -413,6 +419,7 @@ const samePath = (a: string, b: string): boolean => {
*/
export function hooksPathBlocker(root: string): string | null {
const current = currentHooksPath(root);
+ if (current === HOOKS_OFF) return `hooks are off in this clone on purpose (core.hooksPath=${HOOKS_OFF}, set on a source a remote caller added by URL), and gbrain leaves them off`;
if (current) {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed literal tail under the discovered git root
if (samePath(current, join(root, '.githooks'))) return null;
@@ -429,6 +436,7 @@ export function hooksPathBlocker(root: string): string | null {
export function installHook(localPath: string, force: boolean): InstallResult {
const { root, scope } = resolveHookTarget(localPath);
+ if (currentHooksPath(root) === HOOKS_OFF) return 'skipped_hooks_off';
const { hooksDir, hookPath } = hookPaths(root);
mkdirSync(hooksDir, { recursive: true });
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 65dcc8b007..152dfb7470 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -105,6 +105,9 @@ export interface CloneOpts {
skipLfs?: boolean;
}
+/** `git clone` options that write the skipLfs lock-down into the clone's own .git/config. */
+export const LFS_OFF_CLONE_CONFIG = ['--config', 'lfs.fetchexclude=*', '--config', 'core.hooksPath=/dev/null', '--config', 'lfs.locksverify=false'] as const;
+
export class GitOperationError extends Error {
constructor(
public op: 'clone' | 'pull' | 'fetch' | 'remote_get_url',
@@ -169,7 +172,7 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
if (opts.branch) {
args.push('--branch', opts.branch);
}
- if (opts.skipLfs) args.push('--config', 'lfs.fetchexclude=*', '--config', 'core.hooksPath=/dev/null', '--config', 'lfs.locksverify=false');
+ if (opts.skipLfs) args.push(...LFS_OFF_CLONE_CONFIG);
args.push(url, destDir);
try {
diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.ts
index c23894f707..dbe4469049 100644
--- a/src/core/persistence/topology-clone.ts
+++ b/src/core/persistence/topology-clone.ts
@@ -7,7 +7,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import { parseRemoteUrl } from '../git-remote.ts';
-import { isOwnedClone } from '../sources-ops.ts';
+import { isOwnedClone, lfsDownloadsOff } from '../sources-ops.ts';
import { parseSourceConfig } from '../sources-load.ts';
import type { SourceLifecycleInput } from './source-lifecycle.ts';
import type { TopologyCloneRecovery } from './topology-clone-model.ts';
@@ -33,7 +33,7 @@ const recoveryCapacityFix=():Action=>readFix('Shows the configured per-worktree
/** Provider seam only for deterministic storage-boundary tests. */
export interface CloneLifecycleHooks {
- clone?:(url:string,stage:string,budget:number)=>Promise<void>;
+ clone?:(url:string,stage:string,budget:number,options:{skipLfs:boolean})=>Promise<void>;
boundary?:(name:'reserved'|'prepared'|'old_moved'|'new_moved'|'committed')=>Promise<void>;
}
export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifecycleInput,principal:string,requestId:string,intent:unknown,
@@ -166,7 +166,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await tx.executeRaw("UPDATE persistence_topology_changes SET recovery=$2::text::jsonb,updated_at=now() WHERE id=$1::uuid AND state='recovering'",[accepted!.id,JSON.stringify(recovery)]);
});
- await (hooks.clone??cloneTopologyCheckout)(url,recovery.stage,recovery.cloneBudget);
+ await (hooks.clone??cloneTopologyCheckout)(url,recovery.stage,recovery.cloneBudget,{skipLfs:lfsDownloadsOff(source?.config)});
const stageBytes=await topologyDirectoryBytes(recovery.stage,recovery.cloneBudget);
const candidate=worktreeManifest(recovery.stage,{progress:humanManifestProgress(),scope:recovery.hashScope});
if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw opError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.',
diff --git a/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.ts
index d4e5890d4d..eead7fdbf7 100644
--- a/src/core/persistence/topology-filesystem.ts
+++ b/src/core/persistence/topology-filesystem.ts
@@ -6,7 +6,7 @@ import { flushDirectory, flushFile } from '../fs-durable.ts';
import type { Action } from '../agent-output.ts';
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 { durableSsrfFlags, GIT_ENV, GIT_SSRF_SUBCOMMAND_FLAGS, LFS_OFF_CLONE_CONFIG, parseRemoteUrl } from '../git-remote.ts';
import { persistenceHome } from './identity.ts';
import { gitChildEnv } from '../git-env.ts';
@@ -62,8 +62,8 @@ export function flushTopologyTree(root:string):void{
visit(root);
}
-/** Reserved staging, no DB checkout; kill only this owned Git child on overflow. */
-export async function cloneTopologyCheckout(url:string,destination:string,maxBytes:number,timeoutMs=600_000):Promise<void>{
+/** Reserved staging, no DB checkout; kill only this owned Git child on overflow. skipLfs: the clone keeps git-lfs downloads and hooks off, as cloneRepo does. */
+export async function cloneTopologyCheckout(url:string,destination:string,maxBytes:number,{skipLfs=false,timeoutMs=600_000}:{skipLfs?:boolean;timeoutMs?:number}={}):Promise<void>{
parseRemoteUrl(url);
if(!existsSync(destination)||!lstatSync(destination).isDirectory()||lstatSync(destination).isSymbolicLink()||readdirSync(destination).length)
throw opError('recovery_required','The reserved clone staging directory must remain empty before cloning.',
@@ -71,7 +71,7 @@ export async function cloneTopologyCheckout(url:string,destination:string,maxByt
{fix:recoveryFix('Shows pending lifecycle requests and their recovery records, read-only.')});
const 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],
+ const child=spawn('git',[...durableSsrfFlags(),'-c',`core.hooksPath=${hooks}`, 'clone',...GIT_SSRF_SUBCOMMAND_FLAGS,...(skipLfs?LFS_OFF_CLONE_CONFIG:[]),'--depth=1','--',url,destination],
{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)=>{
diff --git a/test/frontmatter-install-hook.test.ts b/test/frontmatter-install-hook.test.ts
index 6c0fa75c86..e70c894e5d 100644
--- a/test/frontmatter-install-hook.test.ts
+++ b/test/frontmatter-install-hook.test.ts
@@ -4,7 +4,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
import {
- activeGitHooks, FRONTMATTER_HOOK_VERSION, frontmatterHookVersion, inspectFrontmatterHook, installHook, uninstallHook,
+ activeGitHooks, FRONTMATTER_HOOK_VERSION, frontmatterHookVersion, hooksPathBlocker, inspectFrontmatterHook, installHook, uninstallHook,
} from '../src/commands/frontmatter-install-hook.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -327,6 +327,16 @@ describe('frontmatter install-hook (B13)', () => {
}
});
+ test('a clone with hooks off on purpose (core.hooksPath=/dev/null) is skipped: nothing written, hooks stay off, no rewiring advice', async () => {
+ execFileSync('git', ['-C', tmp, 'config', 'core.hooksPath', '/dev/null']);
+ expect(await install(tmp)).toBe('skipped_hooks_off');
+ expect(existsSync(join(tmp, '.githooks'))).toBe(false);
+ expect(localHooksPath(tmp)).toBe('/dev/null');
+ expect(hooksPathBlocker(tmp)).not.toContain('.githooks');
+ expect(await install(tmp, true)).toBe('skipped_hooks_off');
+ expect(localHooksPath(tmp)).toBe('/dev/null');
+ });
+
test('a fresh clone that carries the committed gbrain hook gets wired on install (not "unchanged" while inert)', async () => {
// The hook FILE travels with the repo; core.hooksPath is per-clone config
// and does not. Install on the clone must fall through to the wiring step
diff --git a/test/persistence-source-lifecycle.test.ts b/test/persistence-source-lifecycle.test.ts
index 01eb055c41..de0e398cfc 100644
--- a/test/persistence-source-lifecycle.test.ts
+++ b/test/persistence-source-lifecycle.test.ts
@@ -367,4 +367,18 @@ test('remote URL changes during clone preparation refuse publication',()=>fixtur
for(const counter of counters){expect(counter.outstanding_count).toBe('0');expect(counter.intent_bytes).toBe('0');expect(counter.recovery_bytes).toBe('0');}
}),60_000);
+
+test('a reclone of a source a remote caller added by URL clones with git-lfs downloads and hooks off',()=>fixture(async(_home,source,root)=>{
+ const seen:Array<{skipLfs?:boolean}|undefined>=[];
+ for(const addedByRemote of [true,false]){
+ await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1',[source,JSON.stringify({managed_clone:true,remote_url:'https://example.invalid/brain.git',...(addedByRemote?{added_by_remote_caller:true}:{})})]);
+ const input={operation:'reclone' as const,sourceId:source,requestId:randomUUID()};
+ const result=await runManagedSourceClone(engine,input,await topologyPrincipal(engine),input.requestId,{...input,requestId:undefined,dryRun:undefined},{
+ clone:async(_url,stage,_budget,options)=>{seen.push(options);cpSync(root,stage,{recursive:true,filter:path=>!isPhysicalRootMetadata(basename(path))});},
+ });
+ expect(result).toMatchObject({state:'committed'});
+ }
+ expect(seen.map(options=>options?.skipLfs===true)).toEqual([true,false]);
+}),60_000);
+
});
diff --git a/test/sources-remote-lfs.test.ts b/test/sources-remote-lfs.test.ts
index 59e6d09ead..b84c3d40e6 100644
--- a/test/sources-remote-lfs.test.ts
+++ b/test/sources-remote-lfs.test.ts
@@ -18,6 +18,7 @@ import { cloneRepo, pullRepo } from '../src/core/git-remote.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operationsByName } from '../src/core/operations.ts';
import { lfsDownloadsOff, recloneIfMissing } from '../src/core/sources-ops.ts';
+import { cloneTopologyCheckout } from '../src/core/persistence/topology-filesystem.ts';
import { withEnv } from './helpers/with-env.ts';
const hasLfs = spawnSync('git', ['lfs', 'version']).status === 0 && process.platform !== 'win32';
@@ -197,6 +198,40 @@ if (args.includes('clone')) mkdirSync(args[args.length - 1]!, { recursive: true
});
});
+describe('cloneTopologyCheckout: the managed reclone writes the same lock-down into the clone', () => {
+ const fakeDir = join(ROOT, 'fake-topology-git');
+ const log = join(fakeDir, 'calls.log');
+ const home = join(ROOT, 'topology-home');
+ beforeAll(() => {
+ mkdirSync(fakeDir, { recursive: true });
+ const recorder = join(fakeDir, 'record.ts');
+ writeFileSync(recorder, `import { appendFileSync } from 'node:fs';\nappendFileSync(${JSON.stringify(log)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`);
+ writeFileSync(join(fakeDir, 'git'), `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${recorder}' "$@"\n`);
+ chmodSync(join(fakeDir, 'git'), 0o755);
+ });
+ beforeEach(() => { writeFileSync(log, ''); });
+ const cloneArgs = () => readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line) as string[]);
+ const run = (destination: string, skipLfs: boolean) => withEnv({ PATH: `${fakeDir}:${process.env.PATH}`, GBRAIN_HOME: home }, async () => {
+ mkdirSync(destination, { recursive: true });
+ await cloneTopologyCheckout('https://example.com/acme-example/brain.git', destination, 1 << 20, { skipLfs });
+ });
+
+ test('skipLfs puts lfs.fetchexclude=*, core.hooksPath=/dev/null and lfs.locksverify=false in the clone config', async () => {
+ await run(join(ROOT, 'topology-skip'), true);
+ const [args] = cloneArgs();
+ const after = args!.slice(args!.indexOf('clone'));
+ for (const setting of ['lfs.fetchexclude=*', 'core.hooksPath=/dev/null', 'lfs.locksverify=false'])
+ expect(after[after.indexOf(setting) - 1]).toBe('--config');
+ });
+
+ test('without skipLfs the clone config is left alone', async () => {
+ await run(join(ROOT, 'topology-plain'), false);
+ const [args] = cloneArgs();
+ expect(args!.includes('lfs.fetchexclude=*')).toBe(false);
+ expect(args!.includes('--config')).toBe(false);
+ });
+});
+
test('lfsDownloadsOff reads the record from an object or a JSON string and never throws', () => {
expect(lfsDownloadsOff({ added_by_remote_caller: true })).toBe(true);
expect(lfsDownloadsOff('{"added_by_remote_caller":true}')).toBe(true);