Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(git): commit ledger in the git common dir, recorded at every gbrain commit site (PR B part 3)

garrytan8cfd4d5e416c
diff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.ts
index 3e8e1baebe..002a6371f4 100644
--- a/src/core/bootstrap/repo.ts
+++ b/src/core/bootstrap/repo.ts
@@ -52,6 +52,7 @@ import {
type ManifestState,
} from './format.ts';
import { BootstrapError } from './lock.ts';
+import { recordCommitAsync, recordIntentAsync } from '../git/commit-ledger.ts';
// ---------------------------------------------------------------------------
// Exec seam (shared by uninstall.ts; the dispatcher passes the real runner)
@@ -478,6 +479,7 @@ async function ensureWorkspaceCommit(runner: ExecRunner, workspaceDir: string):
);
}
+ await recordIntentAsync(workspaceDir, { writer: 'bootstrap', head_before: hasCommit ? head.stdout.trim() || null : null, message: 'gbrain: bootstrap workspace' });
const commit = await runner(['git', '-C', workspaceDir, 'commit', '-m', 'gbrain: bootstrap workspace']);
if (commit.code !== 0 && !hasCommit) {
throw new BootstrapError(
@@ -485,6 +487,10 @@ async function ensureWorkspaceCommit(runner: ExecRunner, workspaceDir: string):
`git commit failed before the first push: ${commit.stderr.trim() || `exit ${commit.code}`}`,
);
}
+ if (commit.code === 0) {
+ const sha = await runner(['git', '-C', workspaceDir, 'rev-parse', 'HEAD']);
+ if (sha.code === 0) await recordCommitAsync(workspaceDir, { sha: sha.stdout.trim(), writer: 'bootstrap' });
+ }
}
/** The current branch, defaulting to 'main' (a pre-first-commit HEAD reports
diff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.ts
new file mode 100644
index 0000000000..ae256087d3
--- /dev/null
+++ b/src/core/git/commit-ledger.ts
@@ -0,0 +1,189 @@
+/**
+ * PR B Part 3 (docs/designs/REFRESH_WRITE_BARRIER.md): the commit ledger. Every commit gbrain makes in a repository is
+ * appended as one JSON line to `<git common dir>/gbrain/commit-ledger.jsonl`, which lives inside `.git` (never tracked,
+ * shared by every worktree, readable without a database). doctor's `foreign_writers` names every locally created commit
+ * that is not in it.
+ *
+ * - One ledger lock (`commit-ledger.lock` beside it) is taken for the start line, every append and rotation; it is held
+ * for microseconds and never while git runs.
+ * - The first append writes a `start` record: reflog entries older than it are uncovered, never foreign.
+ * - At 4 MiB the file rotates to `commit-ledger.1.jsonl` (one previous file kept).
+ * - Plumbing sites (`commit-tree`) record the sha before the ref moves. Porcelain sites (`git commit`) write an intent
+ * line (`head_before`, the message's sha256) first and the commit line after; doctor reports a commit matching an open
+ * intent as unconfirmed and never writes it back.
+ * - A failed append never fails the commit: it is logged once, and doctor then reports that commit as foreign (the safe
+ * direction for an alarm). A directory that is not a git repository records nothing.
+ */
+import { createHash } from 'node:crypto';
+import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { execFileSync } from '../spawn.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { acquireNativeLock, acquireNativeLockSync } from '../persistence/native-lock.ts';
+import { existingLocalHostId } from '../persistence/identity.ts';
+
+export type LedgerWriter = 'commit_push' | 'door' | 'merge' | 'replay' | 'effect' | 'sync_init' | 'workspace_push' | 'bootstrap' | 'hosted_repo';
+
+export const LEDGER_DIR = 'gbrain';
+export const LEDGER_FILE = 'commit-ledger.jsonl';
+export const LEDGER_ROTATED_FILE = 'commit-ledger.1.jsonl';
+export const LEDGER_LOCK_FILE = 'commit-ledger.lock';
+export const LEDGER_ROTATE_BYTES = 4 * 1024 * 1024;
+const LINE_MAX_BYTES = 1023;
+const LOCK_WAIT_MS = 2_000;
+
+export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null }
+export interface LedgerIntent { writer: LedgerWriter; head_before: string | null; message: string }
+
+export type LedgerRecord =
+ | { v: 1; e: 'start'; t: string }
+ | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null }
+ | { v: 1; e: 'intent'; t: string; writer: LedgerWriter; head_before: string | null; msg_sha256: string; worktree: string | null; pid: number; host: string | null };
+
+interface Location { common: string; gitDir: string; worktree: string | null }
+const locations = new Map<string, Location | null>();
+
+/** The repository's common dir, this checkout's git dir and toplevel (null for a bare repository); null outside git. */
+export function ledgerLocation(root: string): Location | null {
+ let key = resolve(root);
+ try { key = realpathSync(key); } catch { /* resolved below */ }
+ if (locations.has(key)) return locations.get(key)!;
+ let found: Location | null = null;
+ try {
+ const run = (args: string[]) => execFileSync('git', ['-C', key, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ LC_ALL: 'C' }) }).toString().split('\n');
+ const [gitDir, bare] = run(['rev-parse', '--absolute-git-dir', '--is-bare-repository']);
+ if (gitDir) {
+ let common = gitDir;
+ try { common = resolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim()); } catch { /* the main git dir is the common dir */ }
+ const worktree = bare === 'true' ? null : run(['rev-parse', '--show-toplevel'])[0] || null;
+ found = { gitDir, common, worktree };
+ }
+ } catch { found = null; }
+ locations.set(key, found);
+ return found;
+}
+
+export function ledgerFiles(common: string): { dir: string; current: string; rotated: string; lock: string } {
+ const dir = join(common, LEDGER_DIR);
+ return { dir, current: join(dir, LEDGER_FILE), rotated: join(dir, LEDGER_ROTATED_FILE), lock: join(dir, LEDGER_LOCK_FILE) };
+}
+
+/** sha256 of a commit message with git's whitespace cleanup applied, so the intent and the stored message compare. */
+export function messageDigest(message: string): string {
+ const out: string[] = [];
+ for (const text of message.replace(/\r\n/g, '\n').split('\n').map(l => l.replace(/\s+$/, ''))) {
+ if (!text && (!out.length || out[out.length - 1] === '')) continue;
+ out.push(text);
+ }
+ while (out.length && out[out.length - 1] === '') out.pop();
+ return createHash('sha256').update(out.join('\n')).digest('hex');
+}
+
+let warned = false;
+function warnOnce(root: string, error: unknown): void {
+ if (warned) return;
+ warned = true;
+ process.stderr.write(`[gbrain notice] commit ledger: could not record a commit in ${root} (${error instanceof Error ? error.message : String(error)}); doctor foreign_writers will report it as foreign.\n`);
+}
+
+function hostId(): string | null {
+ try { return existingLocalHostId(); } catch { return null; }
+}
+
+function headRef(gitDir: string): string | null {
+ try {
+ const head = readFileSync(join(gitDir, 'HEAD'), 'utf8').trim();
+ return head.startsWith('ref: ') ? head.slice(5) : null;
+ } catch { return null; }
+}
+
+/** One JSON line under 1 KiB: an over-long worktree path keeps its tail. */
+function line(record: LedgerRecord): string {
+ let text = JSON.stringify(record);
+ const over = Buffer.byteLength(text) - LINE_MAX_BYTES;
+ if (over > 0 && 'worktree' in record && record.worktree) {
+ text = JSON.stringify({ ...record, worktree: `...${record.worktree.slice(Math.min(record.worktree.length, over + 3))}` });
+ }
+ return `${text}\n`;
+}
+
+function commitRecord(loc: Location, entry: LedgerCommit): LedgerRecord {
+ return { v: 1, e: 'commit', t: new Date().toISOString(), sha: entry.sha, writer: entry.writer, request_id: entry.request_id ?? null,
+ worktree: loc.worktree, worktree_id: entry.worktree_id ?? null, ref: entry.ref === undefined ? headRef(loc.gitDir) : entry.ref, pid: process.pid, host: hostId() };
+}
+
+function intentRecord(loc: Location, intent: LedgerIntent): LedgerRecord {
+ return { v: 1, e: 'intent', t: new Date().toISOString(), writer: intent.writer, head_before: intent.head_before,
+ msg_sha256: messageDigest(intent.message), worktree: loc.worktree, pid: process.pid, host: hostId() };
+}
+
+/** Under the ledger lock: the start line on a new ledger, rotation at 4 MiB, then the append (O_APPEND). */
+function appendLocked(common: string, record: LedgerRecord): void {
+ const files = ledgerFiles(common);
+ const text = line(record);
+ let size = -1;
+ try { size = statSync(files.current).size; } catch { /* no current file */ }
+ if (size >= 0 && size + Buffer.byteLength(text) > LEDGER_ROTATE_BYTES) { renameSync(files.current, files.rotated); size = -1; }
+ if (size < 0 && !existsSync(files.rotated)) appendFileSync(files.current, line({ v: 1, e: 'start', t: record.t }));
+ appendFileSync(files.current, text);
+}
+
+function writeLocked(root: string, build: (loc: Location) => LedgerRecord): void {
+ const loc = ledgerLocation(root);
+ if (!loc) return;
+ try {
+ const files = ledgerFiles(loc.common);
+ mkdirSync(files.dir, { recursive: true });
+ const lock = acquireNativeLockSync(files.lock, { timeoutMs: LOCK_WAIT_MS });
+ if (!lock) throw new Error(`the ledger lock ${files.lock} stayed busy for ${LOCK_WAIT_MS} ms`);
+ try { appendLocked(loc.common, build(loc)); } finally { lock.release(); }
+ } catch (error) { warnOnce(root, error); }
+}
+
+async function writeLockedAsync(root: string, build: (loc: Location) => LedgerRecord): Promise<void> {
+ const loc = ledgerLocation(root);
+ if (!loc) return;
+ try {
+ const files = ledgerFiles(loc.common);
+ mkdirSync(files.dir, { recursive: true });
+ const lock = await acquireNativeLock(files.lock, { timeoutMs: LOCK_WAIT_MS });
+ if (!lock) throw new Error(`the ledger lock ${files.lock} stayed busy for ${LOCK_WAIT_MS} ms`);
+ try { appendLocked(loc.common, build(loc)); } finally { await lock.release(); }
+ } catch (error) { warnOnce(root, error); }
+}
+
+/** Ledger a commit gbrain made in the repository holding `root` (any directory inside it). Never throws. */
+export function recordCommit(root: string, entry: LedgerCommit): void {
+ if (entry.sha) writeLocked(root, loc => commitRecord(loc, entry));
+}
+export async function recordCommitAsync(root: string, entry: LedgerCommit): Promise<void> {
+ if (entry.sha) await writeLockedAsync(root, loc => commitRecord(loc, entry));
+}
+/** A porcelain site's intent, written before `git commit` runs. Never throws. */
+export function recordIntent(root: string, intent: LedgerIntent): void {
+ writeLocked(root, loc => intentRecord(loc, intent));
+}
+export async function recordIntentAsync(root: string, intent: LedgerIntent): Promise<void> {
+ await writeLockedAsync(root, loc => intentRecord(loc, intent));
+}
+
+/** The retained ledger lines, oldest first (the rotated file, then the current one); unparseable lines are skipped. */
+export function readLedger(common: string): LedgerRecord[] {
+ const files = ledgerFiles(common);
+ const out: LedgerRecord[] = [];
+ for (const file of [files.rotated, files.current]) {
+ let text: string;
+ try { text = readFileSync(file, 'utf8'); } catch { continue; }
+ for (const raw of text.split('\n')) {
+ if (!raw) continue;
+ try {
+ const record = JSON.parse(raw) as LedgerRecord;
+ if (record && record.v === 1 && typeof record.t === 'string') out.push(record);
+ } catch { /* a torn or foreign line */ }
+ }
+ }
+ return out;
+}
+
+/** Test seam: forget cached locations (a test that re-inits a directory) and the one-time warning. */
+export function resetLedgerCacheForTests(): void { locations.clear(); warned = false; }
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index a844378f9a..89d1e848cc 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -33,6 +33,7 @@ import { gitChildEnv, literalPathspecs } from '../git-env.ts';
import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, durableSsrfFlags } from '../git-transport.ts';
import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesystemRootFor, type ManagedFilesystemRoot } from '../persistence/filesystem-guard.ts';
import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';
+import { recordCommit, recordIntent } from './commit-ledger.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { shellQuote } from '../agent-output.ts';
@@ -452,12 +453,15 @@ function commitPaths(root: string, rel: string[], message: string, scope: Commit
const env = { [COMMIT_VIA_ENV]: scope.lockPath, ...(scope.markHeld ? { [COMMIT_LOCK_ENV]: scope.lockPath } : {}) };
// #7759: literal per path, never git's global --literal-pathspecs: Git exports that to the commit's hooks, where a
// guard's glob pathspec ('*.json') then matches nothing and lets the commit through.
+ recordIntent(root, { writer: 'commit_push', head_before: git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).stdout.trim() || null, message });
const commit = withIndexRetry(root, ['commit', '--only', '-m', message, '--', ...literalPathspecs(paths)], 'git commit', env);
if (commit.code !== 0) {
throw opError('git_unavailable', `git commit failed in ${root}; the paths were unstaged again and keep their bytes.`,
`${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);
}
- return gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
+ const sha = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
+ recordCommit(root, { sha, writer: 'commit_push' });
+ return sha;
} catch (e) {
try { restoreIndex(root, rel, before); } catch { /* the index lock outlasted the retries; the error below still stands */ }
throw e;
@@ -709,6 +713,7 @@ function integrate(root: string, local: string, remote: string): Integration {
for (const p of step.conflicts) conflicts.add(p);
for (const p of step.structural) structural.add(p);
acc = gitOk(root, ['commit-tree', '--no-gpg-sign', step.tree!, '-p', acc, '-m', 'gbrain: replay'], 'commit-tree');
+ recordCommit(root, { sha: acc, writer: 'replay', ref: null });
}
return { tree: treeOf(root, acc), conflicts: [...conflicts], structural: [...structural], skipped };
}
@@ -814,7 +819,9 @@ function buildMerge(ctx: Ctx, ours: string, theirs: string, tree: string, skippe
const remote = `${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')}`;
const note = skipped.length
? ['-m', `Left out ${skipped.length} local commit(s) whose patch ${remote} already has: ${skipped.slice(0, 20).map(s => s.slice(0, 12)).join(' ')}${skipped.length > 20 ? ' ...' : ''}`] : [];
- return gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs, '-m', `gbrain: merge ${remote} into ${ctx.branch}`, ...note, ...extra.flatMap(m => ['-m', m])], 'commit-tree');
+ const sha = gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs, '-m', `gbrain: merge ${remote} into ${ctx.branch}`, ...note, ...extra.flatMap(m => ['-m', m])], 'commit-tree');
+ recordCommit(ctx.root, { sha, writer: 'merge', ref: null });
+ return sha;
}
function fetchTracking(ctx: Ctx): string | null {
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 0e59669dbe..29cb68a08f 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -12,6 +12,7 @@ import { gitChildEnv, literalPathspecs } from '../git-env.ts';
import type { Action } from '../agent-output.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { proveIndexLockAbandoned, reclaimIndexLock, type IndexLockReclaim } from './index-lock-reclaim.ts';
+import { recordCommitAsync, recordIntentAsync } from '../git/commit-ledger.ts';
/** An index lock younger than this is contention; an older one is reported as stale. */
const INDEX_LOCK_GRACE_MS = 10 * 60 * 1000;
@@ -365,12 +366,19 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
let messageDir: string | undefined;
let result;
try {
- const message = commitMessageArgs(commitMessage(commitPaths, noted), () => {
+ const paragraphs = commitMessage(commitPaths, noted);
+ const message = commitMessageArgs(paragraphs, () => {
mkdirSync(persistenceHome(), { recursive: true, mode: 0o700 });
return messageDir = mkdtempSync(join(persistenceHome(), 'commit-message-'));
});
+ const before = await git(session, ['rev-parse', '--verify', '--quiet', 'HEAD']);
+ await recordIntentAsync(root, { writer: 'effect', head_before: before.code === 0 ? before.stdout.trim() : null, message: paragraphs.join('\n\n') });
result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...literalPathspecs(commitPaths)]);
} finally { if (messageDir) rmSync(messageDir, { recursive: true, force: true }); }
+ if (result.code === 0) {
+ const head = await git(session, ['rev-parse', 'HEAD']);
+ if (head.code === 0) await recordCommitAsync(root, { sha: head.stdout.trim(), writer: 'effect' });
+ }
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
for (const c of changed) results.set(c.requested, outcome);
diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.ts
index 88c9d93bc9..a573c663cd 100644
--- a/src/core/persistence/git-door.ts
+++ b/src/core/persistence/git-door.ts
@@ -52,6 +52,7 @@ import { hashFile } from './large-file.ts';
import type { FileRecoveryRecord, SqlEngine } from './model.ts';
import { nativeFileTarget } from './native-file-target.ts';
import type { NativeLockHandle } from './native-lock.ts';
+import { recordCommitAsync } from '../git/commit-ledger.ts';
import { committedBlob, headBlob, headCommit } from './pending-import.ts';
/** Whether `sourceId` is a strict (git-canonical) source; `lock` reads its row FOR SHARE inside a publication. */
@@ -327,6 +328,7 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],
if (commit.code !== 0) throw gitFailure('Cannot commit the canonical Git target.',
`git commit-tree failed for ${changed.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
const created = commit.stdout.trim();
+ await recordCommitAsync(root, { sha: created, writer: 'door', ref: branch });
await doorSeams.beforeUpdateRef?.(root, attempt);
const moved = await git(session, ['update-ref', '-m', `commit: ${message[0]!.split('\n')[0]}`, branch, created, head]);
if (moved.code === 0) {
diff --git a/src/core/persistence/hosted-repo.ts b/src/core/persistence/hosted-repo.ts
index 51a2b31e9b..1b5c03666e 100644
--- a/src/core/persistence/hosted-repo.ts
+++ b/src/core/persistence/hosted-repo.ts
@@ -29,6 +29,7 @@ import { parseSourceConfig } from '../sources-load.ts';
import { isValidSourceId } from '../source-id.ts';
import { containsPath, managedPersistenceEnabled } from './ownership.ts';
import { assertLinkedWorktreeIntact, linkedWorktreeProblem } from './worktree-link.ts';
+import { recordCommit } from '../git/commit-ledger.ts';
export const HOSTED_BRANCH = 'main';
const HOOK_BANNER = '# gbrain hosted-repo pre-receive hook (G7b-2)';
@@ -197,6 +198,7 @@ export async function hostRepo(engine: BrainEngine, opts: HostRepoOptions): Prom
const blob = git(plan.repository, ['hash-object', '-w', '--stdin'], '');
const tree = git(plan.repository, ['mktree'], `100644 blob ${blob}\t.gitignore\n`);
const commit = git(plan.repository, ['commit-tree', tree, '-m', `gbrain: host source ${opts.sourceId}`]);
+ recordCommit(plan.repository, { sha: commit, writer: 'hosted_repo', ref: `refs/heads/${plan.branch}` });
git(plan.repository, ['update-ref', `refs/heads/${plan.branch}`, commit, '']);
if (opts.pushRemote) {
git(plan.repository, ['remote', 'add', 'origin', opts.pushRemote]);
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
index 1575a5455e..df17e7189f 100644
--- a/src/core/sync-git.ts
+++ b/src/core/sync-git.ts
@@ -13,6 +13,7 @@ import { DELETE_BATCH_SIZE } from './engine-constants.ts';
import { invalidateGitListingCache, knownOutsideGitRepo, noteGitFailure } from './git-visible-files.ts';
import { hasUnresolvedDbOnlyDeclaration, loadStorageConfig } from './storage-config.ts';
import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';
+import { recordCommit, recordIntent } from './git/commit-ledger.ts';
/**
* v0.32.7 CJK wave (codex post-merge F4): resolve a slug by `pages.source_path`
@@ -592,6 +593,7 @@ export function createSyncBaselineCommit(repoPath: string): void {
const stderr = err && typeof err === 'object' && 'stderr' in err ? String((err as { stderr: unknown }).stderr) : '';
if (!stderr.includes('ignored by one of your .gitignore files')) throw err;
}
+ recordIntent(repoPath, { writer: 'sync_init', head_before: null, message: 'gbrain: initial commit (auto-init by sync)' });
git(
repoPath,
// --no-verify only skips pre-commit/commit-msg — prepare-commit-msg
@@ -613,6 +615,7 @@ export function createSyncBaselineCommit(repoPath: string): void {
],
['user.name=gbrain', 'user.email=gbrain@localhost', 'core.hooksPath=/dev/null'],
);
+ recordCommit(repoPath, { sha: git(repoPath, ['rev-parse', 'HEAD']), writer: 'sync_init' });
}
/**
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index a8f2815b85..28028ad308 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -78,6 +78,7 @@ import {
import { scanTextStream } from './secret-scan-stream.ts';
import { shellQuote } from './mcp-registration.ts';
import { gitChildEnv } from './git-env.ts';
+import { recordCommit, recordIntent } from './git/commit-ledger.ts';
// ── Types ───────────────────────────────────────────────────────────────────
@@ -1074,8 +1075,11 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
try {
const clean = tryGit(root, ['diff', '--cached', '--quiet']) !== null;
if (!clean) {
- git(root, ['commit', '-m', opts.commitMessage ?? 'gbrain: workspace push'], { timeoutMs: 60_000 });
+ const message = opts.commitMessage ?? 'gbrain: workspace push';
+ recordIntent(root, { writer: 'workspace_push', head_before: tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD']), message });
+ git(root, ['commit', '-m', message], { timeoutMs: 60_000 });
committed = true;
+ recordCommit(root, { sha: tryGit(root, ['rev-parse', 'HEAD']) ?? '', writer: 'workspace_push' });
}
} catch (e) {
return finish({
diff --git a/test/commit-ledger.test.ts b/test/commit-ledger.test.ts
new file mode 100644
index 0000000000..686678445b
--- /dev/null
+++ b/test/commit-ledger.test.ts
@@ -0,0 +1,98 @@
+/**
+ * PR B Part 3: the commit ledger at <git common dir>/gbrain/commit-ledger.jsonl. Real git repositories in temp dirs.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LEDGER_ROTATE_BYTES, ledgerFiles, messageDigest, readLedger, recordCommit, recordIntent } from '../src/core/git/commit-ledger.ts';
+import { commitPathsLocked } from '../src/core/git/commit-push.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-commit-ledger-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+function git(cwd: string, args: string[]): string {
+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
+}
+let n = 0;
+function repo(): string {
+ const root = join(dir, `repo-${n++}`);
+ mkdirSync(root);
+ git(root, ['init', '-q', '-b', 'main']);
+ git(root, ['config', 'user.email', '[email protected]']);
+ git(root, ['config', 'user.name', 'Alice Example']);
+ writeFileSync(join(root, 'seed.md'), 'seed\n');
+ git(root, ['add', '-A']);
+ git(root, ['commit', '-q', '-m', 'seed']);
+ return root;
+}
+
+test('the first append writes a start line, then one JSON line per record under 1 KiB', () => {
+ const root = repo();
+ const head = git(root, ['rev-parse', 'HEAD']);
+ mkdirSync(join(root, 'notes'));
+ recordCommit(join(root, 'notes'), { sha: head, writer: 'door', request_id: null });
+ recordIntent(root, { writer: 'commit_push', head_before: head, message: 'subject\n\nbody' });
+ const records = readLedger(join(root, '.git'));
+ expect(records.map(r => r.e)).toEqual(['start', 'commit', 'intent']);
+ const commit = records[1]!;
+ expect(commit).toMatchObject({ v: 1, e: 'commit', sha: head, writer: 'door', ref: 'refs/heads/main', worktree: git(root, ['rev-parse', '--show-toplevel']), pid: process.pid });
+ for (const line of readFileSync(ledgerFiles(join(root, '.git')).current, 'utf8').split('\n').filter(Boolean)) expect(Buffer.byteLength(line)).toBeLessThan(1024);
+});
+
+test('a linked worktree appends to the one ledger in the common dir', () => {
+ const root = repo();
+ const linked = join(dir, `linked-${n++}`);
+ git(root, ['worktree', 'add', '-q', '-b', 'side', linked]);
+ recordCommit(linked, { sha: git(linked, ['rev-parse', 'HEAD']), writer: 'effect' });
+ const records = readLedger(join(root, '.git'));
+ expect(records.find(r => r.e === 'commit')).toMatchObject({ writer: 'effect', ref: 'refs/heads/side' });
+ expect(existsSync(join(root, '.git', 'worktrees'))).toBe(true);
+});
+
+test('at 4 MiB the ledger rotates to commit-ledger.1.jsonl without a new start line; both files are read', () => {
+ const root = repo();
+ const files = ledgerFiles(join(root, '.git'));
+ recordCommit(root, { sha: 'a'.repeat(40), writer: 'door' });
+ const filler = `${JSON.stringify({ v: 1, e: 'commit', t: new Date().toISOString(), sha: 'b'.repeat(40), writer: 'door' })}\n`;
+ writeFileSync(files.current, readFileSync(files.current, 'utf8') + filler.repeat(Math.ceil(LEDGER_ROTATE_BYTES / filler.length)));
+ recordCommit(root, { sha: 'c'.repeat(40), writer: 'merge' });
+ expect(existsSync(files.rotated)).toBe(true);
+ expect(statSync(files.current).size).toBeLessThan(1024);
+ const current = readFileSync(files.current, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l));
+ expect(current.map(r => r.e)).toEqual(['commit']);
+ const all = readLedger(join(root, '.git'));
+ expect(all[0]!.e).toBe('start');
+ expect(all.at(-1)).toMatchObject({ sha: 'c'.repeat(40), writer: 'merge' });
+});
+
+test('a directory outside git records nothing and never throws', () => {
+ const plain = mkdtempSync(join(dir, 'plain-'));
+ expect(() => recordCommit(plain, { sha: 'a'.repeat(40), writer: 'bootstrap' })).not.toThrow();
+ expect(existsSync(join(plain, '.git'))).toBe(false);
+});
+
+test('a failed append never fails the commit (commit-push still commits)', () => {
+ const root = repo();
+ writeFileSync(join(root, '.git', 'gbrain'), 'not a directory');
+ writeFileSync(join(root, 'page.md'), 'page\n');
+ const sha = commitPathsLocked(root, ['page.md'], 'add page', { lockWaitMs: 1000 });
+ expect(sha).toBe(git(root, ['rev-parse', 'HEAD']));
+});
+
+test('commit-push records an intent with head_before and the message digest, then the commit', () => {
+ const root = repo();
+ const before = git(root, ['rev-parse', 'HEAD']);
+ writeFileSync(join(root, 'page.md'), 'page\n');
+ const sha = commitPathsLocked(root, ['page.md'], 'add page', { lockWaitMs: 1000 })!;
+ const records = readLedger(join(root, '.git'));
+ const intent = records.find(r => r.e === 'intent');
+ expect(intent).toMatchObject({ writer: 'commit_push', head_before: before, msg_sha256: messageDigest(git(root, ['log', '-1', '--format=%B', sha])) });
+ expect(records.find(r => r.e === 'commit')).toMatchObject({ writer: 'commit_push', sha });
+});
+
+test('messageDigest applies git whitespace cleanup', () => {
+ expect(messageDigest('subject \n\n\n\nbody\n\n')).toBe(messageDigest('subject\n\nbody'));
+ expect(messageDigest('a')).not.toBe(messageDigest('b'));
+});