Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): writer activate warns per source whose Git effects it would leave skipped (#5182)

garrytan9ccbeeed0722
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 23611d5570..81e4eb84e4 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -672,6 +672,25 @@ its writer stopped. A failed activation leaves managed mode disabled. Status
reports `enabled: false` until activation commits. Run an ordinary write and
read its receipt and revision before resuming writers on the upgraded hosts.
+### Git durability at activation
+
+Activation does not turn on Git durability. A filesystem source whose owner
+will not commit or push page writes (durability off, or not recorded with no
+harden post-commit hook) gets one `git_durability_not_enabled` entry in the
+report's `warnings[]` (on stderr as well without `--json`), in the dry run and
+in the real run. Activation still proceeds; the source's Git effects complete
+as skipped (`durability_not_enabled`) until it is enabled. `sources harden` is
+refused once the brain is managed, so enable it with the recorded setting:
+
+```bash
+gbrain sources writer git-durability <source> --enable --dry-run --json
+gbrain sources writer git-durability <source> --enable \
+ --admin-intent writer_git_durability --expected-state <reviewed-admin-state> --json
+```
+
+The preview lists the skipped Git effects; enabling re-queues them, one per
+file, so the pages written while durability was off get committed and pushed.
+
CLI and stdio registrations are durable, separate principals. The CLI lane is
trusted local administration; stdio remains an untrusted memory caller.
Revocation survives restart. Losing a credential file or receiving a denied
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6faeed5c53..d9dff05118 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1278,6 +1278,16 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-page
|---|---|---|---|---|---|---|
| The canonical checkout is on a detached HEAD, so a push would target the wrong ref. | Only the operator of the brain host can change what blocks this. | Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun. | host_admin | `gbrain doctor --json` | 1 | no |
+### git_durability_not_enabled
+
+<a id="git_durability_not_enabled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A filesystem source's owner will not commit or push its page writes (Git durability is off, or not recorded and no harden post-commit hook is installed), so its Git effects complete as skipped; writer activate still proceeds and lists it under warnings. | Activation applies the effect runner's own policy: the binding's recorded setting decides, and only when nothing is recorded does the legacy hook decide (a failed probe counts as not durable). sources harden is refused once the brain is managed, so the recorded setting is the way to turn durability on. | Preview gbrain sources writer git-durability <source> --enable --dry-run on the owner host, then apply it with --admin-intent writer_git_durability; enabling re-queues the Git effects that were skipped while it was off. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/concurrent-writes.md#git-durability-at-activation](../../docs/guides/concurrent-writes.md#git-durability-at-activation)
+
### git_index_locked
<a id="git_index_locked"></a>
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 1769f32ee1..359455cd77 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -249,6 +249,10 @@ export async function runPersistenceAdminCli(group: Group, args: string[], conne
await writeStdoutFinal(renderWriterFailures(result as Parameters<typeof renderWriterFailures>[0], parsed.json));
return;
}
+ // #5182: activation proceeds, but a source whose Git effects it leaves skipped is named for a person on stderr too.
+ if (parsed.operation === 'writer_activate' && !parsed.json) {
+ for (const warning of (result as { warnings?: Array<{ message: string }> }).warnings ?? []) process.stderr.write(`warning: ${warning.message}\n`);
+ }
await writeStdoutFinal(JSON.stringify(result, bigintToStringReplacer, 2) + '\n');
// #6678: a credential repair that refused some parked pushes on their own is partial and exits 1.
if (parsed.operation === 'writer_git_durability' && (result as { status?: unknown }).status === 'partial') setCliExitVerdict(1);
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 113315261d..947be08530 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -219,6 +219,11 @@ export const CODES = {
ghost_mass_delete_refused: { class: 'consent', summary: "gbrain repair ghost-pages refused to soft-delete more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to ghost pages: that many missing canonical files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted.", docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Check the source checkout on its owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is removed.", requires_exclusive: false } },
ghost_storage_unknown: { class: 'unavailable', summary: "Ghost pages of a source cannot be classified because its canonical checkout cannot be read reliably; nothing was listed or changed.", why: "A page is never reported or removed as a ghost while its file may only be unreadable: a missing or non-directory root (storage_unavailable), or a stat error, an invalid gbrain.yml or an inconclusive page check (ambiguous_storage), fails closed.", reasons: ['storage_unavailable', 'ambiguous_storage'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair ghost-pages --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },
git_branch_unborn: { class: 'host_only', summary: "The canonical checkout's branch has no commit yet, so Git durability has nothing to build on.", why: "A Git effect commits on top of HEAD and pushes the branch; on an unborn branch (a fresh `init --git` root) there is no HEAD to commit on and no ref to push, so enabling durability would park every effect. The database is unaffected.", suggestion: 'Make the first commit on the branch on the brain host (git add -A && git commit -m "Initial brain"), then rerun gbrain sources writer git-durability <source> --enable.' },
+ // wave 18b (GBRA-106) #5182: activation warns per source whose Git effects it would leave skipped.
+ git_durability_not_enabled: { class: 'host_only', summary: "A filesystem source's owner will not commit or push its page writes (Git durability is off, or not recorded and no harden post-commit hook is installed), so its Git effects complete as skipped; writer activate still proceeds and lists it under warnings.",
+ why: "Activation applies the effect runner's own policy: the binding's recorded setting decides, and only when nothing is recorded does the legacy hook decide (a failed probe counts as not durable). sources harden is refused once the brain is managed, so the recorded setting is the way to turn durability on.",
+ docs: 'docs/guides/concurrent-writes.md#git-durability-at-activation',
+ suggestion: 'Preview gbrain sources writer git-durability <source> --enable --dry-run on the owner host, then apply it with --admin-intent writer_git_durability; enabling re-queues the Git effects that were skipped while it was off.' },
git_checkout_required: { class: 'host_only', summary: "The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to.", suggestion: 'Initialize the root as a Git repository with a first commit and a remote on the brain host, then rerun; a database-only source needs no Git durability.' },
git_detached_head: { class: 'host_only', summary: "The canonical checkout is on a detached HEAD, so a push would target the wrong ref.", suggestion: 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.' },
git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index 7cfa10109b..5dc2d01234 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -15,7 +15,7 @@ import { inspectLegacyWriterLocks } from './legacy-locks.ts';
import { deleteLockRowExact } from '../db-lock.ts';
import { catalogueError } from '../error-catalogue.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
-import { gitDurabilityState } from './git-durability-policy.ts';
+import { gitDurabilityPolicy, gitDurabilityState } from './git-durability-policy.ts';
import { writeThroughConfigured } from './switches.ts';
import { DATABASE_ONLY_SOURCES_KEY, unboundBindCommand } from './unbound-source.ts';
@@ -33,6 +33,13 @@ export interface ActivationReport {
* until `gbrain sources writer git-durability <source> --enable` runs.
*/
git_durability?: Array<{ source_id: string; state: 'on' | 'off' | 'unknown'; enable_command: string | null }>;
+ /**
+ * #5182: one `git_durability_not_enabled` warning per filesystem source whose
+ * owner will not commit or push page writes (durability off, or not recorded
+ * and no legacy hook): their Git effects complete as skipped until the source
+ * is enabled, which re-queues them. Activation still proceeds.
+ */
+ warnings?: ActivationWarning[];
/**
* #6449: rooted, non-connector sources with no canonical owner on a brain whose `sync.write_through` is off. They are
* database-only (page writes publish to the database with `databaseOnlyReason: disabled_by_config`, `writer status`
@@ -55,6 +62,45 @@ const gitDurabilityListing = (bindings: WorktreeBinding[]): NonNullable<Activati
const state = gitDurabilityState(binding);
return { source_id: binding.source_id, state, enable_command: state === 'on' ? null : `gbrain sources writer git-durability ${binding.source_id} --enable --dry-run` };
});
+export interface ActivationWarning {
+ code: 'git_durability_not_enabled';
+ source_id: string;
+ state: 'off' | 'unknown';
+ message: string;
+ enable_command: string;
+ /** The legacy hook probe failed, so durability could not be verified (fail-closed: not durable). */
+ probe_error?: string;
+ fix: Action;
+}
+/** #5182: the sources whose Git effects activation would leave skipped, by the same policy the effect runner applies. */
+async function gitDurabilityWarnings(bindings: WorktreeBinding[]): Promise<{ warnings?: ActivationWarning[] }> {
+ const warnings: ActivationWarning[] = [];
+ for (const binding of bindings) {
+ const state = gitDurabilityState(binding);
+ if (state === 'on' || !binding.local_path) continue;
+ let probeError: string | undefined;
+ if (state === 'unknown') {
+ const policy = await gitDurabilityPolicy(binding, binding.local_path).catch((error: unknown) => {
+ probeError = error instanceof Error ? error.message : String(error);
+ return null;
+ });
+ if (policy?.durable) continue;
+ }
+ const id = binding.source_id;
+ const enableCommand = `gbrain sources writer git-durability ${id} --enable --dry-run`;
+ const why = state === 'off' ? 'Git durability is disabled on its binding'
+ : probeError ? `Git durability is not recorded and the post-commit hook probe failed (${probeError})`
+ : 'Git durability is not recorded and no harden post-commit hook is installed';
+ warnings.push({ code: 'git_durability_not_enabled', source_id: id, state, enable_command: enableCommand,
+ ...(probeError ? { probe_error: probeError } : {}),
+ message: `Source ${id}: ${why}, so the owner will not commit or push its page writes; their Git effects complete as skipped (durability_not_enabled). `
+ + `Preview with ${enableCommand}, then apply it without --dry-run (admin-intent writer_git_durability); enabling re-queues the Git effects skipped while it was off.`,
+ fix: { ...readFix('Previews enabling Git durability for this source, the checkout checks and the skipped Git effects it would re-queue; changes nothing.',
+ { argv: ['gbrain', 'sources', 'writer', 'git-durability', id, '--enable', '--dry-run', '--json'] }),
+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', id, '--json'] } } });
+ }
+ return warnings.length ? { warnings } : {};
+}
interface SourceRoot { id: string; incarnation: string; root: string | null; connector: boolean; }
const quiescence = () => new OperationError('writer_not_quiesced', 'Managed activation requires all older writers and maintenance jobs to be stopped.',
WRITER_INSPECTION_HINT);
@@ -199,7 +245,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
if (legacyLocks.some(row => !opts.cleanupDeadLocalLocks || row.liveness !== 'dead_eligible')) throw quiescence();
if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length
|| (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw await notQuiescedError(tx, quiescence().message, { queuedEffects: false });
- if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit, git_durability: gitDurabilityListing(bindings), ...databaseOnlyListing };
+ if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit, git_durability: gitDurabilityListing(bindings), ...await gitDurabilityWarnings(bindings), ...databaseOnlyListing };
for (const row of legacyLocks) {
if (!(await deleteLockRowExact(tx, row.id, row.holder_pid, row.acquisition_token)).deleted) throw quiescence();
}
@@ -212,7 +258,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
// Any fsync/marker failure rolls back enabled=true. A conservative stale
// refusal record after rollback is safe and cannot grant writer authority.
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
- return { enabled: true, activated: true, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, git_durability: gitDurabilityListing(bindings), ...databaseOnlyListing };
+ return { enabled: true, activated: true, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, git_durability: gitDurabilityListing(bindings), ...await gitDurabilityWarnings(bindings), ...databaseOnlyListing };
});
} finally { for (const lock of locks.reverse()) await lock.release(); }
}
diff --git a/test/writer-activate-durability-warnings-5182.test.ts b/test/writer-activate-durability-warnings-5182.test.ts
new file mode 100644
index 0000000000..a92efbd55f
--- /dev/null
+++ b/test/writer-activate-durability-warnings-5182.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #5182 — `writer activate` names every filesystem source whose Git effects it
+ * would leave skipped.
+ *
+ * Protects: the activation report (dry run and real run) carries one
+ * `git_durability_not_enabled` warning per source whose owner will not commit
+ * or push page writes, decided by the effect runner's own policy (a recorded
+ * setting wins; with nothing recorded the legacy harden hook decides), with a
+ * read-only `git-durability --enable --dry-run` fix that says enabling
+ * re-queues the skipped effects; a person sees the same warnings on stderr.
+ * Activation still proceeds.
+ * Fails when: activation goes back to a silent `git_durability` listing only
+ * (no warnings), warns on a source whose hook makes it durable, or refuses.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, 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 { activatePersistence } from '../src/core/persistence/activation.ts';
+import { claimWorktree, managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runPersistenceAdminCli } from '../src/commands/persistence-admin.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { gitAsync } from './helpers/git-publication.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+}, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+
+/** Four claimed git roots: no hook, a legacy harden hook, recorded disabled, recorded enabled. */
+async function fixture(run: (ids: { bare: string; hooked: string; off: string; on: string }) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-activate-5182-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await disposePersistenceConsumer(engine); await resetPgliteState(engine); await engine.setConfig('version', schemaVersion);
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', embedding_disabled: true }));
+ const tag = randomUUID().slice(0, 8);
+ const ids = { bare: `bare-${tag}`, hooked: `hooked-${tag}`, off: `off-${tag}`, on: `on-${tag}` };
+ for (const [kind, id] of Object.entries(ids)) {
+ const root = join(home, kind); mkdirSync(root);
+ await gitAsync(root, 'init', '-q', '-b', 'main');
+ if (kind === 'hooked') {
+ const hook = join(root, '.git', 'hooks', 'post-commit');
+ writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(hook, 0o755);
+ }
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ const binding = await claimWorktree(engine, id, root, localHostId());
+ if (kind === 'off' || kind === 'on') {
+ await engine.executeRaw('UPDATE persistence_host_bindings SET git_durability=$1 WHERE worktree_id=$2::uuid',
+ [kind === 'on' ? 'enabled' : 'disabled', binding.worktree_id]);
+ }
+ }
+ try { await run(ids); } finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+function expectWarnings(report: Awaited<ReturnType<typeof activatePersistence>>, ids: { bare: string; off: string }): void {
+ const warnings = report.warnings ?? [];
+ expect(warnings.map(w => [w.source_id, w.state]).sort()).toEqual([[ids.bare, 'unknown'], [ids.off, 'off']].sort());
+ for (const warning of warnings) {
+ expect(warning.code).toBe('git_durability_not_enabled');
+ expect(warning.enable_command).toBe(`gbrain sources writer git-durability ${warning.source_id} --enable --dry-run`);
+ expect(warning.message).toContain('re-queues the Git effects skipped');
+ expect(warning.fix.argv).toEqual(['gbrain', 'sources', 'writer', 'git-durability', warning.source_id, '--enable', '--dry-run', '--json']);
+ expect(warning.fix.consent).toEqual([]);
+ expect(warning.fix.verify?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', warning.source_id, '--json']);
+ }
+}
+
+test('dry run and real activation warn for the sources whose Git effects would be skipped, and activation proceeds', () => fixture(async ids => {
+ const preview = await activatePersistence(engine, { confirmQuiesced: true, dryRun: true });
+ expect(preview).toMatchObject({ enabled: false, activated: false, filesystem_sources: 4 });
+ expectWarnings(preview, ids);
+ const applied = await activatePersistence(engine, { confirmQuiesced: true });
+ expect(applied).toMatchObject({ enabled: true, activated: true, filesystem_sources: 4 });
+ expectWarnings(applied, ids);
+ expect(await managedPersistenceEnabled(engine)).toBe(true);
+}), 120_000);
+
+test('a person sees each warning on stderr; --json keeps stderr clean', () => fixture(async ids => {
+ const capture = async (args: string[]) => {
+ let stderr = '';
+ const write = process.stderr.write, out = process.stdout.write;
+ process.stderr.write = ((chunk: unknown) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;
+ process.stdout.write = (() => true) as typeof process.stdout.write;
+ try { await runPersistenceAdminCli('writer', args, engine); } finally { process.stderr.write = write; process.stdout.write = out; }
+ return stderr;
+ };
+ const human = await capture(['activate', '--confirm-quiesced', '--dry-run']);
+ expect(human).toContain(`warning: Source ${ids.bare}: Git durability is not recorded and no harden post-commit hook is installed`);
+ expect(human).toContain(`warning: Source ${ids.off}: Git durability is disabled on its binding`);
+ expect(human).not.toContain(ids.hooked);
+ expect(human).not.toContain(ids.on);
+ expect(await capture(['activate', '--confirm-quiesced', '--dry-run', '--json'])).not.toContain('warning:');
+}), 120_000);