Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: per-host git_durability opt-in column, policy resolver and writer git-durability verb (#5182, #5808)

garrytanc3ecf565d86b
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 2ccff6d661..c858835f80 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1098,6 +1098,30 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit
|---|---|---|---|---|---|---|
| The eval gate found retrieval regressions or correctness below its thresholds. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### git_branch_unborn
+
+<a id="git_branch_unborn"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The canonical checkout's branch has no commit yet, so Git durability has nothing to build on. | 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. | 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. | host_admin | `gbrain doctor --json` | 1 | no |
+
+### git_checkout_required
+
+<a id="git_checkout_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to. | Only the operator of the brain host can change what blocks this. | 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. | host_admin | `gbrain doctor --json` | 1 | no |
+
+### git_detached_head
+
+<a id="git_detached_head"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| 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_index_locked
<a id="git_index_locked"></a>
@@ -1918,6 +1942,14 @@ More: [docs/guides/repair.md#page-projection-conflict](../../docs/guides/repair.
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### pat_file_unreadable
+
+<a id="pat_file_unreadable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read. | The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written. | Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file. | agent | `repeat the read that failed` | 1 | no |
+
### pattern_claims_pending
<a id="pattern_claims_pending"></a>
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 8d799988c2..af8b30d9d1 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -18,6 +18,7 @@ export const WRITER_HELP = `Usage:
gbrain sources writer status [<source>] [--probe] [--json]
gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]
gbrain sources writer retry-effects <source> --request-id <uuid> [--dry-run] [--json]
+ gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [administration options] [--dry-run] [--json]
gbrain sources writer claim <source> --path <directory> [administration options] [--dry-run] [--json]
gbrain sources writer activate --confirm-quiesced [--cleanup-dead-local-locks] [--shared-skills] [administration options] [--dry-run] [--json]
gbrain sources writer deactivate [--admin-intent writer_deactivate --expected-state <admin_state>] [--dry-run] [--json]
@@ -32,7 +33,11 @@ restarting serve and the workers; see movement --help for its states and exits.
Routine diagnosis, doctor --fix, startup, and maintenance
must not change ownership or activate managed persistence. Read the operator
procedure in docs/architecture/topologies.md before deliberate administration.
-Non-dry-run changes require --admin-intent <writer_claim|writer_activate|writer_deactivate|writer_transfer_prepare|writer_transfer_accept>
+git-durability records whether this owner commits (and pushes) page writes through
+its Git effect; --enable runs a read-only push probe first and re-queues the Git
+effects skipped while it was off, --pat-file wires a repo-scoped push credential
+(same keys as sources harden) and retries this worktree's parked pushes.
+Non-dry-run changes require --admin-intent <writer_claim|writer_activate|writer_deactivate|writer_transfer_prepare|writer_transfer_accept|writer_git_durability>
matching the action and --expected-state <admin_state from reviewed status>.
These checks also apply to interactive terminals; --yes is not a substitute.
Explicit noninteractive administration is supported. Stale state is rejected.
@@ -110,7 +115,7 @@ export function adminHostConfig<T extends GBrainConfig>(config: T | null | undef
type Group = 'writer' | 'local-writer';
const GROUP_ARGV: Record<Group, string[]> = { writer: ['gbrain', 'sources', 'writer'], 'local-writer': ['gbrain', 'auth', 'local-writer'] };
-const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--cleanup-dead-local-locks', '--shared-skills'];
+const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--cleanup-dead-local-locks', '--shared-skills', '--enable', '--disable'];
/** A CLI usage refusal: the exact usage in the suggestion, the group's help as the read-only fix. */
function invalid(group: Group, message: string, suggestion: string) {
return opError('invalid_params', message, suggestion, {
@@ -127,7 +132,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
'--path': 'path', '--source': 'source_id', '--expected-epoch': 'expected_epoch', '--manifest': 'manifest',
'--source-ids': 'source_ids', '--scopes': 'scopes', '--allowed-operations': 'allowed_operations',
'--slug-prefixes': 'slug_prefixes', '--limit': 'limit', '--before': 'before',
- '--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id',
+ '--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id', '--pat-file': 'pat_file',
};
const arrays = new Set(['source_ids', 'scopes', 'allowed_operations', 'slug_prefixes']);
const seen = new Set<string>();
@@ -152,13 +157,14 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (flag === '--brain') { brain = value; continue; }
const key = values[flag];
params[key] = arrays.has(key) ? value.split(',').map(part => part.trim()).filter(Boolean)
- : key === 'limit' ? Number(value) : key === 'path' ? resolve(value) : value;
+ : key === 'limit' ? Number(value) : key === 'path' || key === 'pat_file' ? resolve(value) : value;
}
let operation: PersistenceAdminOperation;
if (group === 'writer') {
const verb = positional.shift();
if (verb === 'status') operation = 'writer_status';
else if (verb === 'retry-effects') operation = 'writer_retry_effects';
+ else if (verb === 'git-durability') operation = 'writer_git_durability';
else if (verb === 'claim') operation = 'writer_claim';
else if (verb === 'activate') operation = 'writer_activate';
else if (verb === 'deactivate') operation = 'writer_deactivate';
@@ -169,7 +175,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (phase !== 'prepare' && phase !== 'accept') throw invalid(group, 'Transfer requires prepare or accept.',
'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed.');
operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';
- } else throw invalid(group, 'Writer administration requires status, movement, retry-effects, claim, activate, deactivate, transfer, lock, or unlock.',
+ } else throw invalid(group, 'Writer administration requires status, movement, retry-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
`Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);
const source = positional.shift();
if (source !== undefined) {
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index afa8c60013..089200a63a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -192,6 +192,9 @@ export const CODES = {
frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
+ 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.' },
+ 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." },
git_index_stale: { class: 'caller', summary: "Git index stale." },
git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },
@@ -336,6 +339,7 @@ export const CODES = {
receipt_fence_changed: { class: 'caller', summary: "The managed owner, topology or source binding changed while the ingestion ran.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
receipt_identity_mismatch: { class: 'caller', summary: "The receipt ID is already bound to different approved ingestion metadata.", docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' },
+ pat_file_unreadable: { class: 'caller', summary: "The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read.", why: "The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written.", suggestion: 'Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file.' },
recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },
redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },
diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.ts
index 394d11b367..66aa917e4f 100644
--- a/src/core/persistence/admin-contract.ts
+++ b/src/core/persistence/admin-contract.ts
@@ -3,7 +3,7 @@
export const WRITER_ADMIN_LOCK_KEY = 'persistence.writer_admin_lock';
export const PERSISTENCE_ADMIN_OPERATIONS = [
'writer_status', 'writer_sync', 'writer_refresh', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',
- 'writer_deactivate', 'writer_lock', 'writer_unlock',
+ 'writer_deactivate', 'writer_lock', 'writer_unlock', 'writer_git_durability',
'local_writer_list', 'local_writer_register', 'local_writer_revoke',
'source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect', 'company_brain_resume',
'writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',
diff --git a/src/core/persistence/admin-intent.ts b/src/core/persistence/admin-intent.ts
index 076e5d780f..f02f299e8d 100644
--- a/src/core/persistence/admin-intent.ts
+++ b/src/core/persistence/admin-intent.ts
@@ -14,7 +14,7 @@ export async function writerAdminState(engine: SqlEngine): Promise<string> {
'fallback', (SELECT value FROM config WHERE key='sync.repo_path'),
'worktrees', (SELECT jsonb_agg(jsonb_build_array(id,owner_host_id,owner_epoch::text,topology_generation::text,state,manifest) ORDER BY id) FROM persistence_worktrees),
'bindings', (SELECT jsonb_agg(jsonb_build_array(source_id,source_incarnation,worktree_id,relative_path,topology_generation::text) ORDER BY source_id) FROM persistence_source_bindings),
- 'hosts', (SELECT jsonb_agg(jsonb_build_array(worktree_id,host_id,local_path,coordination_path) ORDER BY worktree_id,host_id) FROM persistence_host_bindings),
+ 'hosts', (SELECT jsonb_agg(jsonb_build_array(worktree_id,host_id,local_path,coordination_path,git_durability) ORDER BY worktree_id,host_id) FROM persistence_host_bindings),
'legacy_locks', (SELECT jsonb_agg(jsonb_build_array(id,holder_pid,holder_host,acquisition_token,acquired_at) ORDER BY id) FROM gbrain_cycle_locks)
)::text AS state`);
return sha256(row.state);
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index a025140530..0506c7816c 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -154,6 +154,12 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
}
if (operation === 'writer_reindex_code') return (await import('./reindex-administration.ts')).runAuthenticatedCodeReindex(engine, params);
if (operation === 'writer_embed_facts') return (await import('./embed-facts-administration.ts')).runAuthenticatedFactEmbedding(engine, params, config);
+ if (operation === 'writer_git_durability') {
+ const { GIT_DURABILITY_PARAMS, runGitDurabilityAdministration } = await import('./git-durability-administration.ts');
+ keys(params, [...GIT_DURABILITY_PARAMS]);
+ source(params.source_id);
+ return runGitDurabilityAdministration(engine, params);
+ }
if (operation === 'writer_retry_effects') {
keys(params, ['source_id', 'request_id', 'dry_run']);
if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.',
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
new file mode 100644
index 0000000000..9d7daf82f4
--- /dev/null
+++ b/src/core/persistence/git-durability-administration.ts
@@ -0,0 +1,253 @@
+/**
+ * `gbrain sources writer git-durability <source> --enable|--disable [--pat-file <p>] [--dry-run]`
+ * (#5182, #5808): the trusted-local admin verb that records a managed worktree's
+ * Git-durability opt-in on this host's binding, re-wires the repo-scoped push
+ * credential, and catches up the Git effects skipped while durability was off.
+ *
+ * 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`.
+ */
+import { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { execFileBounded } from '../bounded-child-exec.ts';
+import { classifyGitCheckout } from '../git-checkout.ts';
+import { durableSsrfFlags, GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS } from '../git-remote.ts';
+import { ensureGbrainHome, resolveGbrainHome } from '../gbrain-home.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
+import type { BrainEngine } from '../engine.ts';
+import { existingLocalHostId } from './identity.ts';
+import { getWorktreeBinding, type GitDurabilitySetting, type WorktreeBinding } from './ownership.ts';
+import { requireWriterAdminIntent, assertWriterAdminState, writerAdminState } from './admin-intent.ts';
+import { gitDurabilityPolicy, planGitDurabilityCatchUp, requeueGitDurabilityCatchUp } from './git-durability-policy.ts';
+import { retryParkedEffects } from './effect-retry.ts';
+
+export const GIT_DURABILITY_PARAMS = ['source_id', 'enable', 'disable', 'pat_file', 'dry_run', 'admin_intent', 'expected_state'] as const;
+
+/** The same repo-local key `sources harden` writes, so `sources unharden` removes a credential this verb wired. */
+const CRED_MANAGED_KEY = 'gbrain.durability.managedcredential';
+const GIT_TIMEOUT_MS = 20_000;
+
+const statusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s owner binding, its git_durability setting and the admin_state the verb needs, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
+const invalid = (message: string, suggestion: string, sourceId?: string) => opError('invalid_params', message, suggestion, sourceId ? { fix: statusFix(sourceId) } : {});
+
+export interface GitDurabilityInput { sourceId: string; enable: boolean; disable: boolean; patFile?: string; dryRun: boolean }
+
+export function parseGitDurabilityParams(params: Record<string, unknown>): GitDurabilityInput {
+ for (const key of ['enable', 'disable', 'dry_run'] as const) {
+ if (params[key] !== undefined && typeof params[key] !== 'boolean') throw invalid(`${key} must be a boolean.`, `Pass --${key.replace('_', '-')} as a bare flag; it takes no value.`);
+ }
+ if (params.enable === true && params.disable === true) throw invalid('Choose --enable or --disable, not both.',
+ 'Run gbrain sources writer git-durability <source> --enable to publish through the persistence owner, or --disable to keep Git effects off.');
+ if (params.pat_file !== undefined && (typeof params.pat_file !== 'string' || !params.pat_file.trim() || params.pat_file.includes('\0'))) {
+ throw invalid('pat_file must be a path to a file holding the token.', 'Pass --pat-file <path>; the token is read from that 0600 file and never from the command line.');
+ }
+ if (params.disable === true && params.pat_file !== undefined) throw invalid('--pat-file cannot be combined with --disable.',
+ 'Disable without a token, or re-wire the credential with --enable --pat-file <path> (or --pat-file alone to keep the current setting).');
+ if (params.enable !== true && params.disable !== true && params.pat_file === undefined) throw invalid('Name the change: --enable, --disable, or --pat-file <path>.',
+ 'gbrain sources writer git-durability <source> --enable publishes page writes through the owner\'s Git effect; --disable turns that off; --pat-file <path> alone re-wires the push credential and retries parked pushes.');
+ return { sourceId: String(params.source_id), enable: params.enable === true, disable: params.disable === true,
+ patFile: typeof params.pat_file === 'string' ? params.pat_file : undefined, dryRun: params.dry_run === true };
+}
+
+async function git(root: string, args: string[], auth = false): Promise<{ code: number; stdout: string; stderr: string }> {
+ const { error, stdout, stderr } = await execFileBounded('git', ['-C', root, ...(auth ? durableSsrfFlags() : []), ...args],
+ { timeout: GIT_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: { ...process.env, ...GIT_ENV, ...(auth ? GIT_ENV_AUTH : {}), LC_ALL: 'C' } });
+ if (error && (error.killed || typeof error.code !== 'number')) throw opError('git_unavailable', 'Git did not finish within its bounded attempt.',
+ `git ${args[0]} in ${root} did not finish within ${GIT_TIMEOUT_MS / 1000} seconds or could not start; nothing was changed. Check that git runs in that checkout on the brain host, then rerun.`);
+ return { code: error ? error.code as number : 0, stdout, stderr };
+}
+
+/**
+ * The checkout must be a Git checkout on a born branch before durability can
+ * be enabled: a detached HEAD would push the wrong ref, and an unborn branch
+ * (a fresh `init --git` root with no commit yet, #6332) has nothing to push
+ * and is named as such, not as a detached HEAD.
+ */
+export async function inspectDurabilityCheckout(root: string): Promise<{ branch: string; remote: string | null; merge: string | null }> {
+ const checkout = classifyGitCheckout(root);
+ if (checkout !== 'git') {
+ throw opError('git_checkout_required', `${root} is not inside a Git checkout, so its Git effects have nothing to commit to.`,
+ 'Initialize the canonical root as a Git repository (git init, a first commit, and a remote) on the brain host, then rerun; a database-only source needs no Git durability.');
+ }
+ const symbolic = await git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
+ if (symbolic.code !== 0) {
+ throw opError('git_detached_head', `${root} is on a detached HEAD, so a push would target the wrong ref.`,
+ 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.');
+ }
+ const branch = symbolic.stdout.trim();
+ const head = await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']);
+ if (head.code !== 0) {
+ throw opError('git_branch_unborn', `Branch ${branch} in ${root} is unborn: it has no commit yet, so there is nothing for a Git effect to build on.`,
+ `Make the first commit on ${branch} (for example commit the existing page files with git add -A && git commit -m "Initial brain") on the brain host, then rerun.`);
+ }
+ const remote = await git(root, ['config', '--get', `branch.${branch}.remote`]);
+ const merge = await git(root, ['config', '--get', `branch.${branch}.merge`]);
+ const tracked = remote.code === 0 && merge.code === 0 && remote.stdout.trim() && remote.stdout.trim() !== '.';
+ return { branch, remote: tracked ? remote.stdout.trim() : null, merge: tracked ? merge.stdout.trim() : null };
+}
+
+export type PushProbe = { ok: true; skipped?: 'no_tracking_remote' } | { ok: false; reason: 'auth' | 'protected' | 'unreachable' | 'other'; detail: string };
+
+/** `git push --dry-run` to the branch's tracking remote: proves push authority without a commit; the same refspec the Git effect pushes. */
+export async function probeDurabilityPush(root: string, checkout: { remote: string | null; merge: string | null }, redact: (s: string) => string): Promise<PushProbe> {
+ if (!checkout.remote || !checkout.merge) return { ok: true, skipped: 'no_tracking_remote' };
+ const push = await git(root, ['push', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--dry-run', '--', checkout.remote, `HEAD:${checkout.merge}`], true);
+ if (push.code === 0) return { ok: true };
+ const detail = redact(`${push.stderr}\n${push.stdout}`).replace(/\s+/g, ' ').trim().slice(0, 200);
+ const low = detail.toLowerCase();
+ const reason = low.includes('authentication') || low.includes('403') || low.includes('permission') || low.includes('could not read') ? 'auth'
+ : low.includes('protected') || low.includes('pre-receive') || low.includes('hook declined') ? 'protected'
+ : low.includes('could not resolve') || low.includes('unable to access') || low.includes('timed out') || low.includes('network') ? 'unreachable' : 'other';
+ return { ok: false, reason, detail };
+}
+
+/** Read the token from a private file: refuses a group/other-readable or empty file before anything is written. */
+export function readPatFile(path: string): string {
+ if (!existsSync(path)) throw opError('pat_file_unreadable', `--pat-file ${path} does not exist.`, 'Write the token to a file only you can read (chmod 600), then pass its path with --pat-file.');
+ const mode = statSync(path).mode;
+ if (process.platform !== 'win32' && (mode & 0o077) !== 0) {
+ throw opError('pat_file_unreadable', `--pat-file ${path} is group- or other-readable (mode ${(mode & 0o777).toString(8)}), so it was not read.`,
+ `Run chmod 600 ${path} and rerun; a token file that other users can read is refused before any credential is written.`);
+ }
+ const token = readFileSync(path, 'utf8').trim();
+ if (!token || /\s/.test(token)) throw opError('pat_file_unreadable', `--pat-file ${path} is empty or holds more than one token.`,
+ 'Put exactly one token on one line in the file, then rerun.');
+ return token;
+}
+
+async function remoteHost(root: string, remote: string | null): Promise<string> {
+ const url = remote ? await git(root, ['remote', 'get-url', remote]) : { code: 1, stdout: '' };
+ try { return new URL(url.stdout.trim()).hostname || 'github.com'; } catch { return 'github.com'; }
+}
+
+/**
+ * Wire a repo-scoped credential for the tracking remote's host: a repo-LOCAL
+ * `credential.helper store --file <gbrain-home>/git-credentials` (0600) marked
+ * with the key `sources harden` uses, so both verbs share one store and
+ * `sources unharden` removes either's wiring. A repo-local helper gbrain did not
+ * write is left alone. The token never appears in the result or a log line.
+ */
+export async function wireDurabilityCredential(root: string, remote: string | null, token: string, dryRun: boolean): Promise<{ status: 'ok' | 'fixed'; detail: string }> {
+ const existing = (await git(root, ['config', '--local', '--get', 'credential.helper'])).stdout.trim();
+ const ours = (await git(root, ['config', '--local', '--get', CRED_MANAGED_KEY])).stdout.trim() === 'true';
+ if (existing && !ours) return { status: 'ok', detail: 'reusing the repo-local credential.helper another tool configured (no store written)' };
+ const host = await remoteHost(root, remote);
+ const store = join(resolveGbrainHome(), 'git-credentials');
+ const line = `https://x-access-token:${token}@${host}`;
+ const lines = existsSync(store) ? readFileSync(store, 'utf8').split('\n') : [];
+ if (ours && existing && lines.includes(line)) return { status: 'ok', detail: `repo-scoped credential already wired for ${host}` };
+ if (dryRun) return { status: 'fixed', detail: `would wire a repo-scoped credential for ${host} (dry-run)` };
+ ensureGbrainHome();
+ const prefix = 'https://x-access-token:';
+ const kept = lines.filter(entry => entry && !(entry.startsWith(prefix) && entry.endsWith(`@${host}`)));
+ writeFileSync(store, `${[...kept, line].join('\n')}\n`, { mode: 0o600 });
+ try { chmodSync(store, 0o600); } catch { /* best effort on filesystems without modes */ }
+ const set = await git(root, ['config', '--local', 'credential.helper', `store --file ${store}`]);
+ const mark = await git(root, ['config', '--local', CRED_MANAGED_KEY, 'true']);
+ if (set.code !== 0 || mark.code !== 0) throw opError('git_unavailable', 'The repo-local credential helper could not be configured.',
+ `git config --local in ${root} failed, so the push credential was not wired; nothing else changed. Check that the checkout's .git/config is writable on the brain host, then rerun.`);
+ return { status: 'fixed', detail: `wired a repo-scoped credential for ${host} (store 0600; replaces an earlier token for that host)` };
+}
+
+/**
+ * #5808(a): after a credential change, one more attempt for every effect of this
+ * worktree that parked on `git_push_unavailable`. Other worktrees are untouched;
+ * each request goes through `retryParkedEffects`, so the original write's
+ * authority is re-checked and a claimed or settled effect is left alone.
+ */
+export async function retryParkedPushes(engine: BrainEngine, worktreeId: string, dryRun: boolean): Promise<{ requests: number; queued: number; unchanged: number }> {
+ const rows = await engine.executeRaw<{ source_id: string; request_id: string }>(`
+ SELECT DISTINCT e.source_id,e.request_id::text AS request_id FROM persistence_effects e
+ WHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND e.recovery IS NULL
+ AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) p WHERE p->>'error_code'='git_push_unavailable')
+ ORDER BY e.source_id,request_id`, [worktreeId]);
+ let queued = 0, unchanged = 0;
+ for (const row of rows) {
+ const result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun);
+ const effects = (result?.effects ?? []) as Array<{ action: string }>;
+ if (effects.some(effect => effect.action === 'retry_queued' || effect.action === 'would_retry')) queued++; else unchanged++;
+ }
+ return { requests: rows.length, queued, unchanged };
+}
+
+async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<WorktreeBinding & { local_path: string }> {
+ const hostId = existingLocalHostId();
+ const binding = await getWorktreeBinding(engine, sourceId, hostId);
+ if (!binding) {
+ throw opError('writer_registration_required', `Source ${sourceId} has no canonical owner on this brain.`,
+ `Claim its checkout first (gbrain sources writer claim ${sourceId} --path <directory>, with the admin-intent handshake), then enable Git durability; a database-only source needs neither.`,
+ { fix: statusFix(sourceId) });
+ }
+ if (!hostId || binding.owner_host_id !== hostId || !binding.local_path) {
+ throw opError('permission_denied', `Only source ${sourceId}'s owner host can change its Git durability.`,
+ `This host is not the registered owner of source ${sourceId}'s checkout (or has no local binding for it), so nothing was changed. Run the verb on the owner host that writer status names.`,
+ { fix: statusFix(sourceId) });
+ }
+ if (binding.state !== 'active') throw opError('recovery_required', `Source ${sourceId}'s worktree is ${binding.state}, not active.`,
+ 'Finish the pending recovery or transfer that writer status shows before changing Git durability; the setting is recorded on the active binding.', { fix: statusFix(sourceId) });
+ return binding as WorktreeBinding & { local_path: string };
+}
+
+/** The verb. `params` are the raw admin params; the caller has already checked the key set. */
+export async function runGitDurabilityAdministration(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const input = parseGitDurabilityParams(params);
+ const binding = await ownedBinding(engine, input.sourceId);
+ const root = binding.local_path;
+ const token = input.patFile === undefined ? undefined : readPatFile(input.patFile);
+ const redact = token ? (text: string) => text.split(token).join('[redacted]') : (text: string) => text;
+ const before: GitDurabilitySetting = binding.git_durability;
+ const target: GitDurabilitySetting = input.enable ? 'enabled' : input.disable ? 'disabled' : before;
+ const report: Record<string, unknown> = { source_id: input.sourceId, worktree_id: binding.worktree_id, path: root, dry_run: input.dryRun,
+ git_durability: { before, after: target }, action: 'writer_git_durability' };
+ // Policy under the current binding, so the operator sees what the hook probe says when nothing is recorded yet.
+ report.current_policy = await gitDurabilityPolicy(binding, root).then(policy => ({ ...policy }), error => ({ error: error instanceof Error ? error.message : String(error) }));
+ let checkout: Awaited<ReturnType<typeof inspectDurabilityCheckout>> | undefined;
+ if (target === 'enabled' || token) {
+ checkout = await inspectDurabilityCheckout(root);
+ report.branch = checkout.branch;
+ report.tracking_remote = checkout.remote;
+ }
+ if (token && checkout) {
+ report.credential = await wireDurabilityCredential(root, checkout.remote, token, input.dryRun);
+ // Only after the credential write succeeded: one more attempt per parked push of this worktree.
+ report.parked_pushes = await retryParkedPushes(engine, binding.worktree_id, input.dryRun);
+ }
+ if (target === 'enabled' && checkout) {
+ const probe = await probeDurabilityPush(root, checkout, redact);
+ report.push_probe = probe;
+ if (!probe.ok) {
+ throw opError('git_push_unavailable', `The read-only push probe for ${input.sourceId} failed (${probe.reason}), so Git durability was not enabled.`,
+ `git push --dry-run to ${checkout.remote} from ${root} failed: ${probe.detail || probe.reason}. Enabling now would park every Git effect on its push. ${probe.reason === 'auth' ? 'Pass a token file with --pat-file <path> (chmod 600) to wire a repo-scoped credential, or ' : ''}Fix the remote or its credentials on the brain host, check with git push --dry-run there, then rerun. Nothing was changed.`,
+ { fix: statusFix(input.sourceId) });
+ }
+ }
+ const plan = target === 'enabled' ? await planGitDurabilityCatchUp(engine, binding) : [];
+ report.catch_up = { planned: plan.length, paths: plan.slice(0, 50).map(effect => effect.relative_path) };
+ if (input.dryRun) {
+ const state = await writerAdminState(engine);
+ return { ...report, queued_catch_up: 0, next_action: before === target && !token ? 'The setting is already as requested; nothing to apply.'
+ : `Review this preview, then apply with: gbrain sources writer git-durability ${input.sourceId}${input.enable ? ' --enable' : input.disable ? ' --disable' : ''}${input.patFile ? ` --pat-file ${input.patFile}` : ''} --admin-intent writer_git_durability --expected-state ${state}` };
+ }
+ const expectedState = await requireWriterAdminIntent(engine, 'writer_git_durability', params);
+ const queued = await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','2000ms',true),set_config('synchronous_commit','on',true)");
+ await assertWriterAdminState(tx, expectedState);
+ const [updated] = await tx.executeRaw<{ git_durability: GitDurabilitySetting }>(`UPDATE persistence_host_bindings SET git_durability=$3
+ WHERE worktree_id=$1::uuid AND host_id=$2::uuid RETURNING git_durability`, [binding.worktree_id, binding.owner_host_id, target]);
+ if (!updated) throw opError('source_changed', 'The host binding disappeared while the setting was being recorded.',
+ `Source ${input.sourceId}'s host binding was removed by another topology change, so nothing was recorded. Inspect writer status before trying again.`, { fix: statusFix(input.sourceId) });
+ return target === 'enabled' ? await requeueGitDurabilityCatchUp(tx, binding, plan.map(effect => effect.id)) : [];
+ });
+ return { ...report, applied: true, queued_catch_up: queued.length,
+ next_action: target === 'enabled' ? `Page writes to ${input.sourceId} now commit (and push to ${checkout?.remote ?? 'no tracking remote: commits stay local'}) through the persistence owner's Git effect; ${queued.length} earlier skipped effect(s) were re-queued. Check with gbrain sources writer status ${input.sourceId} --json.`
+ : target === 'disabled' ? `Git effects for ${input.sourceId} now complete as skipped (durability_not_enabled) even where a legacy hook exists; database writes are unaffected. Re-enable with --enable; the skipped effects are caught up then.`
+ : `The push credential was re-wired; ${report.parked_pushes ? (report.parked_pushes as { queued: number }).queued : 0} parked push(es) got one more attempt.` };
+}
diff --git a/src/core/persistence/git-durability-policy.ts b/src/core/persistence/git-durability-policy.ts
new file mode 100644
index 0000000000..86e4a868ba
--- /dev/null
+++ b/src/core/persistence/git-durability-policy.ts
@@ -0,0 +1,82 @@
+/**
+ * Git-durability policy for a managed worktree (#5182).
+ *
+ * Whether the persistence owner commits (and pushes) page writes through its
+ * Git effect used to be read only from the legacy `sources harden` post-commit
+ * hook banner, which an operator cannot install once the brain is managed. The
+ * per-host binding now records the operator's explicit setting
+ * (`persistence_host_bindings.git_durability`, tri-state):
+ *
+ * 'enabled' → durable, no hook needed (the outbox owns durability);
+ * 'disabled' → not durable, even where a legacy hook exists;
+ * null → not recorded: the legacy hook probe decides, as before.
+ *
+ * Fail-closed: a probe failure under `null` is an error the effect records,
+ * never a silent "durable". The resolver takes the probe as a parameter so the
+ * effect runner can inject its cached per-root probe and tests can stub it.
+ *
+ * The catch-up planner lists the Git effects of a worktree that completed as
+ * `durability_not_enabled` while the setting was off, and the requeue re-arms
+ * exactly those rows: no row is inserted (UNIQUE(request_id,kind) stays
+ * untouched), so a request keeps its one Git effect and the worker's ordinary
+ * claim runs it.
+ */
+import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
+import type { SqlEngine } from './model.ts';
+import type { WorktreeBinding } from './ownership.ts';
+import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+
+export const DURABILITY_NOT_ENABLED_REASON = 'durability_not_enabled';
+
+export type GitDurabilityPolicy = { durable: boolean; source: 'binding' | 'legacy_hook' | 'no_hook' };
+
+/** The policy for `root` under `binding`; `probe` is the legacy hook probe, used only when nothing is recorded. */
+export async function gitDurabilityPolicy(binding: Pick<WorktreeBinding, 'git_durability'> | null | undefined, root: string,
+ probe: (root: string) => Promise<boolean> = isDurabilityHardenedAsync): Promise<GitDurabilityPolicy> {
+ if (binding?.git_durability === 'enabled') return { durable: true, source: 'binding' };
+ if (binding?.git_durability === 'disabled') return { durable: false, source: 'binding' };
+ const hooked = await probe(root);
+ return hooked ? { durable: true, source: 'legacy_hook' } : { durable: false, source: 'no_hook' };
+}
+
+/** The operator-facing tri-state: what is recorded, before any probe. */
+export function gitDurabilityState(binding: Pick<WorktreeBinding, 'git_durability'> | null | undefined): 'on' | 'off' | 'unknown' {
+ return binding?.git_durability === 'enabled' ? 'on' : binding?.git_durability === 'disabled' ? 'off' : 'unknown';
+}
+
+export interface GitDurabilityCatchUpEffect { id: string; request_id: string; relative_path: string | null; slug: string | null }
+
+/**
+ * The Git effects of this worktree (current source incarnation) that completed
+ * as skipped because durability was off: one per file, the latest. A page
+ * written several times needs one commit of its current file, so earlier
+ * skipped effects for the same path are left completed. Source scans and
+ * recovered or claimed effects are not catch-up candidates.
+ */
+export async function planGitDurabilityCatchUp(engine: SqlEngine, binding: Pick<WorktreeBinding, 'worktree_id' | 'source_id' | 'source_incarnation'>): Promise<GitDurabilityCatchUpEffect[]> {
+ return engine.executeRaw<GitDurabilityCatchUpEffect>(`
+ SELECT DISTINCT ON (e.data->>'relative_path') e.id::text AS id,e.request_id::text AS request_id,e.data->>'relative_path' AS relative_path,e.data->>'slug' AS slug
+ FROM persistence_effects e
+ WHERE e.worktree_id=$1::uuid AND e.source_id=$2 AND e.source_incarnation=$3::uuid AND e.kind='git' AND e.state='committed'
+ AND e.outcome->>'reason'=$4 AND e.recovery IS NULL AND e.execution_token IS NULL
+ AND COALESCE((e.data->>'source_scan')::boolean,false)=false AND e.data->>'relative_path' IS NOT NULL
+ ORDER BY e.data->>'relative_path',e.id DESC`, [binding.worktree_id, binding.source_id, binding.source_incarnation, DURABILITY_NOT_ENABLED_REASON]);
+}
+
+/**
+ * Re-arm the planned effects inside the caller's transaction. Every predicate of
+ * the plan is repeated, so an effect the worker touched since the plan was read
+ * (or that is no longer skipped) is left alone; the returned ids are the rows
+ * actually queued.
+ */
+export async function requeueGitDurabilityCatchUp(tx: SqlEngine, binding: Pick<WorktreeBinding, 'worktree_id' | 'source_incarnation'>, ids: readonly string[]): Promise<string[]> {
+ if (!ids.length) return [];
+ await declarePersistenceProtocol(tx);
+ const rows = await tx.executeRaw<{ id: string }>(`
+ UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,error_code=NULL,outcome=NULL,
+ next_attempt_at=now(),updated_at=now(),data=data||jsonb_build_object('durability_catch_up',COALESCE((data->>'durability_catch_up')::int,0)+1)
+ WHERE id=ANY($1::text[]::bigint[]) AND kind='git' AND state='committed' AND outcome->>'reason'=$4 AND worktree_id=$2::uuid AND source_incarnation=$3::uuid
+ AND recovery IS NULL AND execution_token IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}
+ RETURNING id::text AS id`, [[...ids], binding.worktree_id, binding.source_incarnation, DURABILITY_NOT_ENABLED_REASON]);
+ return rows.map(row => row.id);
+}
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index ef90fbf429..a2b93e7c4c 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -37,7 +37,10 @@ export interface WorktreeBinding {
state: 'active' | 'draining' | 'recovering';
local_path: string | null;
coordination_path: string | null;
+ /** #5182 per-host Git-durability opt-in: null until an operator records one. */
+ git_durability: GitDurabilitySetting;
}
+export type GitDurabilitySetting = 'enabled' | 'disabled' | null;
export function containsPath(root: string, path: string): boolean {
const rel = relative(root, path);
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
@@ -49,7 +52,7 @@ export async function managedPersistenceEnabled(engine: SqlEngine): Promise<bool
export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
const [row] = await engine.executeRaw<WorktreeBinding>(`SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path,
s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,
- h.local_path,h.coordination_path FROM persistence_source_bindings s
+ h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s
JOIN persistence_worktrees w ON w.id=s.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid
WHERE s.source_id=$1`, [sourceId, hostId]);
diff --git a/src/core/persistence/schema.ts b/src/core/persistence/schema.ts
index 20e68fc583..e238b2d769 100644
--- a/src/core/persistence/schema.ts
+++ b/src/core/persistence/schema.ts
@@ -117,6 +117,7 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
host_id uuid NOT NULL,
local_path text NOT NULL,
coordination_path text NOT NULL,
+ git_durability text CHECK (git_durability IN ('enabled','disabled')),
PRIMARY KEY(worktree_id,host_id)
)`,
`CREATE TABLE IF NOT EXISTS persistence_local_writers (
@@ -192,3 +193,13 @@ export const PERSISTENCE_SCHEMA_STATEMENTS = [
PERSISTENCE_CONSUMERS_TABLE_SQL,
MANAGED_WRITER_GUARD_SQL,
] as const;
+
+/**
+ * #5182: the per-host Git-durability opt-in column, added by v232 on an
+ * existing brain. Deliberately NOT part of the schema statement list: a fresh
+ * install gets the column from CREATE TABLE above, and replaying an ALTER on
+ * every init would take an ACCESS EXCLUSIVE lock on the bindings table each
+ * time the schema blob runs. NULL means "not recorded" (legacy hook probe
+ * decides); 'enabled'/'disabled' is the operator's explicit setting.
+ */
+export const PERSISTENCE_GIT_DURABILITY_COLUMN_SQL = `ALTER TABLE persistence_host_bindings ADD COLUMN IF NOT EXISTS git_durability text CHECK (git_durability IN ('enabled','disabled'))`;
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index e0e76a11e7..dfcab82625 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1257,6 +1257,7 @@ CREATE TABLE IF NOT EXISTS persistence_host_bindings (
host_id uuid NOT NULL,
local_path text NOT NULL,
coordination_path text NOT NULL,
+ git_durability text CHECK (git_durability IN ('enabled','disabled')),
PRIMARY KEY(worktree_id,host_id)
);
CREATE TABLE IF NOT EXISTS persistence_local_writers (
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index c815c62cb4..123a349980 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1994,6 +1994,7 @@ CREATE TABLE IF NOT EXISTS persistence_host_bindings (
host_id uuid NOT NULL,
local_path text NOT NULL,
coordination_path text NOT NULL,
+ git_durability text CHECK (git_durability IN ('enabled','disabled')),
PRIMARY KEY(worktree_id,host_id)
);
CREATE TABLE IF NOT EXISTS persistence_local_writers (
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index f08dfeeffd..ed00b02841 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 231;
+export const LATEST_SCHEMA_VERSION = 232;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 7b020ce4dc..bb00e2138c 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -232,6 +232,7 @@ import { v228 } from './v228-memory-purge.ts';
import { v229 } from './v229-trust-allow-rules.ts';
import { v230 } from './v230-trust-generation.ts';
import { v231 } from './v231-fact-purge-lookup-indexes.ts';
+import { v232 } from './v232-persistence-git-durability.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -462,4 +463,5 @@ export const MIGRATIONS: Migration[] = [
v229,
v230,
v231,
+ v232,
];
diff --git a/src/core/schema-migrations/v232-persistence-git-durability.ts b/src/core/schema-migrations/v232-persistence-git-durability.ts
new file mode 100644
index 0000000000..5153b752bf
--- /dev/null
+++ b/src/core/schema-migrations/v232-persistence-git-durability.ts
@@ -0,0 +1,26 @@
+import type { Migration } from './types.ts';
+import { PERSISTENCE_GIT_DURABILITY_COLUMN_SQL } from '../persistence/schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #5182 per-host Git-durability opt-in for managed worktrees. The column is
+// nullable with no default, so Postgres adds it as a catalog-only change (no
+// row rewrite, no table scan). The ALTER lives only here and in CREATE TABLE
+// (src/core/persistence/schema.ts), never in the replayed schema blob, so an
+// existing brain takes the lock exactly once. Postgres bounds the wait so a
+// busy writer makes the migration fail fast and retry instead of queueing
+// behind it; PGLite has no concurrent writers and PgBouncer transaction mode
+// sees SET LOCAL inside the migration's own transaction.
+export const v232: Migration = {
+ version: 232,
+ name: 'persistence_git_durability',
+ idempotent: true,
+ sql: PERSISTENCE_GIT_DURABILITY_COLUMN_SQL,
+ sqlFor: { postgres: `SET LOCAL statement_timeout = '30s'; SET LOCAL lock_timeout = '2s';\n ${PERSISTENCE_GIT_DURABILITY_COLUMN_SQL}` },
+ verify: async (engine) => {
+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM information_schema.columns
+ WHERE table_name='persistence_host_bindings' AND column_name='git_durability'`);
+ return Number(rows[0]?.n ?? 0) === 1;
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index 61285eccc9..437449dfa3 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1990,6 +1990,7 @@ CREATE TABLE IF NOT EXISTS persistence_host_bindings (
host_id uuid NOT NULL,
local_path text NOT NULL,
coordination_path text NOT NULL,
+ git_durability text CHECK (git_durability IN ('enabled','disabled')),
PRIMARY KEY(worktree_id,host_id)
);
CREATE TABLE IF NOT EXISTS persistence_local_writers (
diff --git a/test/owner-refusal.test.ts b/test/owner-refusal.test.ts
index 8b10d21fb1..e9b2af2983 100644
--- a/test/owner-refusal.test.ts
+++ b/test/owner-refusal.test.ts
@@ -35,7 +35,7 @@ import { withEnv } from './helpers/with-env.ts';
const OWNER = 'aaaaaaaa-1111-4111-8111-111111111111', LOCAL = 'bbbbbbbb-2222-4222-8222-222222222222';
const INCARNATION = 'cccccccc-3333-4333-8333-333333333333';
const binding = (over: Partial<WorktreeBinding> = {}): WorktreeBinding => ({ worktree_id: randomUUID(), source_id: 'src', source_incarnation: INCARNATION, relative_path: '',
- topology_generation: 1, owner_host_id: LOCAL, owner_epoch: 1, state: 'active', local_path: '/srv/brain', coordination_path: '/srv/brain/.gbrain-coordination', ...over });
+ topology_generation: 1, owner_host_id: LOCAL, owner_epoch: 1, state: 'active', local_path: '/srv/brain', coordination_path: '/srv/brain/.gbrain-coordination', git_durability: null, ...over });
const http: RenderContext = { transport: 'http', surface: 'full', isCallable: () => false, preapproved: () => false, principal: 'client-example' };
describe('the matrix', () => {