Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(durability): managed variant of the AGENTS durability block, regenerated by writer git-durability (#5808)

garrytan9ccaa6e55ad8
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 4a09ca44ff..5ab4795733 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -733,6 +733,27 @@ elsewhere), and never during a pending recovery or transfer
(`recovery_required`). The setting is not a backup: the owner still never pulls
or rebases the checkout.
+<a id="files-that-are-not-pages"></a>**Files that are not pages.** The owner's
+Git effect commits only the page paths it wrote (`git commit --only`) and then
+pushes HEAD. Everything else in the checkout (`MEMORY.md`, daily notes,
+`AGENTS.md`, scripts) is the operator's: `git add` and `git commit` it with
+plain git in the checkout. Those commits reach the remote on the owner's next
+push, because the owner pushes HEAD, or sooner with a hand `git push` from the
+checkout; `gbrain sources push` refuses on a managed root and its secret scan
+does not run on a hand push. A hand push and the owner's push race only by
+ordinary Git semantics (both push the same HEAD; a push the remote rejects is
+retried by the owner and, after repeated failures, parked, which
+`writer status --json` shows). Never
+`git pull --rebase`, `git reset` or `git checkout` page paths in the checkout:
+the owner never pulls, and moving files under it is what `source_changed`
+guards against; bring remote commits in with `gbrain sources refresh <source>`.
+The durability block `sources harden` writes into `AGENTS.md`/`RESOLVER.md`
+before activation says the opposite (run the push helper after every write,
+pull before writing), so `writer git-durability <source> --enable` and
+`--pat-file` rewrite that block in place to the managed variant (#5808); the
+preview reports it as `agents`, the rewrite touches nothing outside the
+markers, and the file is left for you to commit.
+
### Supported managed work and explicit repair
Once active, ordinary authorized local atom extraction, fact fences/backstop,
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index b65c92987b..d25afc6316 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -426,7 +426,12 @@ without writing anything"* — your agent runs `gbrain sync --dry-run`.
This hardening path applies to unmanaged worktrees. After activating managed
writers, Git effects belong to the persistence outbox; generated legacy push
helpers refuse to run rather than bypass that ownership boundary. See the
-[concurrent-write guide](concurrent-writes.md).
+[concurrent-write guide](concurrent-writes.md). On a managed root the owner
+commits and pushes page writes (`gbrain sources writer git-durability <source>
+--enable`), files that are not pages are committed with plain git and ride the
+owner's next push, the checkout is never pulled or rebased, and the durability
+block below is regenerated in its managed form by that verb; see
+[files that are not pages](../architecture/topologies.md#files-that-are-not-pages).
A long-lived agent that writes to a knowledge-wiki git repo needs three
things to never lose work: pull before it edits, push every write, and not
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index 887b6b770a..7b8665c4f9 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -21,6 +21,7 @@ import type { Check } from '../../doctor.ts';
import { parseSourceConfig } from '../../../core/sources-load.ts';
import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
import { isPhysicalRootMetadata } from '../../../core/persistence/root-metadata.ts';
+import { isManagedFilesystemPath } from '../../../core/persistence/filesystem-guard.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { doctorVerify } from '../check-fix.ts';
@@ -99,8 +100,12 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const lines = bad.map(r => `${r.root}${r.source_ids.length ? ` (${r.source_ids.join(', ')})` : ''}: `
+ [r.ahead ? `${r.ahead} commit(s) not on the upstream since ${r.oldest_unpushed_at}` : '', r.dirty && r.oldest_dirty_at ? `${r.dirty} uncommitted change(s), oldest from ${r.oldest_dirty_at}` : '']
.filter(Boolean).join('; '));
+ // #5808 (#5606 residue): a managed canonical worktree has no bulk push; its owner pushes page writes and the operator pushes the rest.
+ const remedy = bad.some(r => isManagedFilesystemPath(r.root))
+ ? 'Commit and push them: on a managed canonical worktree the persistence owner commits and pushes page writes (gbrain sources writer status <source> --json shows parked pushes; gbrain sources writer git-durability <source> --enable turns them on), and files that are not pages are committed and pushed with plain git in the checkout, never pulled or rebased; elsewhere gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout'
+ : 'Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout)';
return { name: 'git_convergence', status: bad.some(r => r.status === 'fail') ? 'fail' : 'warn', details,
- message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout); this compares with the last fetched upstream and does not fetch.` };
+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${remedy}; this compares with the last fetched upstream and does not fetch.` };
}
/**
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4aa2119c65..a4d8399576 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -444,6 +444,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.175.0', text: 'A managed checkout\'s persisted directory birth stamp now matches the live directory when the two are within 1 µs, instead of only when they are byte-identical (#6501: on APFS a freshly created root reports a birth time tens of nanoseconds apart between the process that stamped it and later processes, which left every write to that root refused `recovery_required`). The owner token, brain, worktree, root, inode and device still have to match exactly; a damaged or zero stamp still refuses; the in-process file target check, the staging identity and the transfer prepare/accept comparison stay exact. When the inode or birth time moved beyond that while everything else matches (a checkout restored or recreated at its recorded path), the refusal now carries detail `physical_root_directory_changed` and names the exit: `gbrain sources writer transfer prepare/accept <source> --self-transfer --confirm-relocated-root` (`writer status --json` prints it filled in). The tolerance covers the reported drift; it was not reproduced on APFS here, so #6501 stays open until a reporter confirms on this build.' },
// Fix wave 15 G2 (GBRA-79, #6449); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.
{ since: '0.60.175.0', text: '`gbrain sources writer activate` no longer refuses `writer_registration_required` for a source that has a checkout path but no canonical owner when the brain\'s `sync.write_through` is `false` (#6449): `writer status` already reported that source `database_only`, and activation now agrees, listing it under `database_only_sources` and leaving it unbound. Page writes to it stay database-only (`disabled_by_config`), and turning `sync.write_through` back on does not claim it automatically on a PGLite brain (activation records the listed sources in `persistence.database_only_sources`; deactivation clears it): the next write refuses `owner_unavailable` with `detail: unbound_source` and the `gbrain sources writer claim` to run (or publishes database-only under `persistence.unbound_write=database_only`), the same as on Postgres. With `sync.write_through` on, the activation refusal and the `owner_unavailable` that `gbrain sync` gives such a source now name the claim (preview with `--dry-run`) instead of a generic inspection hint.' },
+ // Fix wave 15 G2 (GBRA-79, #5808); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.
+ { since: '0.60.175.0', text: 'On a managed canonical worktree, `gbrain sources writer git-durability <source> --enable` (and `--pat-file`) now rewrites the durability block between the gbrain markers in `AGENTS.md`/`RESOLVER.md` to a managed variant (#5808). The block `sources harden` wrote before activation told agents to run the commit-and-push helper after every write and to pull --rebase before writing, both of which route around the persistence owner; the managed variant says page writes go through gbrain, files that are not pages are committed with plain git and ride the owner\'s next push, and the checkout is never pulled, rebased or reset. The rewrite is idempotent, changes nothing outside the markers and is not committed: the file is left for the operator to commit. The preview (`--dry-run`) lists it as `agents`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index 21ecfd69e8..2d1688de25 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -330,10 +330,43 @@ function renderTaxonomyLines(rules: FilingRulesDoc): string {
return lines.join('\n');
}
-function renderManagedBlock(repoPath: string): string {
+/**
+ * The classic rules tell agents to run the push helper after every write and
+ * to `git pull --rebase` before writing. On a managed canonical worktree
+ * (#5808) both route agents around the persistence owner, so the block has a
+ * managed variant: page writes through gbrain, non-page files with plain git,
+ * never pull or rebase the checkout. `gbrain sources writer git-durability
+ * <source> --enable` (and `--pat-file`) regenerates it there.
+ */
+function renderManagedBlock(repoPath: string, managed?: { sourceId: string }): string {
const rules = resolveFilingRules(repoPath);
+ const regeneratedBy = managed ? `gbrain sources writer git-durability ${managed.sourceId} --enable` : 'gbrain sources harden';
+ const writeRules = managed ? `2. **Page writes go through gbrain, never through git.** This checkout is the
+ managed canonical worktree of gbrain source \`${managed.sourceId}\`: the persistence
+ owner writes each page file, commits only the page paths it wrote and pushes
+ HEAD after every page write. Save pages with the gbrain tools (\`put_page\`,
+ \`edit_page\`, \`remember\`, \`capture\`); do not run the classic commit-and-push
+ helper, \`git add -A\` or \`git commit\` for pages. Confirm a write landed with
+ \`gbrain sources writer status ${managed.sourceId} --json\` (its receipts and parked
+ effects), and that links resolve with \`gbrain check-resolvable\`.
+
+3. **Never pull, rebase or reset this checkout.** The owner publishes from local
+ HEAD and never pulls, so a pull, rebase, reset or checkout of page paths moves
+ files under it. To bring in remote commits run
+ \`gbrain sources refresh ${managed.sourceId}\`. Files that are not pages (this file,
+ \`MEMORY.md\`, daily notes) are yours: \`git add\` and \`git commit\` them with plain
+ git; they reach the remote on the owner's next push, or push them by hand
+ with \`git push\` (never \`--force\`).` : `2. **Every write is committed AND pushed — push is never deferred.** After any
+ persistent write, run \`scripts/brain-commit-push.sh "<msg>" <path>\` (it commits,
+ pushes, and FAILS LOUDLY if the push doesn't land), then confirm links resolve
+ with \`gbrain check-resolvable\`. Do not move on until the push succeeded. The
+ post-commit hook is only a best-effort fallback — the helper is the guarantee.
+
+3. **Pull before you touch anything.** Run \`git fetch && git pull --rebase\` at
+ session start and again before each batch of writes, so a long-lived session
+ never edits a stale tree (a cron also pulls every ~30 min).`;
return `${AGENTS_BEGIN}
-<!-- gbrain durability rules. This block is regenerated by \`gbrain sources harden\`.
+<!-- gbrain durability rules. This block is regenerated by \`${regeneratedBy}\`.
Do not index as user knowledge; do not edit between the markers. -->
## Brain durability rules (always on)
@@ -343,23 +376,20 @@ ${renderTaxonomyLines(rules)}
Writing to /tmp, scratch dirs, or outside the repo is forbidden for anything
meant to persist.
-2. **Every write is committed AND pushed — push is never deferred.** After any
- persistent write, run \`scripts/brain-commit-push.sh "<msg>" <path>\` (it commits,
- pushes, and FAILS LOUDLY if the push doesn't land), then confirm links resolve
- with \`gbrain check-resolvable\`. Do not move on until the push succeeded. The
- post-commit hook is only a best-effort fallback — the helper is the guarantee.
-
-3. **Pull before you touch anything.** Run \`git fetch && git pull --rebase\` at
- session start and again before each batch of writes, so a long-lived session
- never edits a stale tree (a cron also pulls every ~30 min).
+${writeRules}
${AGENTS_END}`;
}
+/** #5808: the managed variant of the block, rewritten in place by the Git-durability admin verb; the operator commits it. */
+export function patchManagedDurabilityBlock(repoPath: string, sourceId: string, dryRun: boolean): { status: StepStatus; detail: string } {
+ return patchResolverFile(repoPath, dryRun, { sourceId });
+}
+
/** Patch the active resolver file with the managed block (idempotent). */
-function patchResolverFile(repoPath: string, dryRun: boolean): { status: StepStatus; detail: string } {
+function patchResolverFile(repoPath: string, dryRun: boolean, managed?: { sourceId: string }): { status: StepStatus; detail: string } {
const existing = findResolverFile(repoPath);
const target = existing ?? join(repoPath, RESOLVER_FILENAMES[1]); // default AGENTS.md
- const block = renderManagedBlock(repoPath);
+ const block = renderManagedBlock(repoPath, managed);
const name = relative(repoPath, target) || target;
let current = '';
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index 868d3a14ff..9281db63df 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -7,10 +7,13 @@
* It is a `PERSISTENCE_ADMIN_OPERATIONS` verb (never a public operation) with
* the same `--admin-intent`/`--expected-state` handshake as `writer_activate`:
* the binding column is part of the admin-state hash, so a stale state is
- * refused. Nothing under the canonical root is written: the opt-in is a
- * database column, the credential is Git metadata in `.git/config` plus a
- * 0600 store under the gbrain home (the same keys `sources harden` uses, so
- * `sources unharden` removes it), and the push probe is `git push --dry-run`.
+ * refused. The opt-in is a database column, the credential is Git metadata in
+ * `.git/config` plus a 0600 store under the gbrain home (the same keys
+ * `sources harden` uses, so `sources unharden` removes it), and the push probe
+ * is `git push --dry-run`. The one file under the canonical root this verb
+ * writes is the resolver file's durability block (#5808): `--enable` and
+ * `--pat-file` rewrite it idempotently to the managed variant, which never
+ * sends agents around the owner, and leave it for the operator to commit.
*/
import { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
@@ -28,6 +31,7 @@ import { getWorktreeBinding, type GitDurabilitySetting, type WorktreeBinding } f
import { requireWriterAdminIntent, assertWriterAdminState, writerAdminState } from './admin-intent.ts';
import { gitDurabilityPolicy, planGitDurabilityCatchUp, requeueGitDurabilityCatchUp } from './git-durability-policy.ts';
import { retryParkedEffects } from './effect-retry.ts';
+import { patchManagedDurabilityBlock } from '../brain-repo-durability.ts';
export const GIT_DURABILITY_PARAMS = ['source_id', 'enable', 'disable', 'pat_file', 'dry_run', 'admin_intent', 'expected_state'] as const;
@@ -232,6 +236,12 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, params
}
const plan = target === 'enabled' ? await planGitDurabilityCatchUp(engine, binding) : [];
report.catch_up = { planned: plan.length, paths: plan.slice(0, 50).map(effect => effect.relative_path) };
+ // #5808: a block `sources harden` rendered before activation tells agents to pull --rebase and run the push helper;
+ // on this managed root it is replaced with the managed variant (a non-page file: the operator commits it).
+ if (checkout) {
+ const agents = patchManagedDurabilityBlock(root, input.sourceId, input.dryRun);
+ report.agents = { ...agents, ...(agents.status === 'fixed' && !input.dryRun ? { commit: 'The durability block is a non-page file: review it and commit it with plain git; it rides the owner\'s next push.' } : {}) };
+ }
if (input.dryRun) {
const state = await writerAdminState(engine);
if (before === target && !token) return { ...report, queued_catch_up: 0, why: 'The setting is already as requested; nothing to apply.' };
diff --git a/test/durability-block-managed-5808.test.ts b/test/durability-block-managed-5808.test.ts
new file mode 100644
index 0000000000..77af19d717
--- /dev/null
+++ b/test/durability-block-managed-5808.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #5808 [R9]: the AGENTS durability block `gbrain sources harden` renders tells
+ * agents to run `scripts/brain-commit-push.sh` after every write and to
+ * `git fetch && git pull --rebase` before writing. On a managed canonical
+ * worktree both route agents around the persistence owner, and `sources harden`
+ * itself refuses there, so a block rendered before activation stayed stale.
+ *
+ * Fix: `gbrain sources writer git-durability <source> --enable` (and
+ * `--pat-file`) rewrites the block to its managed variant, idempotently,
+ * without touching the text outside the markers, without committing (the
+ * block is a non-page file the operator commits) and without any claim,
+ * transfer or topology change.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { 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 { hardenBrainRepo, patchManagedDurabilityBlock } from '../src/core/brain-repo-durability.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { gitAsync } from './helpers/git-publication.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+
+const BEGIN = '<!-- BEGIN gbrain-brain-durability (managed; do not edit between markers) -->';
+const END = '<!-- END gbrain-brain-durability -->';
+const CLASSIC = ['scripts/brain-commit-push.sh', 'git fetch && git pull --rebase', 'regenerated by `gbrain sources harden`'];
+const block = (text: string) => text.slice(text.indexOf(BEGIN), text.indexOf(END) + END.length);
+const outside = (text: string) => text.slice(0, text.indexOf(BEGIN)) + text.slice(text.indexOf(END) + END.length);
+
+let engine: PGLiteEngine;
+const homes: string[] = [];
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); for (const home of homes) rmSync(home, { recursive: true, force: true }); });
+
+async function isolated<T>(run: (home: string) => Promise<T>): Promise<T> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-5808-')); homes.push(home);
+ try {
+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, async () => { await registerLocalWriter(engine, 'cli'); return run(home); });
+ } finally { await disposePersistenceConsumer(engine); }
+}
+
+/** A checkout with a bare remote, hardened the classic way before anyone claimed it: the reported install. */
+async function hardenedRoot(home: string): Promise<{ root: string; agents: string; before: string }> {
+ const root = join(home, `root-${randomUUID().slice(0, 8)}`); mkdirSync(root);
+ await gitAsync(root, 'init', '-q', '-b', 'main');
+ await gitAsync(root, 'config', 'user.name', 'Example Writer');
+ await gitAsync(root, 'config', 'user.email', '[email protected]');
+ const agents = join(root, 'AGENTS.md');
+ writeFileSync(agents, '# Example brain\n\nHouse rules the operator wrote. Keep these.\n');
+ writeFileSync(join(root, 'initial.md'), 'Initial\n');
+ await gitAsync(root, 'add', '-A'); await gitAsync(root, 'commit', '-q', '-m', 'Initial');
+ const remote = join(home, `remote-${randomUUID().slice(0, 8)}.git`); mkdirSync(remote);
+ await gitAsync(remote, 'init', '-q', '--bare');
+ await gitAsync(root, 'remote', 'add', 'origin', remote); await gitAsync(root, 'push', '-q', '-u', 'origin', 'main');
+ const report = await hardenBrainRepo({ repoPath: root, sourceId: 'example', installCron: false, verify: false });
+ expect(report.steps.find(step => step.step === 'agents')).toMatchObject({ status: 'fixed' });
+ const before = readFileSync(agents, 'utf8');
+ for (const marker of CLASSIC) expect(block(before)).toContain(marker);
+ await gitAsync(root, 'add', '-A'); await gitAsync(root, 'commit', '-q', '-m', 'Harden');
+ return { root, agents, before };
+}
+
+describe('the managed durability block (#5808)', () => {
+ test('the managed variant never tells agents to pull --rebase or run the push helper, and is idempotent in place', () => isolated(async home => {
+ const { root, agents, before } = await hardenedRoot(home);
+ expect(patchManagedDurabilityBlock(root, 'vault-example', true)).toMatchObject({ status: 'fixed', detail: expect.stringContaining('dry-run') });
+ expect(readFileSync(agents, 'utf8')).toBe(before);
+ expect(patchManagedDurabilityBlock(root, 'vault-example', false)).toMatchObject({ status: 'fixed' });
+ const after = readFileSync(agents, 'utf8');
+ const managed = block(after);
+ for (const marker of CLASSIC) expect(managed).not.toContain(marker);
+ expect(managed).not.toContain('pull --rebase');
+ expect(managed).toContain('regenerated by `gbrain sources writer git-durability vault-example --enable`');
+ expect(managed).toContain('Page writes go through gbrain, never through git.');
+ expect(managed).toContain('Never pull, rebase or reset this checkout.');
+ expect(managed).toContain('gbrain sources writer status vault-example --json');
+ expect(managed).toContain('gbrain sources refresh vault-example');
+ expect(managed).toContain('Files that are not pages');
+ expect(managed).toContain('Deterministic filing');
+ expect(outside(after)).toBe(outside(before));
+ expect(after).toContain('House rules the operator wrote. Keep these.');
+ expect(patchManagedDurabilityBlock(root, 'vault-example', false)).toMatchObject({ status: 'ok', detail: expect.stringContaining('already current') });
+ expect(readFileSync(agents, 'utf8')).toBe(after);
+ }), 60_000);
+
+ test('git-durability --enable on an already-hardened managed install rewrites the stale block, commits nothing and changes no ownership', () => isolated(async home => {
+ const { root, agents, before } = await hardenedRoot(home);
+ const sourceId = `vault-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root, localHostId());
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ const binding = (await getWorktreeBinding(engine, sourceId, localHostId()))!;
+ const identity = (b: typeof binding) => [b.worktree_id, b.owner_host_id, String(b.owner_epoch), String(b.topology_generation), b.state, b.local_path];
+
+ const preview = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });
+ expect(preview).toMatchObject({ dry_run: true, push_probe: { ok: true }, agents: { status: 'fixed', detail: expect.stringContaining('dry-run') } });
+ expect(readFileSync(agents, 'utf8')).toBe(before);
+
+ const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });
+ expect(applied).toMatchObject({ applied: true, git_durability: { before: null, after: 'enabled' },
+ agents: { status: 'fixed', detail: expect.stringContaining('durability rules written'), commit: expect.stringContaining('plain git') } });
+ const after = readFileSync(agents, 'utf8');
+ for (const marker of CLASSIC) expect(block(after)).not.toContain(marker);
+ expect(block(after)).toContain(`gbrain sources writer git-durability ${sourceId} --enable`);
+ expect(outside(after)).toBe(outside(before));
+ // The verb commits nothing: the rewritten file is the operator's to commit, and no ownership record moved.
+ expect((await gitAsync(root, 'status', '--porcelain')).trim()).toBe('M AGENTS.md');
+ expect(identity((await getWorktreeBinding(engine, sourceId, localHostId()))!)).toEqual(identity(binding));
+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBe('enabled');
+
+ // A second --enable is a no-op for the block and for the file.
+ const again = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });
+ expect(again).toMatchObject({ agents: { status: 'ok', detail: expect.stringContaining('already current') }, why: expect.stringContaining('already as requested') });
+ expect(readFileSync(agents, 'utf8')).toBe(after);
+
+ // --disable leaves the block alone: the checkout stays managed either way.
+ const disabled = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, disable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });
+ expect(disabled).toMatchObject({ applied: true, git_durability: { before: 'enabled', after: 'disabled' } });
+ expect(disabled.agents).toBeUndefined();
+ expect(readFileSync(agents, 'utf8')).toBe(after);
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }), 120_000);
+});