Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): bulk parked-push retry finds its requests; revoked writer's Git effects get an owner exit (#6678, #6697)
time-attack40c5879021c8
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 1c2648e82b..96b80a0f3f 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -144,7 +144,19 @@ a receipt can report has a row here.| `core_remote_edit_refused` | `invalid_params` (detail `core_remote_edit_refused`) | `memory.core.remote_edit` is `refuse`, so remote edits to core pages are refused. Nothing was written. | Ask the user to make the edit on the brain host, or to allow remote edits with notices (`gbrain config set memory.core.remote_edit notify`). See [remote edits](core-memory.md#remote-edits). |`gbrain doctor` reports parked targets as the `parked_effects` check with the-exact `retry-effects` command per request. It reports `persistence_capacity`+exact `retry-effects` command per request. When the original writer was revoked,+the preview reports `action: owner_revoked` with `authority: {ok: false, code,+message}` and a `fix` that asks the user first, and doctor names that exit instead+of the retry command: the Git backup of those pages is incomplete. After the user+agrees, the owner host retries a parked Git effect once under the brain owner's+authority with `gbrain sources writer retry-effects <source> --request-id <id>+--admin-intent writer_retry_effects --expected-state <admin_state>`; the effect+records `retried_under: owner_host`. A withdrawal effect is never retried under+another authority. `gbrain sources writer git-durability <source> --pat-file+<path>` retries every parked push of the worktree after wiring the credential;+a request refused on its own (revoked writer, replaced source, live claim) is+listed in `parked_pushes.refused` with its fix, the result has `status: partial`,+and the command exits 1. It reports `persistence_capacity`when lifetime request IDs or receipt bytes reach 80% of a limit, with the`gbrain config set` value to use; outstanding-request, queued-byte andrecovery-byte limits can refuse writes without that warning.diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsindex 986b9ba478..abd88b784c 100644--- a/src/commands/doctor/checks/parked-effects.ts+++ b/src/commands/doctor/checks/parked-effects.ts@@ -1,6 +1,20 @@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import type { ParkedTarget } from '../../../core/persistence/effect-model.ts';+import type { WriteRequest } from '../../../core/persistence/model.ts';+import { OperationError } from '../../../core/ops/contract.ts';+import { authorizeStoredRequest } from '../../../core/persistence/authority.ts';++/** #6697: the stored authority's refusal message, or null while the original writer may still act. */+async function revokedAuthority(engine: BrainEngine, request: WriteRequest): Promise<string | null> {+ try {+ await authorizeStoredRequest(engine, request);+ return null;+ } catch (error) {+ if (error instanceof OperationError) return error.code === 'permission_denied' ? error.message : null;+ throw error;+ }+}const SAMPLE = 20;@@ -14,14 +28,23 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringconst scoped = sourceIds ? ' AND e.source_id=ANY($1::text[])' : '';const params = sourceIds ? [sourceIds] : [];const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects e WHERE e.data ? 'parked'${scoped}`, params);- const rows = await engine.executeRaw<{ request_id: string; source_id: string; kind: string; state: string; parked: ParkedTarget[] }>(- `SELECT r.request_id::text AS request_id,e.source_id,e.kind,e.state,e.data->'parked' AS parked FROM persistence_effects e+ const rows = await engine.executeRaw<{ request: WriteRequest; source_id: string; kind: string; state: string; parked: ParkedTarget[] }>(+ `SELECT to_jsonb(r) AS request,e.source_id,e.kind,e.state,e.data->'parked' AS parked FROM persistence_effects eJOIN persistence_requests r ON r.id=e.request_id WHERE e.data ? 'parked'${scoped} ORDER BY e.id LIMIT ${SAMPLE}`, params);- const effects = rows.map(row => ({ ...row, command: `gbrain sources writer retry-effects ${row.source_id} --request-id ${row.request_id} --dry-run` }));+ const effects = [];+ for (const { request, ...row } of rows) {+ const preview = `gbrain sources writer retry-effects ${row.source_id} --request-id ${request.request_id} --dry-run`;+ const revoked = await revokedAuthority(engine, request);+ effects.push({ request_id: request.request_id, ...row, command: preview, ...(revoked === null ? {} : {+ owner_revoked: revoked,+ exit: row.kind === 'git'+ ? `the original writer is revoked; ask the user, then retry once under the brain owner's authority: gbrain sources writer retry-effects ${row.source_id} --request-id ${request.request_id} --admin-intent writer_retry_effects --expected-state <admin_state from gbrain sources writer status>`+ : 'the original writer is revoked and a withdrawal is never retried under another authority; ask the user how to withdraw the page' }) });+ }const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects };if (!count) return { name: 'parked_effects', status: 'ok', message: 'No Git or withdrawal effect is parked.', details };const listed = effects.map(effect => `${effect.kind} ${effect.source_id}: ${effect.parked.map(target =>- `${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${effect.command}`);+ `${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${'exit' in effect ? effect.exit : effect.command}`);return { name: 'parked_effects', status: 'warn', details,message: `${count} Git or withdrawal effect(s) have parked targets after five consecutive failures; their withdrawal or Git backup is incomplete. ` +`Inspect \`gbrain sources writer status <source>\`, fix the cause, preview with the command shown, then rerun it without --dry-run to authorize one more attempt: ${listed.join(' | ')}` +diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.tsindex dc1696183f..1769f32ee1 100644--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@ -19,7 +19,7 @@ export const WRITER_HELP = `Usage:gbrain sources writer failures <source> [--state all] [--group-by category] [--since 7d] [--limit 20] [--before <cursor>][--category <c>] [--code <c>] [--origin <o>|none] [--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 retry-effects <source> --request-id <uuid> [--admin-intent writer_retry_effects --expected-state <admin_state>] [--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]@@ -82,7 +82,13 @@ previews parked targets with --dry-run and otherwise authorizes one more attemptper parked target (a target that fails again parks again). For embeddings itreconciles existing complete vectors or authorizes one additional bounded retrycycle per request; repeating it never renews that allowance. --dry-run never queues work.-It never changes ownership or activation and needs no topology admin-intent.+It never changes ownership or activation and needs no topology admin-intent, except+when the original writer was revoked: --dry-run then reports action owner_revoked,+and --admin-intent writer_retry_effects with the reviewed --expected-state lets the+owner host retry the parked Git effect once under its own authority (recorded as+retried_under: owner_host); a withdrawal effect is never retried that way.+git-durability --pat-file retries every parked push of the worktree; requests refused+on their own are listed in parked_pushes.refused, the result is status partial, and it exits 1.lock sets an opt-in, brain-level writer admin lock (config key persistence.writer_admin_lock)and unlock clears it; both are local-only, idempotent and print the resulting state.While locked, writer claim, activate and transfer (prepare and accept) are refused with@@ -244,6 +250,8 @@ export async function runPersistenceAdminCli(group: Group, args: string[], connereturn;}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);} catch (error) {if (!await reportPersistenceCliError(error, args.includes('--json'))) {console.error(error instanceof Error ? error.message : String(error));diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 7b8952531b..17afb8b818 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -188,13 +188,16 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioreturn runGitDurabilityAdministration(engine, params);}if (operation === 'writer_retry_effects') {- keys(params, ['source_id', 'request_id', 'dry_run']);+ keys(params, ['source_id', 'request_id', 'dry_run', 'admin_intent', 'expected_state']);if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.','Pass --request-id with the original write\'s request id (a UUID); gbrain sources writer status for that source lists blocked effects with their request ids.',typeof params.source_id === 'string' && isValidSourceId(params.source_id)? readFix(`Lists source ${params.source_id}'s blocked effects with their request ids, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', params.source_id, '--json'] }): undefined);- return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy);+ // #6697 (D6): the admin-intent handshake is the owner's approval to retry a revoked writer's parked Git effect under owner authority.+ const ownerHost = params.admin_intent !== undefined || params.expected_state !== undefined;+ if (ownerHost) await requireWriterAdminIntent(engine, 'writer_retry_effects', params);+ return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy, ownerHost);}if (operation === 'source_add' || operation === 'source_lifecycle') {const { managedPersistenceEnabled } = await import('./ownership.ts');diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.tsindex 67c8e93f29..f28ef400af 100644--- a/src/core/persistence/effect-retry.ts+++ b/src/core/persistence/effect-retry.ts@@ -15,6 +15,7 @@ import { PARK_AFTER_FAILURES, type PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';import { declarePersistenceProtocol } from './protocol.ts';+import { writerAdminState } from './admin-intent.ts';const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its blocking, retrying and parked effects, read-only.`,{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });@@ -58,13 +59,59 @@ async function mountedEmbeddingSignature(engine: BrainEngine): Promise<string> {return `${model}:${dimensions}`;}+/** The refusal fields a caller reports for one request: the same envelope whether it was previewed or thrown. */+export function refusalEnvelope(error: OperationError): { code: string; message: string; suggestion?: string; fix?: Action } {+ return { code: error.code, message: error.message, ...(error.suggestion ? { suggestion: error.suggestion } : {}), ...(error.fix ? { fix: error.fix } : {}) };+}++/** #6697: the stored authority's refusal, or null while the original writer may still act. */+async function storedAuthorityRefusal(tx: BrainEngine, request: WriteRequest, sourceId: string): Promise<OperationError | null> {+ try {+ await authorizeStoredRequest(tx, request, true);+ const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,+ request.operation, sourceId, request.source_incarnation, request.slug);+ await authorizeWrite(tx, authority, request.operation, request.slug, true);+ return null;+ } catch (error) {+ if (error instanceof OperationError && error.code === 'permission_denied') return error;+ throw error;+ }+}++/**+ * #6697 / D6: a parked effect whose original writer was revoked. A Git effect+ * mirrors content already committed under valid authority, so the brain owner+ * may approve one more attempt under its own authority; a withdrawal effect+ * keeps the strict original-authority rule and has no supported retry.+ */+async function ownerRevokedError(tx: BrainEngine, sourceId: string, request: WriteRequest, refusal: OperationError, gitParked: boolean): Promise<OperationError> {+ const why = `Request ${request.request_id}'s original writer is no longer authorized (${refusal.message}), so its parked effect cannot retry under that writer and the Git backup of ${request.slug} is incomplete.`;+ const fix: Action = gitParked+ ? { ask_user: true, argv: ['gbrain', 'sources', 'writer', 'retry-effects', '--source', sourceId, '--request-id', request.request_id,+ '--admin-intent', 'writer_retry_effects', '--expected-state', await writerAdminState(tx)], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Retries the parked Git effect once under this brain owner\'s authority on the owner host; the effect records retried_under: owner_host.',+ user_message: `${why} Approve one more Git attempt for ${request.slug} under this brain owner's authority? It mirrors content the database already committed.`,+ verify: { argv: ['gbrain', 'sources', 'writer', 'retry-effects', '--source', sourceId, '--request-id', request.request_id, '--dry-run', '--json'] } }+ : { ask_user: true, consent: [], actor: 'user', requires_exclusive: false, why: 'A withdrawal effect runs only under its original writer\'s authority.',+ user_message: `${why} A withdrawal is never retried under another authority, so this parked withdrawal has no supported retry; decide with the brain owner how to withdraw ${request.slug}.`,+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] } };+ return opError('permission_denied', why, gitParked+ ? 'Ask the user before retrying under the brain owner\'s authority: run the command in fix on the owner host after they agree.'+ : 'Relay fix.user_message; nothing can retry this withdrawal under another authority.', { fix });+}+/*** #5612: parked Git and withdrawal effects of one committed request. Returns* null when the request has none, so the caller falls through to embedding* retry. Each invocation authorizes exactly one more attempt per parked target.+ * `internalId` selects one journal row when several principals share the public+ * receipt id; `ownerHost` is the owner's admin-intent approval for #6697 (D6).*/-export async function retryParkedEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean): Promise<Record<string, unknown> | null> {- const [request, ambiguous] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid LIMIT 2', [sourceId, requestId]);+export async function retryParkedEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean,+ options: { internalId?: string; ownerHost?: boolean } = {}): Promise<Record<string, unknown> | null> {+ const [request, ambiguous] = options.internalId+ ? await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND id=$2::uuid', [sourceId, options.internalId])+ : await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid LIMIT 2', [sourceId, requestId]);if (!request || ambiguous) return null;const tracked = await engine.executeRaw<PersistenceEffect>(`SELECT * FROM persistence_effects WHERE request_id=$1::uuidAND kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried') ORDER BY kind`, [request.id]);@@ -72,10 +119,9 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,const hostId = existingLocalHostId();if (!hostId) throw unregisteredHost(sourceId, requestId);return engine.transaction(async tx => {- await authorizeStoredRequest(tx, request, true);- const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,- request.operation, sourceId, request.source_incarnation, request.slug);- await authorizeWrite(tx, authority, request.operation, request.slug, true);+ const refusal = await storedAuthorityRefusal(tx, request, sourceId);+ const denied = refusal ? await ownerRevokedError(tx, sourceId, request, refusal,+ tracked.some(effect => effect.kind === 'git' && effect.state === 'failed' && effect.error_code === 'targets_parked')) : null;const effects = [];for (const selected of tracked) {await guardEffectSource(tx, selected, hostId);@@ -89,7 +135,14 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,if (effect.execution_token !== null || effect.recovery) throw opError('write_claim_lost', 'A parked effect still has a claim or recovery record; inspect it before retrying.',`The ${effect.kind} effect of request ${requestId} in source ${sourceId} is still claimed by a worker or holds a recovery record, so nothing was queued. Inspect the owner's effects; once the worker releases it, preview it again with --dry-run.`,{ fix: ownerStatusFix(sourceId) });- if (dryRun) { effects.push({ ...summary, state: 'parked', terminal: true, action: 'would_retry' }); continue; }+ const underOwner = denied !== null && options.ownerHost === true && effect.kind === 'git';+ if (denied && !underOwner) {+ if (!dryRun && !options.ownerHost) throw denied;+ effects.push({ ...summary, state: 'parked', terminal: true, action: 'owner_revoked' });+ continue;+ }+ const retriedUnder = underOwner ? { retried_under: 'owner_host' } : {};+ if (dryRun) { effects.push({ ...summary, state: 'parked', terminal: true, action: 'would_retry', ...retriedUnder }); continue; }const { parked: _parked, retry_slugs: retrying = [], failing_target: _target, ...data } = effect.data;const scanning = targetedWithdrawalEffect(effect) || effect.data.source_scan === true;const slugs = scanning ? [...new Set([...retrying, ...parked.flatMap(entry => entry.slug ? [entry.slug] : [])])] : [];@@ -98,17 +151,22 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,AND execution_token IS NULL AND recovery IS NULL RETURNING state`,[effect.id, JSON.stringify({ ...data, ...(slugs.length ? { retry_slugs: slugs } : {}), target_failures: PARK_AFTER_FAILURES - 1,...(!scanning && (effect.data.slug ?? effect.data.relative_path) ? { failing_target: effect.data.slug ?? effect.data.relative_path } : {}),+ ...(underOwner ? { retried_under: 'owner_host', retried_by_host: hostId } : {}),retried: (effect.data.retried ?? 0) + 1 })]);if (!updated) throw opError('write_claim_lost', 'The parked effect changed during retry approval.',`The ${effect.kind} effect of request ${requestId} changed (claimed, retried or settled by the worker) while this approval ran, so the transaction rolled back and nothing was queued. Preview its current state before deciding again.`,{ fix: previewFix(sourceId, requestId) });- effects.push({ ...summary, state: 'queued', terminal: false, action: 'retry_queued' });+ effects.push({ ...summary, state: 'queued', terminal: false, action: 'retry_queued', ...retriedUnder });}const queued = effects.some(effect => effect.action === 'retry_queued');+ const revoked = denied !== null && effects.some(effect => effect.action === 'owner_revoked');return { request_id: request.request_id, source_id: sourceId, dry_run: dryRun, effects,- next_action: dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target.'- : queued ? 'The resident owner makes one more attempt per parked target. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'- : 'No parked target remains for this request.' };+ ...(denied ? { authority: { ok: false, code: refusal!.code, message: refusal!.message } } : {}),+ ...(revoked ? { action: 'owner_revoked', refusal: refusalEnvelope(denied!), fix: denied!.fix } : {}),+ next_action: revoked && !queued ? denied!.suggestion+ : dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target.'+ : queued ? 'The resident owner makes one more attempt per parked target. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'+ : 'No parked target remains for this request.' };});}@@ -118,8 +176,8 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,* history reported alongside (or alone when the request has no retryable embedding).*/export async function retryRequestEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean, baseConfig?: GBrainConfig,- policy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {- const parked = await retryParkedEffects(engine, sourceId, requestId, dryRun);+ policy: 'owner' | 'mounted_database' = 'owner', ownerHost = false): Promise<Record<string, unknown>> {+ const parked = await retryParkedEffects(engine, sourceId, requestId, dryRun, { ownerHost });if (parked && (parked.effects as Array<{ state: string }>).some(effect => effect.state !== 'committed')) return parked;try {const embedding = await retryEmbeddingEffect(engine, sourceId, requestId, dryRun, baseConfig, policy);diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.tsindex 9281db63df..a43dabbf6b 100644--- a/src/core/persistence/git-durability-administration.ts+++ b/src/core/persistence/git-durability-administration.ts@@ -22,7 +22,7 @@ import { classifyGitCheckout } from '../git-checkout.ts';import { durableSsrfFlags, GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS } from '../git-remote.ts';import { gitChildEnv } from '../git-env.ts';import { ensureGbrainHome, resolveGbrainHome } from '../gbrain-home.ts';-import { opError } from '../ops/contract.ts';+import { OperationError, 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';@@ -30,7 +30,7 @@ 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';+import { refusalEnvelope, 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;@@ -162,25 +162,45 @@ export async function wireDurabilityCredential(root: string, remote: string | nureturn { status: 'fixed', detail: `wired a repo-scoped credential for ${host} (store 0600; replaces an earlier token for that host)` };}+export type ParkedPushRefusal = { source_id: string; request_id: string; code: string; message: string; suggestion?: string; fix?: Action };+export type ParkedPushRetry = { status: 'ok' | 'partial'; requests: number; queued: number; unchanged: number; refused: ParkedPushRefusal[] };+const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_claim_lost']);+/*** #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+ * each journal row goes through `retryParkedEffects`, so the original write's* authority is re-checked and a claimed or settled effect is left alone.+ * #6678: effects reference the internal journal id, so the public receipt id is+ * joined for the report and the row is selected by its internal id. A request+ * refused on its own (revoked writer, replaced source, live claim) is listed in+ * `refused` with the same envelope in preview and apply, and the run is `partial`;+ * a host or binding problem (`owner_unavailable`) still stops the whole run.*/-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+export async function retryParkedPushes(engine: BrainEngine, worktreeId: string, dryRun: boolean): Promise<ParkedPushRetry> {+ const rows = await engine.executeRaw<{ source_id: string; id: string; request_id: string }>(`+ SELECT DISTINCT e.source_id,r.id::text AS id,r.request_id::text AS request_id FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_idWHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND e.recovery IS NULLAND 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]);+ ORDER BY e.source_id,request_id,id`, [worktreeId]);let queued = 0, unchanged = 0;+ const refused: ParkedPushRefusal[] = [];for (const row of rows) {- const result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun);+ const target = { source_id: row.source_id, request_id: row.request_id };+ let result: Record<string, unknown> | null;+ try {+ result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id });+ } catch (error) {+ if (!(error instanceof OperationError) || !REQUEST_REFUSALS.has(error.code)) throw error;+ refused.push({ ...target, ...refusalEnvelope(error) });+ continue;+ }+ if (result?.action === 'owner_revoked') { refused.push({ ...target, ...(result.refusal as ReturnType<typeof refusalEnvelope>) }); continue; }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 };+ return { status: refused.length ? 'partial' : 'ok', requests: rows.length, queued, unchanged, refused };}async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<WorktreeBinding & { local_path: string }> {@@ -223,7 +243,9 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, paramsif (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);+ const parked = await retryParkedPushes(engine, binding.worktree_id, input.dryRun);+ report.parked_pushes = parked;+ report.status = parked.status;}if (target === 'enabled' && checkout) {const probe = await probeDurabilityPush(root, checkout, redact);@@ -264,5 +286,6 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, paramsreturn { ...report, applied: true, queued_catch_up: queued.length, fix: statusFix(input.sourceId),why: 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.`: 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.` };+ : `The push credential was re-wired; ${report.parked_pushes ? (report.parked_pushes as ParkedPushRetry).queued : 0} parked push(es) got one more attempt${+ report.status === 'partial' ? `; ${(report.parked_pushes as ParkedPushRetry).refused.length} request(s) were refused on their own and are listed in parked_pushes.refused with their fix (exit 1)` : ''}.` };}diff --git a/test/parked-push-retry-6678.test.ts b/test/parked-push-retry-6678.test.tsnew file mode 100644index 0000000000..1689215065--- /dev/null+++ b/test/parked-push-retry-6678.test.ts@@ -0,0 +1,248 @@+/**+ * #6678: `git-durability --pat-file` retries every parked push of the worktree.+ * Effects reference the internal journal id; the bulk retry joins the public+ * receipt id, selects each journal row by its internal id (two principals may+ * share one receipt id), and reports a request refused on its own in `refused`+ * with the same envelope in preview and apply (status `partial`).+ * #6697 (D6 option A): a revoked writer's parked Git effect previews as+ * `owner_revoked` instead of throwing, and the owner host may retry it once under+ * its own authority with the admin-intent handshake (`retried_under: owner_host`).+ * Withdrawal effects keep the strict original-authority rule.+ * Based on PR #6683 by @javieraldape.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.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 { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { retryParkedPushes } from '../src/core/persistence/git-durability-administration.ts';+import { retryParkedEffects } from '../src/core/persistence/effect-retry.ts';+import { checkParkedEffects } from '../src/commands/doctor/checks/parked-effects.ts';+import { gitAsync } from './helpers/git-publication.ts';+import { withEnv } from './helpers/with-env.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';++let engine: PGLiteEngine;+const roots: string[] = [];+const config = { engine: 'pglite' as const, embedding_disabled: true };+const page = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body.trim(), timeline: '', frontmatter: {} });+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); for (const root of roots) rmSync(root, { recursive: true, force: true }); });++async function isolated<T>(run: (home: string) => Promise<T>): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-parked-push-')); roots.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); }+}++async function gitRoot(home: string): Promise<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]');+ writeFileSync(join(root, 'initial.md'), 'Initial\n');+ await gitAsync(root, 'add', 'initial.md'); await gitAsync(root, 'commit', '-q', '-m', 'Initial');+ return root;+}++async function claimedSource(root: string) {+ const sourceId = `parked-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const binding = await claimWorktree(engine, sourceId, root, localHostId());+ return { sourceId, binding };+}++/** A committed page write whose Git effect is queued (the persistence-effects fixture, minus the hook). */+async function committedWrite(root: string, sourceId: string, slug: string, opts: { requestId?: string; remote?: boolean } = {}) {+ const binding = (await getWorktreeBinding(engine, sourceId, localHostId()))!;+ await engine.putPage(slug, page('Before'), { sourceId });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ const ctx: OperationContext = { engine, config, remote: opts.remote === true, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: binding.source_incarnation, slug, pageId: snapshot.page.id, requestId: opts.requestId ?? randomUUID(),+ callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const row = (await claimNextWrite(engine, localHostId()))!;+ expect(row.id).toBe(admitted.id);+ const result = await publishMutation(engine, row, { observedRevision: snapshot.revision, file: { path: file, root, content: 'After' },+ apply: async tx => { await tx.putPage(slug, page('After'), { sourceId }); return {}; } }, localHostId());+ expect(result.state).toBe('committed');+ return row.id;+}+async function gitOutcome(requestId: string) {+ const [row] = await engine.executeRaw<{ state: string; outcome: Record<string, unknown> | null; data: Record<string, unknown> }>(+ "SELECT state,outcome,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [requestId]);+ return row;+}+async function runEffects() {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git'");+ await runPersistenceEffects(engine, config, { hostId: localHostId(), limit: 10 });+}+async function parked(root: string, sourceId: string, slug: string, opts: { requestId?: string; remote?: boolean } = {}, code = 'git_push_unavailable') {+ const id = await committedWrite(root, sourceId, slug, opts);+ await engine.executeRaw(`UPDATE persistence_effects SET state='failed',error_code='targets_parked',+ data=data || $2::text::jsonb WHERE request_id=$1::uuid AND kind='git'`,+ [id, JSON.stringify({ parked: [{ slug, error_code: code }], target_failures: 5 })]);+ return id;+}+async function publicId(id: string): Promise<string> {+ const [request] = await engine.executeRaw<{ request_id: string }>('SELECT request_id::text AS request_id FROM persistence_requests WHERE id=$1::uuid', [id]);+ return request.request_id;+}+async function revoke(id: string) {+ await engine.executeRaw(`UPDATE persistence_local_writers SET revoked_at=now()+ WHERE id=(SELECT principal_id::uuid FROM persistence_requests WHERE id=$1::uuid)`, [id]);+}++describe('#6678 credential repair retries parked Git pushes', () => {+ test('preview leaves effects parked, apply queues one retry, and other worktrees and causes stay untouched', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId, binding } = await claimedSource(root);+ const id = await parked(root, sourceId, 'push');+ expect(await publicId(id)).not.toBe(id);+ const otherCause = await parked(root, sourceId, 'ignored', {}, 'git_target_unsafe');+ const otherRoot = await gitRoot(home);+ const other = await claimedSource(otherRoot);+ const otherId = await parked(otherRoot, other.sourceId, 'foreign');+ const clean = { status: 'ok' as const, requests: 1, queued: 1, unchanged: 0, refused: [] };+ expect(await retryParkedPushes(engine, binding.worktree_id, true)).toEqual(clean);+ expect(await gitOutcome(id)).toMatchObject({ state: 'failed', data: { parked: [{ error_code: 'git_push_unavailable' }] } });+ expect(await retryParkedPushes(engine, binding.worktree_id, false)).toEqual(clean);+ expect(await gitOutcome(id)).toMatchObject({ state: 'queued', data: { retried: 1, target_failures: 4 } });+ expect((await gitOutcome(id)).data.parked).toBeUndefined();+ expect(await retryParkedPushes(engine, binding.worktree_id, false)).toEqual({ status: 'ok', requests: 0, queued: 0, unchanged: 0, refused: [] });+ for (const untouched of [otherCause, otherId]) expect(await gitOutcome(untouched)).toMatchObject({ state: 'failed' });+ await engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled' WHERE worktree_id=$1::uuid", [binding.worktree_id]);+ await runEffects();+ expect(await gitOutcome(id)).toMatchObject({ state: 'committed', outcome: { git: 'committed' } });+ expect((await gitAsync(root, 'status', '--porcelain', '--', 'push.md')).trim()).toBe('');+ }), 120_000);++ test('distinct principals sharing one receipt ID both retry, while public-ID retry remains ambiguous', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId, binding } = await claimedSource(root);+ const requestId = randomUUID();+ const first = await parked(root, sourceId, 'cli', { requestId });+ await registerLocalWriter(engine, 'stdio');+ const second = await parked(root, sourceId, 'stdio', { requestId, remote: true });+ expect(first).not.toBe(second);+ expect(await retryParkedEffects(engine, sourceId, requestId, false)).toBeNull();+ expect(await retryParkedPushes(engine, binding.worktree_id, true)).toEqual({ status: 'ok', requests: 2, queued: 2, unchanged: 0, refused: [] });+ for (const id of [first, second]) expect(await gitOutcome(id)).toMatchObject({ state: 'failed' });+ expect(await retryParkedPushes(engine, binding.worktree_id, false)).toEqual({ status: 'ok', requests: 2, queued: 2, unchanged: 0, refused: [] });+ for (const id of [first, second]) expect(await gitOutcome(id)).toMatchObject({ state: 'queued', data: { retried: 1 } });+ }), 120_000);++ test('a revoked writer is refused on its own: the healthy push is queued, preview and apply list the same refusal, status partial', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId, binding } = await claimedSource(root);+ const revoked = await parked(root, sourceId, 'revoked');+ await registerLocalWriter(engine, 'cli', undefined, true);+ const healthy = await parked(root, sourceId, 'healthy');+ await revoke(revoked);+ const preview = await retryParkedPushes(engine, binding.worktree_id, true);+ expect(preview).toMatchObject({ status: 'partial', requests: 2, queued: 1, unchanged: 0 });+ expect(preview.refused).toEqual([expect.objectContaining({ source_id: sourceId, request_id: await publicId(revoked), code: 'permission_denied',+ message: expect.stringContaining('Git backup of revoked is incomplete'), fix: expect.objectContaining({ ask_user: true, user_message: expect.stringContaining('Git backup') }) })]);+ expect(preview.refused[0].fix!.argv).toEqual(expect.arrayContaining(['retry-effects', '--admin-intent', 'writer_retry_effects', '--expected-state']));+ const applied = await retryParkedPushes(engine, binding.worktree_id, false);+ expect(applied).toMatchObject({ status: 'partial', requests: 2, queued: 1, unchanged: 0 });+ expect(applied.refused).toEqual(preview.refused);+ expect(await gitOutcome(revoked)).toMatchObject({ state: 'failed', data: { target_failures: 5 } });+ expect(await gitOutcome(healthy)).toMatchObject({ state: 'queued', data: { retried: 1 } });+ }), 120_000);++ test('a foreign owner still stops the whole bulk retry without changing the parked effect', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId, binding } = await claimedSource(root);+ const id = await parked(root, sourceId, 'owner');+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [binding.worktree_id, randomUUID()]);+ await expect(retryParkedPushes(engine, binding.worktree_id, false)).rejects.toMatchObject({ code: 'owner_unavailable' });+ expect(await gitOutcome(id)).toMatchObject({ state: 'failed' });+ }), 120_000);+});++describe('#6697 revoked writer: parked Git effect', () => {+ test('the dry-run preview reports owner_revoked instead of throwing, and plain apply is refused', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId } = await claimedSource(root);+ const id = await parked(root, sourceId, 'revoked6697');+ const requestId = await publicId(id);+ await revoke(id);+ const preview = await retryParkedEffects(engine, sourceId, requestId, true);+ expect(preview).toMatchObject({ action: 'owner_revoked', authority: { ok: false, code: 'permission_denied' },+ effects: [{ kind: 'git', action: 'owner_revoked', state: 'parked' }], fix: { ask_user: true } });+ expect((preview!.fix as { user_message: string }).user_message).toContain('Git backup of revoked6697 is incomplete');+ await expect(runPersistenceAdministration(engine, 'writer_retry_effects', { source_id: sourceId, request_id: requestId }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ expect(await gitOutcome(id)).toMatchObject({ state: 'failed', data: { target_failures: 5 } });+ }), 120_000);++ test('the owner host retries it once under owner authority with the admin-intent handshake', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId } = await claimedSource(root);+ const id = await parked(root, sourceId, 'owned6697');+ const requestId = await publicId(id);+ await revoke(id);+ await registerLocalWriter(engine, 'cli', undefined, true);+ await expect(runPersistenceAdministration(engine, 'writer_retry_effects', { source_id: sourceId, request_id: requestId, admin_intent: 'writer_retry_effects', expected_state: 'f'.repeat(64) }))+ .rejects.toMatchObject({ code: 'writer_admin_state_changed' });+ const preview = await runPersistenceAdministration(engine, 'writer_retry_effects', { source_id: sourceId, request_id: requestId, dry_run: true, admin_intent: 'writer_retry_effects' });+ expect(preview).toMatchObject({ effects: [{ action: 'would_retry', retried_under: 'owner_host' }] });+ expect(await gitOutcome(id)).toMatchObject({ state: 'failed' });+ const applied = await runPersistenceAdministration(engine, 'writer_retry_effects',+ { source_id: sourceId, request_id: requestId, ...await reviewedWriterIntent(engine, 'writer_retry_effects') });+ expect(applied).toMatchObject({ effects: [{ action: 'retry_queued', retried_under: 'owner_host' }] });+ expect(await gitOutcome(id)).toMatchObject({ state: 'queued', data: { retried: 1, retried_under: 'owner_host', retried_by_host: localHostId() } });+ }), 120_000);++ test('a withdrawal effect of a revoked writer keeps the strict rule even under owner approval', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId } = await claimedSource(root);+ const id = await parked(root, sourceId, 'withdrawn6697');+ const requestId = await publicId(id);+ await engine.executeRaw("UPDATE persistence_effects SET kind='withdrawal-mirror' WHERE request_id=$1::uuid AND kind='git'", [id]);+ await revoke(id);+ await registerLocalWriter(engine, 'cli', undefined, true);+ const applied = await runPersistenceAdministration(engine, 'writer_retry_effects',+ { source_id: sourceId, request_id: requestId, ...await reviewedWriterIntent(engine, 'writer_retry_effects') });+ expect(applied).toMatchObject({ action: 'owner_revoked', effects: [{ kind: 'withdrawal-mirror', action: 'owner_revoked' }], fix: { ask_user: true } });+ expect((applied.fix as { argv?: string[] }).argv).toBeUndefined();+ const [effect] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [id]);+ expect(effect.state).toBe('failed');+ }), 120_000);++ test('doctor names the owner-authority exit for a revoked writer instead of the bare retry command', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId } = await claimedSource(root);+ const revoked = await parked(root, sourceId, 'doctor-revoked');+ await registerLocalWriter(engine, 'cli', undefined, true);+ const healthy = await parked(root, sourceId, 'doctor-healthy');+ await revoke(revoked);+ const check = await checkParkedEffects(engine, [sourceId]);+ const effects = (check.details as { effects: Array<Record<string, unknown>> }).effects;+ const byRequest = Object.fromEntries(effects.map(effect => [effect.request_id as string, effect]));+ expect(byRequest[await publicId(revoked)]).toMatchObject({ owner_revoked: expect.any(String), exit: expect.stringContaining('--admin-intent writer_retry_effects') });+ expect(byRequest[await publicId(healthy)].exit).toBeUndefined();+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`doctor-revoked (git_push_unavailable); the original writer is revoked`);+ expect(check.message).toContain(`doctor-healthy (git_push_unavailable); gbrain sources writer retry-effects ${sourceId} --request-id ${await publicId(healthy)} --dry-run`);+ }), 120_000);+});