Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(takes): commit fence writes on durability-hardened repos (#5638)

garrytan14a865deb280
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index 2cca0723d1..4141922c91 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -56,6 +56,7 @@ import { resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';
import { sanitizeRecordedSourcePath, recordedPathFromFileUri, scannerSlugRootMode } from './write-through.ts';
import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';
import { atomicWriteFileSync } from './atomic-write.ts';
+import { commitWriteThroughFile, isDurabilityHardened } from './brain-repo-durability.ts';
export type TakesWriteErrorCode =
| 'page_not_found' // slug has no pages row (scoped)
@@ -354,7 +355,7 @@ function readPageBody(path: string): string {
* not escape), then atomic temp+rename so a reader never observes a torn file
* and a crash mid-write leaves only a tmp sibling.
*/
-function writePageBody(path: string, body: string, writeRoot: string): void {
+function writePageBody(path: string, body: string, writeRoot: string, slug: string): void {
if (!isWriteTargetContained(path, writeRoot)) {
throw new TakesWriteError(
'mirror_unavailable',
@@ -364,6 +365,9 @@ function writePageBody(path: string, body: string, writeRoot: string): void {
}
mkdirSync(dirname(path), { recursive: true });
atomicWriteFileSync(path, body);
+ // Same #2426 contract as put_page write-through: a durability-hardened repo
+ // gets a best-effort, path-limited commit; a failed commit never fails the write.
+ if (isDurabilityHardened(writeRoot)) commitWriteThroughFile(writeRoot, path, slug);
}
/**
@@ -559,7 +563,7 @@ export async function addTakeToPage(
sinceDate: input.sinceDate,
active: true,
});
- writePageBody(path, nextBody, writeRoot);
+ writePageBody(path, nextBody, writeRoot, target.slug);
let mirrorWarning: string | undefined;
try {
await target.engine.addTakesBatch([{
@@ -620,7 +624,7 @@ export async function appendTakesToPageMdFirst(
// mirror_unavailable) — see the contract note above.
const body = readPageBody(path);
const { body: nextBody, rowNums } = appendTakesToPageBody(body, rows);
- writePageBody(path, nextBody, writeRoot);
+ writePageBody(path, nextBody, writeRoot, target.slug);
// Mirror md→DB with the reconcile primitive, exactly as the fence now
// states the appended rows.
const appended = new Set(rowNums);
@@ -676,7 +680,7 @@ export async function updateTakeOnPage(
sinceDate: fields.sinceDate ?? targetRow.sinceDate,
};
const allRows = parsed.takes.map(t => (t.rowNum === rowNum ? updated : t));
- writePageBody(path, replaceFence(body, allRows), writeRoot);
+ writePageBody(path, replaceFence(body, allRows), writeRoot, target.slug);
// Mirror md→DB with the reconcile primitive (upsert on (page_id,row_num));
// base columns only, resolution columns preserved by the DO UPDATE list.
let mirrorWarning: string | undefined;
@@ -738,7 +742,7 @@ export async function supersedeTakeOnPage(
sinceDate: input.sinceDate,
source: input.source,
});
- writePageBody(path, nextBody, writeRoot);
+ writePageBody(path, nextBody, writeRoot, target.slug);
// Mirror BOTH affected rows exactly as the fence now states them:
// old → inactive + superseded_by pointer, new → active append.
const after = parseTakesFence(nextBody).takes;
@@ -808,7 +812,7 @@ export async function resolveTakeOnPage(
resolvedBy: input.resolvedBy,
};
const allRows = parsed.takes.map(t => (t.rowNum === rowNum ? updated : t));
- writePageBody(path, replaceFence(body, allRows), writeRoot);
+ writePageBody(path, replaceFence(body, allRows), writeRoot, target.slug);
// Resolution fields aren't in TakeBatchInput — mirror via resolveTake.
// A drifted DB missing the row is self-healed md→DB (upsert the base row,
// then resolve): the markdown is the truth being propagated.
diff --git a/test/takes-write-through-commit.serial.test.ts b/test/takes-write-through-commit.serial.test.ts
new file mode 100644
index 0000000000..b3dbec467b
--- /dev/null
+++ b/test/takes-write-through-commit.serial.test.ts
@@ -0,0 +1,80 @@
+/**
+ * #5638: a takes fence write lands in git on a durability-hardened repo, the
+ * same #2426 contract put_page write-through follows. Unhardened repos keep
+ * the write-only behavior.
+ *
+ * .serial: real git subprocesses against tmp repos.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { addTakeToPage, updateTakeOnPage } from '../src/core/takes-write.ts';
+
+let engine: PGLiteEngine;
+const dirs: string[] = [];
+const slug = 'notes/takes-commit-example';
+
+const git = (repo: string, ...args: string[]) =>
+ execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+async function seedRepo(hardened: boolean): Promise<string> {
+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-takes-commit-'));
+ dirs.push(repo);
+ const fixture = await makeGitFixture(repo);
+ if (hardened) {
+ mkdirSync(join(repo, '.git', 'hooks'), { recursive: true });
+ writeFileSync(join(repo, '.git', 'hooks', 'post-commit'), '#!/usr/bin/env bash\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n');
+ chmodSync(join(repo, '.git', 'hooks', 'post-commit'), 0o755);
+ }
+ await engine.putPage(slug, { type: 'note', title: 'Takes commit example', compiled_truth: 'About the example.' });
+ const snapshot = (await engine.readPageSnapshot(slug))!;
+ mkdirSync(join(repo, 'notes'), { recursive: true });
+ writeFileSync(join(repo, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ writeFileSync(join(repo, 'unrelated.md'), 'committed\n');
+ fixture.commitAll('seed page');
+ writeFileSync(join(repo, 'unrelated.md'), 'dirty unrelated edit\n');
+ return repo;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+beforeEach(async () => { await resetPgliteState(engine); });
+afterAll(async () => {
+ await engine.disconnect();
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
+});
+
+test('on a hardened repo each fence mutation commits only the page file', async () => {
+ const repo = await seedRepo(true);
+ const head = git(repo, 'rev-parse', 'HEAD');
+ const target = { engine, slug, brainDir: repo };
+
+ const added = await addTakeToPage(target, { claim: 'This take reaches git', kind: 'take', holder: 'world' });
+ expect(git(repo, 'rev-list', '--count', `${head}..HEAD`)).toBe('1');
+ expect(git(repo, 'log', '-1', '--format=%s')).toBe(`gbrain: write-through ${slug}`);
+ expect(git(repo, 'show', '--name-only', '--format=', 'HEAD')).toBe(`${slug}.md`);
+ expect(git(repo, 'show', `HEAD:${slug}.md`)).toContain('This take reaches git');
+
+ await updateTakeOnPage(target, added.rowNum, { weight: 0.9 });
+ expect(git(repo, 'rev-list', '--count', `${head}..HEAD`)).toBe('2');
+ expect(git(repo, 'status', '--porcelain')).toBe('M unrelated.md');
+ expect(readFileSync(join(repo, 'unrelated.md'), 'utf8')).toBe('dirty unrelated edit\n');
+});
+
+test('on an unhardened repo the fence write stays uncommitted', async () => {
+ const repo = await seedRepo(false);
+ const head = git(repo, 'rev-parse', 'HEAD');
+ const result = await addTakeToPage({ engine, slug, brainDir: repo }, { claim: 'Written but not committed', kind: 'take', holder: 'world' });
+ expect(result.mirror.written).toBe(true);
+ expect(git(repo, 'rev-parse', 'HEAD')).toBe(head);
+ expect(git(repo, 'status', '--porcelain').split('\n').map(line => line.trim()).sort()).toEqual(['M notes/takes-commit-example.md', 'M unrelated.md']);
+});