Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
PR B /ship fixes: deferred writes exit 10 on every CLI route, idle owners expire overdue deferred writes, owner guard keeps the durability hook
garrytan868f87bd77fe
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex 9b2946fcf6..2f65edba1c 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -16,4 +16,4 @@ Key files:- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files. Tests: `test/commit-ledger.test.ts`.- `src/commands/doctor/checks/foreign-writers.ts` — `foreign_writers` (PR B part 4): every registered source checkout on this host, managed worktrees included, deduplicated by git common dir. Reflogs (`logs/HEAD`, `logs/refs/heads/*`, `worktrees/*/logs/HEAD`, newest 5,000 entries each) are classified by `classifyReflogMessage`: porcelain creations by new sha, other ref moves by the `old..new` range within 10 minutes of the entry, merges/fast-forwards/resets/checkouts/branch/clone excluded. Unledgered commits fail (`plain`, `amend`, `rewrite`, `plumbing`; `guard_bypassed` when the enforce guard predates the commit); intent matches are `unconfirmed` (warn, never written back); entries before the ledger start are uncovered. Dirty page files come from `status --porcelain=v2` under the source roots minus queued/running git effects and the write-through pending ledger. Repo-less: `not_applicable`. Tests: `test/doctor-foreign-writers.test.ts`.-- `src/commands/sources-guard.ts` — `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]` (PR B part 5): owner host only (`permission_denied` elsewhere), install/uninstall under the worktree's native writer lock (`acquireWorktree`). `commit-guard.ts` `installOwnerGuard` writes the hook to `<worktree git dir>/gbrain-hooks` and sets `git config --worktree core.hooksPath` (enabling `extensions.worktreeConfig`, moving `core.bare`/`core.worktree` to `config.worktree`, only when linked worktrees exist), refusing when another tool's hook lives at the effective hooks path; both owner-path modes exit 0 outside the owner worktree (a worktree added after the install inherits its hooks path through `config.worktree`), `renderGuardHook('enforce')` keeps only the merge exemption, and `renderGuardHook()` with no mode stays byte-identical to the opt-in `gbrain git guard` hook. Tests: `test/sources-guard.test.ts`.+- `src/commands/sources-guard.ts` — `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]` (PR B part 5): owner host only (`permission_denied` elsewhere), install/uninstall under the worktree's native writer lock (`acquireWorktree`). `commit-guard.ts` `installOwnerGuard` writes the hook to `<worktree git dir>/gbrain-hooks` and sets `git config --worktree core.hooksPath` (enabling `extensions.worktreeConfig`, moving `core.bare`/`core.worktree` to `config.worktree`, only when linked worktrees exist), refusing when another tool's hook lives at the effective hooks path and copying gbrain's own hooks there (the brain-durability post-commit hook, so an unrecorded binding stays durable); both owner-path modes exit 0 outside the owner worktree (a worktree added after the install inherits its hooks path through `config.worktree`), `renderGuardHook('enforce')` keeps only the merge exemption, and `renderGuardHook()` with no mode stays byte-identical to the opt-in `gbrain git guard` hook. Tests: `test/sources-guard.test.ts`.diff --git a/docs/designs/REFRESH_WRITE_BARRIER.md b/docs/designs/REFRESH_WRITE_BARRIER.mdindex 43dad5ccde..21636b9b1e 100644--- a/docs/designs/REFRESH_WRITE_BARRIER.md+++ b/docs/designs/REFRESH_WRITE_BARRIER.md@@ -175,7 +175,8 @@ refuses `worktree_refreshing` as today (retryable, `fix.next: wait`).**Age bound.** A deferred row whose refresh is still unreleased after`persistence.refresh_barrier_max_wait_ms` (default 15 minutes; a tick runs a few minutes) is finished-`failed` with `refresh_barrier_expired` by the owner consumer's housekeeping turn, in one statement+`failed` with `refresh_barrier_expired` by the owner consumer's housekeeping turn (its idle probe+counts an overdue deferred row as work, so an otherwise idle owner still runs it), in one statementthat rechecks `released_at IS NULL` and releases its counters. Nothing is applied; the producerresubmits with a new request id. If the owner host is down, nothing claims or expires rows; receiptsstay pending and readable, as for any queued row on that host.@@ -241,7 +242,9 @@ Deferred rows are durable rows; nothing about them lives in process memory.### Surfaces- CLI write verbs: deferred → exit 10 with the receipt (`state: deferred`, `deferred`), `--json`- carries `outcome: pending`. `gbrain write-request <id>` shows the deferral until it drains.+ carries `outcome: pending`. This holds on every CLI route: the owner socket asks dispatch for the+ `write_pending` error (`pendingAsError`), and a thin client turns a `status: "pending"` success+ into the same pending error. `gbrain write-request <id>` shows the deferral until it drains.- MCP: deferred → `isError: false`, `status: "pending"`; `requestLogStatusForResult` classifies apending non-error result as `accepted_pending` (today it only reads pending from error results).Other `write_pending` results (an acknowledgement lost to the owner) are unchanged.diff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsindex 425802325d..fb3415422e 100644--- a/src/core/git/commit-guard.ts+++ b/src/core/git/commit-guard.ts@@ -172,7 +172,9 @@ export function ownerGuardStatus(worktree: string): OwnerGuardStatus {* Point only this worktree's core.hooksPath at a hooks directory inside its own git dir and write the guard there. With* linked worktrees present, extensions.worktreeConfig is enabled first (moving core.bare / core.worktree into the main* worktree's config.worktree, as git requires), so a sibling worktree keeps its own hooks. Refuses, changing nothing, on- * git older than 2.31 or another tool's hook at the effective hooks path. The caller holds the worktree's writer lock.+ * git older than 2.31 or another tool's hook at the effective hooks path. gbrain's own hooks there (the brain-durability+ * post-commit hook decides whether Git effects commit and push) are copied along, so the switch silences none of them.+ * The caller holds the worktree's writer lock.*/export function installOwnerGuard(worktree: string, mode: GuardMode): OwnerGuardStatus & { changed: boolean } {const p = ownerPaths(worktree);@@ -195,6 +197,14 @@ export function installOwnerGuard(worktree: string, mode: GuardMode): OwnerGuardchanged = true;}if (p.effective !== p.own) {+ for (const name of existsSync(p.effective) ? readdirSync(p.effective) : []) {+ const from = join(p.effective, name), to = join(p.own, name);+ if (name === GUARD_HOOK || name.endsWith('.sample') || !statSync(from).isFile()) continue;+ const body = readFileSync(from, 'utf8');+ if (!GBRAIN_HOOK.test(body) || (existsSync(to) && readFileSync(to, 'utf8') === body)) continue;+ writeFileSync(to, body);+ chmodSync(to, 0o755);+ }if (!before.worktree_config) enableWorktreeConfig(p.root, p.common);gitMust(p.root, ['config', '--worktree', 'core.hooksPath', p.own]);changed = true;diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex baf3b290ba..c8944026ec 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -27,7 +27,7 @@ import { anySignal } from './abort-check.ts';import type { GBrainConfig } from './config.ts';import { discoverOAuth, mintClientCredentialsToken } from './remote-mcp-probe.ts';import { clearTokenCacheFile, dropCachedToken, readCachedToken, tokenCacheKey, writeCachedToken, type CachedToken } from './remote-token-cache.ts';-import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt } from './persistence/types.ts';+import { isTerminalWriteState, isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt, type WriteReceipt } from './persistence/types.ts';import { GBRAIN_CLIENT_HEADER, GBRAIN_THIN_CLIENT_NAME } from '../mcp/result-rows.ts';import { VERSION } from '../version.ts';import { RemoteMcpError, extractResponseMeta, type RemoteMcpErrorDetail } from './remote-mcp-error.ts';@@ -207,6 +207,16 @@ export function extractToolErrorDetail(message: string): RemoteMcpErrorDetail {return detail;}+/** PR B: a server answers a write deferred behind a refresh as a `status: "pending"` success; the CLI treats it as the pending write it is. */+function deferredPendingReceipt(res: unknown): WriteReceipt | null {+ const first = (res as { content?: Array<{ text?: unknown }> } | null)?.content?.[0]?.text;+ if (typeof first !== 'string' || !/^\s*\{\s*"status"\s*:\s*"pending"/.test(first.slice(0, 64))) return null;+ try {+ const body = JSON.parse(first) as { receipt?: unknown };+ return isWriteReceipt(body.receipt) && !isTerminalWriteState(body.receipt.state) ? publicWriteReceipt(body.receipt) : null;+ } catch { return null; }+}+function requireRemoteMcp(config: GBrainConfig | null): NonNullable<GBrainConfig['remote_mcp']> {if (!config?.remote_mcp) {throw new RemoteMcpError(@@ -445,6 +455,11 @@ export async function callRemoteTool({ mcp_url: remote.mcp_url, ...extractToolErrorDetail(message) },);}+ const pending = deferredPendingReceipt(res);+ if (pending) {+ throw new RemoteMcpError('tool_error', `Remote tool ${toolName}: request ${pending.request_id} was accepted and publishes after the worktree refresh.`,+ { mcp_url: remote.mcp_url, code: 'write_pending', write_error: 'write_pending', write_request: pending, request_id: pending.request_id });+ }return res;} finally {try { await client.close(); } catch { /* best-effort */ }diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex c337f8fe72..96095ef432 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -3,7 +3,7 @@ import { withoutCallerAccess } from '../search/private-visibility.ts';import { withEngineScope } from '../engine-scope.ts';import type { GBrainConfig } from '../config.ts';import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage, yieldToEventLoop } from './journal.ts';-import { expireDeferredWrites } from './refresh-barrier.ts';+import { expireDeferredWrites, overdueDeferredWorkSql } from './refresh-barrier.ts';import { connectionCapFailure, finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';import { hostIdFor } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';@@ -445,6 +445,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {OR EXISTS (SELECT 1 FROM persistence_topology_changes cJOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuidWHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))+ OR ${overdueDeferredWorkSql('$1')}) AS work`, params, signal));// A window holding work stays put, so the tick it wakes reads the same rows.advanceProjectionCursor(cursor, row?.projection_work ? null : row?.projection_last, row?.high_water);diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex 71dc4326f2..66eb5c2563 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -83,7 +83,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);const result = await dispatchToolCall(engine, request.operation, params, {// #6696 (A5): a verified local registration is the user's CLI or agent, as on the in-process entry points.- admissionOrigin: 'interactive',+ admissionOrigin: 'interactive', pendingAsError: true,config, remote: verified.remote, transport: verified.remote || localSkillAdministration || localCliLocalOnly ? 'stdio' : undefined, sourceId, auth,...(writeWaitMs !== undefined ? { writeWaitMs } : {}),...(unrestricted ? {} : { localFederatedSourceIds: verified.grant.sourceIds }),diff --git a/src/core/persistence/refresh-barrier.ts b/src/core/persistence/refresh-barrier.tsindex 548d27bbec..0a78569c08 100644--- a/src/core/persistence/refresh-barrier.ts+++ b/src/core/persistence/refresh-barrier.ts@@ -73,6 +73,13 @@ export async function deferredReplayRefusal(engine: SqlEngine, row: WriteRequestexport const REFRESH_BARRIER_MAX_WAIT_KEY = 'persistence.refresh_barrier_max_wait_ms';export const REFRESH_BARRIER_MAX_WAIT_MS = 15 * 60_000;+/** The wait limit in ms: the configured value when it is a positive integer, else the default. */+const MAX_WAIT_SQL = `COALESCE((SELECT CASE WHEN value ~ '^[1-9][0-9]{0,14}$' THEN value::double precision END FROM config WHERE key='${REFRESH_BARRIER_MAX_WAIT_KEY}'), ${REFRESH_BARRIER_MAX_WAIT_MS})`;+const overdueDeferredFrom = (host: string, maxWait: string) => `JOIN persistence_worktrees w ON w.id=r.worktree_id+ JOIN persistence_worktree_refreshes f ON f.id=r.deferred_refresh_id+ WHERE w.owner_host_id=${host}::uuid AND r.state='deferred' AND f.released_at IS NULL AND r.created_at<now()-(${maxWait}*interval '1 millisecond')`;+/** The owner's idle probe counts an overdue deferred write as work, so its expiry runs even when nothing else is queued. */+export const overdueDeferredWorkSql = (host: string) => `EXISTS (SELECT 1 FROM persistence_requests r ${overdueDeferredFrom(host, MAX_WAIT_SQL)})`;/*** The owner's housekeeping: a deferred write whose refresh is still unreleased past the wait limit ends failed with@@ -82,13 +89,10 @@ export const REFRESH_BARRIER_MAX_WAIT_MS = 15 * 60_000;* the release that would make the row claimable never both win.*/export async function expireDeferredWrites(engine: BrainEngine, hostId: string, signal?: AbortSignal): Promise<WriteRequest[]> {- const [config] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [REFRESH_BARRIER_MAX_WAIT_KEY], { signal });- const configured = Number(config?.value);- const maxWaitMs = Number.isSafeInteger(configured) && configured > 0 ? configured : REFRESH_BARRIER_MAX_WAIT_MS;- const expired = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r- JOIN persistence_worktrees w ON w.id=r.worktree_id JOIN persistence_worktree_refreshes f ON f.id=r.deferred_refresh_id- WHERE w.owner_host_id=$1::uuid AND r.state='deferred' AND f.released_at IS NULL- AND r.created_at<now()-($2::double precision*interval '1 millisecond') ORDER BY r.sequence LIMIT 100`, [hostId, maxWaitMs], { signal });+ const [config] = await engine.executeRaw<{ ms: number }>(`SELECT ${MAX_WAIT_SQL} AS ms`, undefined, { signal });+ const maxWaitMs = Number(config?.ms ?? REFRESH_BARRIER_MAX_WAIT_MS);+ const expired = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r ${overdueDeferredFrom('$1', '$2::double precision')}+ ORDER BY r.sequence LIMIT 100`, [hostId, maxWaitMs], { signal });const finished: WriteRequest[] = [];for (const row of expired) {const done = await engine.transaction(async tx => {diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 814b03c419..4b5a790a3e 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -316,6 +316,8 @@ export interface DispatchOpts {isListed?: (op: OperationMeta) => Promise<boolean>;/** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */writeWaitMs?: number;+ /** PR B: the owner socket answers a write deferred behind a refresh as the write_pending error, so its CLI exits 10 and polls. */+ pendingAsError?: boolean;/** Large pages: the caller sent X-Gbrain-Client (OperationContext.thinClient). Shape only, never authority. */thinClient?: boolean;/** C1: search/query row shape chosen by the transport (OperationContext.resultRows); unset = lean for remote callers. */@@ -563,11 +565,12 @@ function deferredPendingReceipt(parsed: unknown): WriteReceipt | null {* PR B (docs/designs/REFRESH_WRITE_BARRIER.md): a write deferred behind a worktree refresh was accepted and publishes after* it, so MCP answers it as a pending success instead of an error. Any other `write_pending` stays an error.*/-export function deferredWriteResult(e: unknown): Record<string, unknown> | null {- if (!(e instanceof OperationError) || (e.code !== 'write_pending' && e.writeError !== 'write_pending') || !e.writeRequest?.deferred) return null;+export function deferredWriteResult(e: unknown, notices: Notice[], opts: DispatchOpts): ToolResult | null {+ if (opts.pendingAsError || !(e instanceof OperationError) || (e.code !== 'write_pending' && e.writeError !== 'write_pending') || !e.writeRequest?.deferred) return null;const receipt = publicWriteReceipt(e.writeRequest);- return { status: 'pending', request_id: receipt.request_id, receipt, deferred: e.writeRequest.deferred,- next: { tool: 'get_write_request', arguments: { request_id: receipt.request_id }, cli: `gbrain write-request ${receipt.request_id}`, retry_after_ms: receipt.retry_after_ms } };+ return toolResultWithNotices({ status: 'pending', request_id: receipt.request_id, receipt, deferred: e.writeRequest.deferred,+ next: { tool: 'get_write_request', arguments: { request_id: receipt.request_id }, cli: `gbrain write-request ${receipt.request_id}`, retry_after_ms: receipt.retry_after_ms } },+ admitNotices(notices, opts), dispatchRenderContext(opts));}/**@@ -1358,7 +1361,6 @@ async function dispatchResolvedCall(// never tells a mutating op with an unknown outcome to retry.notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));notices.push(...await grantBlockedNotices(engine, opts, refusedByGrant(e)));- const deferred = deferredWriteResult(e); if (deferred) return toolResultWithNotices(deferred, admitNotices(notices, opts), dispatchRenderContext(opts));- return errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });+ return deferredWriteResult(e, notices, opts) ?? errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/test/mcp-client.test.ts b/test/mcp-client.test.tsindex 9fd8ff6902..8ada8823fe 100644--- a/test/mcp-client.test.ts+++ b/test/mcp-client.test.ts@@ -26,6 +26,8 @@ import type { GBrainConfig } from '../src/core/config.ts';import { discoverOAuth, mintClientCredentialsToken } from '../src/core/remote-mcp-probe.ts';import { withEnv } from './helpers/with-env.ts';import { VERSION } from '../src/version.ts';+import { pendingReceiptOf, writeErrorExitCode } from '../src/core/persistence/write-wait.ts';+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';import { Client } from '@modelcontextprotocol/sdk/client/index.js';let server: ReturnType<typeof Bun.serve>;@@ -509,6 +511,18 @@ describe('callRemoteTool — error surfaces', () => {expect(toolExecutions).toBe(1);expect(tokenMintCount).toBe(1);});++ test('a write deferred behind a refresh, answered as a pending success, reaches the CLI as a pending write (exit 10)', async () => {+ const receipt = { request_id: 'd7599b95-65c2-4d54-aa4e-cb5745af90cf', state: 'queued', retry_after_ms: 1000 };+ mcpResponseFor = () => ({ content: [{ type: 'text', text: JSON.stringify({ status: 'pending', request_id: receipt.request_id, receipt,+ deferred: { refresh_id: 'c0ffee00-0000-4000-8000-000000000000' }, next: { tool: 'get_write_request', arguments: { request_id: receipt.request_id } } }) }] });+ const error = await callRemoteTool(makeConfig(), 'put_page', { slug: 'notes/x', content: 'x', request_id: receipt.request_id }).then(() => null, e => e);+ expect(error).toBeInstanceOf(RemoteMcpError);+ expect(error).toMatchObject({ reason: 'tool_error', detail: { write_error: 'write_pending', write_request: receipt } });+ expect(pendingReceiptOf(error)?.request_id).toBe(receipt.request_id);+ expect(writeErrorExitCode(error, false)).toBe(PENDING_WRITE_EXIT_CODE);+ expect(toolExecutions).toBe(1);+ });});describe('unpackToolResult', () => {diff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.tsindex 94ae0fec76..5157869454 100644--- a/test/refresh-write-barrier.test.ts+++ b/test/refresh-write-barrier.test.ts@@ -12,7 +12,7 @@*/import { afterAll, afterEach, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { rmSync, writeFileSync } from 'node:fs';+import { readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { run as runUpgradeCommand } from '../src/cli/commands/upgrade.ts';import { mintLegacyToken } from '../src/core/token-mint.ts';@@ -20,7 +20,12 @@ import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-fimport type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';-import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import { disposePersistenceConsumer, preparePersistedMutation, waitForWrite } from '../src/core/persistence/service.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { settleTopologyRequests, topologyPrincipal } from '../src/core/persistence/topology-locks.ts';+import { pendingReceiptOf, writeErrorExitCode } from '../src/core/persistence/write-wait.ts';+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';+import { OperationError } from '../src/core/ops/contract.ts';import { refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';import { getWriteRequestById } from '../src/core/persistence/journal.ts';import { resetWriteSwitches } from '../src/core/persistence/switches.ts';@@ -31,7 +36,7 @@ import { quarantineSharedSkillRestore } from '../src/core/shared-skills/restore.import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';-import { page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';+import { git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';const backends = testBackends();const engines: BrainEngine[] = [];@@ -399,3 +404,94 @@ test('with the barrier off a write during a refresh is still refused worktree_reexpect((await refresh).status).toBe('completed');});}), 180_000);++test('the owner socket answers a deferred write as write_pending, so its CLI exits 10 and polls', () => each(async f => {+ const refresh = await duringRefresh(f, async () => {+ const result = await dispatchToolCall(f.engine, 'put_page', { slug: 'notes/socket', content: page('Socket', 'deferred over the owner socket') },+ { remote: false, sourceId: f.alpha, admissionOrigin: 'interactive', pendingAsError: true });+ expect(result.isError).toBe(true);+ const body = JSON.parse(result.content[0]!.text) as Record<string, any>;+ const error = Object.assign(new OperationError(body.error, body.message), { writeRequest: body.write_request, writeError: body.write_error });+ expect(pendingReceiptOf(error)?.request_id).toBe(body.write_request.request_id);+ expect(writeErrorExitCode(error, false)).toBe(PENDING_WRITE_EXIT_CODE);+ expect((await requestRow(f, body.write_request.request_id)).state).toBe('deferred');+ });+ expect((await refresh).status).toBe('completed');+}), 180_000);++test('an overdue deferred write expires on an idle owner tick when nothing else is queued', () => each(async f => {+ const refresh = await duringRefresh(f, async () => {+ const out = await call(f, 'put_page', { slug: 'notes/idle-expiry', content: page('Idle', 'body') });+ const deferred = await requestRow(f, out.body.request_id);+ const consumer = new PersistenceConsumer(f.engine, { engine: f.engine.kind } as never, preparePersistedMutation);+ await consumer.tick();+ expect((await getWriteRequestById(f.engine, deferred.id))!.state).toBe('deferred');+ await f.engine.executeRaw("INSERT INTO config(key,value) VALUES('persistence.refresh_barrier_max_wait_ms','1') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value");+ try {+ await new Promise(resolve => setTimeout(resolve, 20));+ await consumer.tick();+ expect(await getWriteRequestById(f.engine, deferred.id)).toMatchObject({ state: 'failed', error_code: 'refresh_barrier_expired' });+ } finally {+ await f.engine.executeRaw("DELETE FROM config WHERE key='persistence.refresh_barrier_max_wait_ms'");+ await consumer.stop();+ }+ });+ expect((await refresh).status).toBe('completed');+}), 180_000);++test('a deferred edit_page of a page the refresh changed ends revision_conflict and leaves the refreshed file', () => each(async f => {+ f.push('alpha/people/alice-example.md', PERSON);+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');+ const upstream = PERSON.replace('Alice is a person.', 'Alice is a person who moved.');+ const read = await call(f, 'get_page', { slug: 'people/alice-example', include_content: true });+ expect(typeof read.body.revision).toBe('string');+ let deferred!: WriteRequest;+ const refresh = await duringRefresh(f, async () => {+ const out = await call(f, 'edit_page', { slug: 'people/alice-example', expected_revision: read.body.revision,+ edits: [{ old_text: 'Alice is a person.', new_text: 'Alice is a person who stayed.' }] });+ expect(out.isError).toBe(false);+ expect(out.body.status).toBe('pending');+ deferred = await requestRow(f, out.body.request_id);+ expect(deferred.state).toBe('deferred');+ }, ['alpha/people/alice-example.md', upstream]);+ expect((await refresh).status).toBe('completed');+ expect(await settle(f, deferred)).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });+ expect(readFileSync(join(f.root, 'alpha/people/alice-example.md'), 'utf8')).toBe(upstream);+}), 180_000);++test('a deferred forget on a page the refresh changed ends revision_conflict and the fact stays active', () => each(async f => {+ f.push('alpha/people/alice-example.md', PERSON);+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');+ const remembered = await call(f, 'remember', { fact: 'alice-example likes coffee', entity: 'people/alice-example', provenance: 'test' });+ expect(remembered.isError).toBe(false);+ const [fact] = await f.engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact LIKE '%likes coffee%' AND expired_at IS NULL");+ expect(fact).toBeDefined();+ git(f.root, 'add', '-A'); git(f.root, 'commit', '-q', '-m', 'the remembered fact'); git(f.root, 'push', '-q', 'origin', 'main');+ git(f.upstream, 'pull', '-q', '--ff-only', 'origin', 'main');+ let deferred!: WriteRequest;+ const refresh = await duringRefresh(f, async () => {+ const out = await call(f, 'forget', { id: String(fact!.id) });+ expect(out.isError).toBe(false);+ expect(out.body.status).toBe('pending');+ deferred = await requestRow(f, out.body.request_id);+ expect(deferred.state).toBe('deferred');+ }, ['alpha/people/alice-example.md', readFileSync(join(f.root, 'alpha/people/alice-example.md'), 'utf8').replace('Alice is a person.', 'Alice is a person who moved.')]);+ expect((await refresh).status).toBe('completed');+ expect(await settle(f, deferred)).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });+ const [{ n }] = await f.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE id=$1 AND expired_at IS NULL', [fact!.id]);+ expect(Number(n)).toBe(1);+}), 180_000);++test('a source lifecycle change while a deferred write waits ends it source_changed and releases its counters', () => each(async f => {+ const refresh = await duringRefresh(f, async () => {+ const before = await outstanding(f);+ const out = await call(f, 'put_page', { slug: 'notes/topology', content: page('Topology', 'body') });+ const deferred = await requestRow(f, out.body.request_id);+ expect(await outstanding(f)).toBe(before + 1);+ const principal = await topologyPrincipal(f.engine);+ expect(await f.engine.transaction(tx => settleTopologyRequests(tx, [f.alpha], [f.worktreeId], principal))).toBe(1);+ expect(await getWriteRequestById(f.engine, deferred.id)).toMatchObject({ state: 'conflict', error_code: 'source_changed' });+ expect(await outstanding(f)).toBe(before);+ });+ expect((await refresh).status).toBe('completed');+}), 180_000);diff --git a/test/sources-guard.test.ts b/test/sources-guard.test.tsindex b99f6621ac..c47e8a43b1 100644--- a/test/sources-guard.test.ts+++ b/test/sources-guard.test.ts@@ -5,13 +5,14 @@*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { createHash } from 'node:crypto';-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { parseSourcesGuardArgs, sourcesGuard } from '../src/commands/sources-guard.ts';-import { renderGuardHook } from '../src/core/git/commit-guard.ts';+import { installOwnerGuard, renderGuardHook, uninstallOwnerGuard } from '../src/core/git/commit-guard.ts';+import { gitDurabilityPolicy } from '../src/core/persistence/git-durability-policy.ts';import { commitThroughDoor } from '../src/core/persistence/git-door.ts';import { commitGitTargets } from '../src/core/persistence/effect-git.ts';import { refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';@@ -47,6 +48,23 @@ test('the opt-in hook is byte-identical; both owner-path modes guard only the owexpect(enforce).not.toContain('CHERRY_PICK_HEAD');});+test('installing the owner guard keeps the brain-durability post-commit hook, so an unrecorded binding stays durable', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-guard-durable-'));+ try {+ git(repo, 'init', '-q', '-b', 'main');+ const hooks = join(repo, '.git', 'hooks');+ mkdirSync(hooks, { recursive: true });+ writeFileSync(join(hooks, 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n', { mode: 0o755 });+ expect(await gitDurabilityPolicy({ git_durability: null }, repo)).toEqual({ durable: true, source: 'legacy_hook' });+ for (const mode of ['default', 'enforce'] as const) {+ expect(installOwnerGuard(repo, mode).installed).toBe(true);+ expect(await gitDurabilityPolicy({ git_durability: null }, repo)).toEqual({ durable: true, source: 'legacy_hook' });+ }+ uninstallOwnerGuard(repo);+ expect(await gitDurabilityPolicy({ git_durability: null }, repo)).toEqual({ durable: true, source: 'legacy_hook' });+ } finally { rmSync(repo, { recursive: true, force: true }); }+});+test('arguments: one source, one action, --mode only with --install', () => {expect(parseSourcesGuardArgs(['notes', '--install', '--mode', 'enforce'])).toEqual({ sourceId: 'notes', action: 'install', mode: 'enforce' });expect(parseSourcesGuardArgs(['notes'])).toEqual({ sourceId: 'notes', action: 'status', mode: 'default' });