Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan55c6d3ea7fdd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a62947fad2..aa7dc3ecf4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,15 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**`gbrain sources record-origin --remote` can no longer report success while a reclone still clones with git-lfs on, and it locks down the existing checkout too.** On a managed brain the record took only the source row lock, so a reclone that had already read the source, or held its worktree locks, could clone with git-lfs downloads and hooks on after the command said the source was recorded. The record now takes the worktree locks and rows a reclone takes (refusing the id `source_busy` while one runs), and the reclone reads the record under its own locks. `--remote --apply` now also turns git-lfs downloads and hooks off in the existing checkout's `.git/config`, because a reclone only happens when a checkout is lost or replaced, and until then doctor read green while the checkout still fetched git-lfs objects and ran hooks. The git-lfs check now reads a committed `.gitattributes` under a directory whose name holds a tab (it was cut at the tab and skipped), ignores commented-out `filter=lfs` lines, says "declares a git-lfs filter" when a rule only declares one, and records a clone of an empty repository instead of telling the operator to restore an intact checkout. A failed write is reported for its own id instead of ending the run without saying which ids were recorded.+**On a managed brain, `gbrain sources record-origin --remote` can no longer report success while a reclone still clones with git-lfs on, and it locks down the existing checkout too.** On a managed brain the record took only the source row lock, so a reclone that had already read the source, or held its worktree locks, could clone with git-lfs downloads and hooks on after the command said the source was recorded. The record now takes the worktree locks and rows a reclone takes (refusing the id `source_busy` while one runs), and the reclone reads the record under its own locks. `--remote --apply` now also turns git-lfs downloads and hooks off in the existing checkout's `.git/config`, because a reclone only happens when a checkout is lost or replaced, and until then doctor read green while the checkout still fetched git-lfs objects and ran hooks. The git-lfs check now reads a committed `.gitattributes` under a directory whose name holds a tab (it was cut at the tab and skipped), ignores commented-out `filter=lfs` lines, says "declares a git-lfs filter" when a rule only declares one, and records a clone of an empty repository instead of telling the operator to restore an intact checkout. A failed write is reported for its own id instead of ending the run without saying which ids were recorded.### Itemized changes-- `src/core/url-source-origin.ts`: on a managed brain each apply runs inside `withTopologyLocks` and `lockTopologyRows` (a held lock 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; a throw is reported per id as `write_failed` 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: checkout missing, not its own repository's top level (an enclosing repository, or none), or a Git read failed.+- `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; 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: checkout missing, not its own repository's top level (an enclosing repository, or none), or a Git read failed.- `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.- Docs: `docs/guides/repair.md#url-source-origin` (checkout lock-down and why, `source_busy`, `write_failed`, `lfs_tracked` and `lfs_unknown` causes), the key-files row in `docs/architecture/key-files/files-and-sync-2.md`, `docs/architecture/canonical-writers.tsv`.-- Tests: `test/url-source-origin.test.ts` (PGLite and Postgres): a record attempted while a reclone holds its locks is refused and writes nothing; a reclone that read the source before a record landed clones with the recorded settings; the existing checkout gets the lock-down on apply and not on preview; a tab-named directory's `.gitattributes` is read; commented rules are ignored and a declared-only rule is worded as declared; an empty-repository clone records; each `lfs_unknown` cause is named; a mid-batch write failure is reported for its id while the others record.+- Tests: `test/url-source-origin.test.ts` (PGLite and Postgres): a record attempted while a reclone holds its locks is refused and writes nothing; a reclone that read the source before a record landed clones with the recorded settings; the existing checkout gets the lock-down on apply and not on preview; a tab-named directory's `.gitattributes` is read; commented rules are ignored and a declared-only rule is worded as declared; an empty-repository clone records; each `lfs_unknown` cause is named; a mid-batch write failure is reported for its id while the others record; a record during an active refresh is refused `source_busy`; a lock-down that fails part way is reported as a partial change.## [0.60.620.0] - 2026-11-09**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 9970caca5c..90f8f6a084 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2850,8 +2850,10 @@ transaction and refuses `source_changed` if it moved since the check. On amanaged brain it first takes the worktree locks and rows a reclone takes, sono reclone runs between the record and the clone; while a reclone, refresh orwrite holds them the id is refused `source_busy` (nothing changed; run it-again once that finishes). A write that fails is reported for its own id as-`write_failed`, and the other ids keep their results. Without git-lfs files a+again once that finishes, and finish a refresh with `gbrain sources refresh+<id> --resume`). A write that fails is reported for its own id as+`write_failed`, saying whether the checkout already got all or part of the+lock-down, and the other ids keep their results. Without git-lfs files aclone with these settings holds the same tracked bytes, so the stored writermanifest needs no change and the reclone verifies as before. `--remote`refuses, writing nothing:diff --git a/src/core/url-source-origin.ts b/src/core/url-source-origin.tsindex ffa105532f..ace670a183 100644--- a/src/core/url-source-origin.ts+++ b/src/core/url-source-origin.ts@@ -169,7 +169,7 @@ export async function recordSourceOrigin(engine: BrainEngine, ids: string[], optconst locks = opts.apply && await managedPersistenceEnabled(engine)? { ...await import('./persistence/topology-locks.ts'), ...await import('./persistence/topology-transaction.ts') } : null;for (const id of [...new Set(ids)]) {- let lockedDown = false;+ const lockDown: { state: 'none' | 'started' | 'done' } = { state: 'none' };try {const [row] = await engine.executeRaw<SourceRowLike>('SELECT id, local_path, config, archived FROM sources WHERE id=$1', [id]);const early = check(row, id, opts.origin);@@ -188,8 +188,9 @@ export async function recordSourceOrigin(engine: BrainEngine, ids: string[], optif (remote) {const lfsNow = lfsRefusal(id, locked!.local_path!);if (lfsNow) return lfsNow;+ lockDown.state = 'started';lockDownCheckout(locked!.local_path!);- lockedDown = true;+ lockDown.state = 'done';}await tx.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1',[id, JSON.stringify(normalizeSourceConfig({ ...config, added_by_remote_caller: remote }))]);@@ -200,10 +201,15 @@ export async function recordSourceOrigin(engine: BrainEngine, ids: string[], opt: await engine.transaction(write));} catch (error) {const message = error instanceof Error ? error.message : String(error);- const lockdown = lockedDown ? ' Its checkout already has git-lfs downloads and hooks off.' : '';- results.push((error as { code?: string }).code === 'write_pending'- ? refusal(id, 'source_busy', `Another gbrain process (a reclone, refresh or write) holds source ${id}'s worktree locks, so its origin was not recorded; nothing changed. Run this again once that process finishes.`)- : refusal(id, 'write_failed', `Recording source ${id}'s origin failed: ${message} The record was not written.${lockdown} The other ids in this run keep their own results; run this again for ${id}.`));+ const lockdown = lockDown.state === 'done' ? ' Its checkout already has git-lfs downloads and hooks off.'+ : lockDown.state === 'started' ? " Its checkout's .git/config may already hold part of the git-lfs and hooks lock-down; running this again writes all of it." : '';+ const unchanged = lockdown ? `the record was not written.${lockdown}` : 'nothing changed.';+ const code = (error as { code?: string }).code;+ results.push(code === 'write_pending'+ ? refusal(id, 'source_busy', `Another gbrain process (a reclone, refresh or write) holds source ${id}'s worktree locks, so its origin was not recorded; ${unchanged} Run this again once that process finishes.`)+ : code === 'refresh_in_progress'+ ? refusal(id, 'source_busy', `A refresh of the worktree holding source ${id} is still running, so its origin was not recorded; ${unchanged} Finish it (gbrain sources refresh ${id} --resume), then run this again.`)+ : refusal(id, 'write_failed', `Recording source ${id}'s origin failed: ${message} The record was not written.${lockdown} The other ids in this run keep their own results; run this again for ${id}.`));}}return { origin: opts.origin, apply: opts.apply, results };diff --git a/test/url-source-origin.test.ts b/test/url-source-origin.test.tsindex 4c2d15be52..c085f6b0ab 100644--- a/test/url-source-origin.test.ts+++ b/test/url-source-origin.test.ts@@ -1,5 +1,6 @@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 { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';@@ -379,4 +380,37 @@ for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const)expect(await config('source-b')).toEqual(URL_CONFIG);expect(await config('source-c')).toEqual({ ...URL_CONFIG, added_by_remote_caller: false });}), 60_000);++ test('--remote --apply on a managed source whose worktree has an active refresh is refused source_busy and writes nothing', () => brain(async home => {+ const { source, root } = await managedUrlSource(home, false);+ const [binding] = await engine.executeRaw<{ worktree_id: string }>('SELECT worktree_id::text FROM persistence_source_bindings WHERE source_id=$1', [source]);+ await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes(worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)+ VALUES($1::uuid,ARRAY[$2::text],$3::uuid,1,1,'draining','a','b','origin/main')`, [binding!.worktree_id, source, randomUUID()]);+ const [result] = (await recordSourceOrigin(engine, [source], { origin: 'remote', apply: true, remote: false })).results;+ expect(result).toMatchObject({ source_id: source, status: 'refused', code: 'source_busy' });+ expect(result!.reason).toContain('refresh');+ expect(result!.reason).toContain('nothing changed');+ expect(lfsDownloadsOff(await config(source))).toBe(false);+ expect(localConfig(root, 'core.hooksPath')).toBeNull();+ }), 120_000);++ test('a lock-down that fails part way is reported as a partial change to the checkout, and the record is not written', () => brain(async () => {+ const root = defaultCloneDir('source-a');+ repoAt(root, { 'example.md': 'Canonical\n' });+ await insert('source-a', root, URL_CONFIG);+ const original = childProcess.execFileSync;+ let writes = 0;+ const patched = spyOn(childProcess, 'execFileSync').mockImplementation(((file: string, args?: readonly string[], options?: object) => {+ if (file === 'git' && args?.includes('--file') && ++writes === 2) throw new Error('config write failed (example)');+ return original(file, args as string[], options as never);+ }) as typeof childProcess.execFileSync);+ let report: Awaited<ReturnType<typeof recordSourceOrigin>>;+ try { report = await recordSourceOrigin(engine, ['source-a'], { origin: 'remote', apply: true, remote: false }); }+ finally { patched.mockRestore(); }+ expect(report.results[0]).toMatchObject({ source_id: 'source-a', status: 'refused', code: 'write_failed' });+ expect(report.results[0]!.reason).toContain('part of the git-lfs and hooks lock-down');+ expect(report.results[0]!.reason).not.toContain('already has git-lfs downloads and hooks off');+ expect(localConfig(root, 'lfs.fetchexclude')).toBe('*');+ expect(await config('source-a')).toEqual(URL_CONFIG);+ }), 60_000);});