Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a gitignored Git target parks at once as git_target_ignored; parked groups with one bulk retry per code
garrytan7289fdfd2199
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex d82125d56e..058d0fed47 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1731,6 +1731,14 @@ More: [docs/guides/shared-checkout-git.md#stuck-rebase](../../docs/guides/shared|---|---|---|---|---|---|---|| The canonical commit is durable locally; its push will retry. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### git_target_ignored++<a id="git_target_ignored"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once. | The request itself was wrong or no longer matches the brain; nothing was changed. | Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked. | agent | `repeat the read that failed` | 1 | no |+### git_target_pending<a id="git_target_pending"></a>diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsindex 62dc692c8a..d81836eeae 100644--- a/src/commands/doctor/checks/parked-effects.ts+++ b/src/commands/doctor/checks/parked-effects.ts@@ -55,7 +55,9 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringfor (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 ? {} : {+ // GBRA-133: a target a .gitignore rule excludes parks again on any retry while the rule stands; its group says what to change first.+ const ignored = row.parked.every(target => target.error_code === 'git_target_ignored');+ effects.push({ request_id: request.request_id, ...row, ...(ignored ? {} : { 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>`@@ -66,7 +68,9 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringconst pushHolds = await (await import('../../../core/persistence/git-push-holds.ts')).readGitPushHolds(engine, sourceIds);// GBRA-133: per source, effects that have waited on a busy worktree for over 10 minutes (a catch-up that does not move).const stalled = await (await import('../../../core/persistence/effect-catchup.ts')).readStalledCatchups(engine, sourceIds);- const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, git_push_holds: pushHolds,+ // GBRA-133: parked Git targets grouped per source and code, each with one bulk command instead of one per request.+ const groups = await (await import('../../../core/persistence/parked-groups.ts')).readParkedGroups(engine, sourceIds);+ const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, parked_groups: groups, git_push_holds: pushHolds,...(stalled.length ? { stalled_catchups: stalled } : {}), ...(reclaims ? { index_lock_reclaims: reclaims } : {}) };const conflicts = pushHolds.filter(hold => hold.conflict);const pushNote = pushHolds.length ? ' Git backups not pushed: ' + pushHolds.map(hold => `${hold.source_id} ${hold.retrying} retrying, ${hold.parked} parked (${hold.codes.join(', ')})${hold.conflict@@ -76,11 +80,12 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringif (!count && (conflicts.length || stalled.length)) return { name: 'parked_effects', status: 'warn', details,message: `No effect is parked yet, but ${conflicts.length ? 'Git backups are held by a conflict between this machine and the remote' : 'a backlog of effects is not moving'}.${pushNote}${stalledNote}` };if (!count) return { name: 'parked_effects', status: 'ok', message: `No Git or withdrawal effect is parked.${pushNote}${reclaims ? reclaimNote(reclaims) : ''}`, details };+ const grouped = groups.map(group => `${group.source_id} ${group.code}: ${group.targets} target(s) in ${group.effects} Git effect(s). ${group.next}`);const listed = effects.map(effect => `${effect.kind} ${effect.source_id}: ${effect.parked.map(target =>- `${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${'exit' in effect ? effect.exit : effect.command}`);+ `${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${'exit' in effect ? effect.exit : effect.command ?? 'change the .gitignore rule first (see its group)'}`);return { name: 'parked_effects', status: 'warn', details,message: `${count} Git, withdrawal or embedding effect(s) have parked targets after repeated failures; their withdrawal, Git backup or vectors are 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(' | ')}` ++ `Inspect \`gbrain sources writer status <source>\`. ${grouped.length ? `Per source and code: ${grouped.join(' | ')}. ` : ''}Per effect, fix the cause, preview with the command shown, then rerun it without --dry-run to authorize one more attempt: ${listed.join(' | ')}` +(count > rows.length ? ` (first ${rows.length} of ${count} shown)` : '') +(effects.some(effect => effect.parked.some(target => target.error_code === 'git_target_pending'))? '. git_target_pending: Git still lists a removed page file in the index; on Windows close the program holding it open (a sync watcher, indexer or antivirus), check with `git -c core.fscache=false status` on the brain host, then run the retry command.' : '') +diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.tsindex 5d676099e2..680427ff09 100644--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@ -21,6 +21,7 @@ export const WRITER_HELP = `Usage:gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--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 retry-effects <source> --parked-pushes [--dry-run] [--json]+ gbrain sources writer retry-effects <source> --parked-code <code> [--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]@@ -98,6 +99,10 @@ retry-effects <source> --parked-pushes does the same without a credential changeattempt per Git effect of the source's worktree parked on a push (git_push_unavailable,push_unconfirmed, integrate_conflict); a push the remote rejected because it moved publishesover the remote without moving the checkout (gbrain sources refresh brings remote files in).+retry-effects <source> --parked-code <code> gives one more attempt to every Git effect of the+source's worktree with a target parked on that code; doctor parked_effects and writer status list+each parked code with its command. A target a .gitignore rule excludes parks at once as+git_target_ignored, naming the rule: change the rule first, or the retry parks it again.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, accept and cancel) are refused with@@ -156,7 +161,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', '--pat-file': 'pat_file',+ '--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id', '--pat-file': 'pat_file', '--parked-code': 'parked_code','--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category',};const arrays = new Set(['source_ids', 'scopes', 'allowed_operations', 'slug_prefixes']);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 58926a7d3d..785b441888 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1218,6 +1218,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.426.0', text: 'With `--job-isolation process`, `--max-rss` now caps each job child too: the worker measures the child\'s process tree (RssAnon + RssShmem) every 5 seconds, and a child past the cap gets SIGTERM, then SIGKILL after the 25-second grace. Its attempt fails with `ChildRssLimitError`, so a job that grows the same way on every retry ends at its `max_attempts`. Before, the cap read only the worker\'s own memory, and a runaway child grew until the host or container limit restarted every process.' },{ since: 'TBD', text: 'On a managed brain, a cycle extract phase with no changed-page list from sync (sync left out of the phases, as for a source with sync disabled, or a sync that failed) now stops its stale-page pass after the cycle\'s 3-minute stale-drain budget instead of running over every stale page of the source. The rest stays stale and drains across later cycles, and the phase reports `stale_backlog`. `gbrain extract` and `gbrain extract --stale --catch-up` still run to the end.' },{ since: 'TBD', text: 'The job stall sweep now deletes a drain-lease holder record (queue `gbrain-drain-lease`) whose lease lock is gone or expired. Such a record is left when the process holding a source\'s drain lease is killed before it releases the lease, and it used to stay `active` until the next sync of that source, shown as a stalled sync job. A live holder\'s record is never touched.' },+ { since: 'TBD', text: 'A Git effect whose target file a .gitignore rule excludes now parks on its first attempt as `git_target_ignored`, naming the rule (`<file>:<line>: <pattern>`), instead of retrying and then parking as `git_target_unsafe`. doctor `parked_effects` and `gbrain sources writer status` (`parked_groups`) group parked Git targets per source and code, each group with one bulk command: `--parked-pushes` for push codes and the new `gbrain sources writer retry-effects <source> --parked-code <code>` otherwise. An ignored target gets no per-request retry suggestion, because a retry parks it again while the rule stands. Nothing already parked changes on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 19cfe5c3e6..99b0916938 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -325,6 +325,7 @@ export const CODES = {git_target_pending: { class: 'retryable', summary: "Git still lists a removed canonical file in the index; the removal was not committed yet." },git_operation_in_progress: { class: 'caller', summary: "A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it.", docs: 'docs/guides/shared-checkout-git.md#stuck-rebase' },git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },+ git_target_ignored: { class: 'caller', summary: "A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once.", suggestion: 'Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked.' },git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 1d6a900b73..e980495e26 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -188,7 +188,14 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioreturn runGitDurabilityAdministration(engine, params);}if (operation === 'writer_retry_effects') {- keys(params, ['source_id', 'request_id', 'dry_run', 'admin_intent', 'expected_state', 'parked_pushes']);+ keys(params, ['source_id', 'request_id', 'dry_run', 'admin_intent', 'expected_state', 'parked_pushes', 'parked_code']);+ if (params.parked_code !== undefined) {+ if (typeof params.parked_code !== 'string' || !/^[a-z][a-z0-9_]*$/.test(params.parked_code) || params.parked_pushes !== undefined || params.request_id !== undefined+ || params.admin_intent !== undefined || params.expected_state !== undefined) throw invalid(+ '--parked-code retries every Git effect of the source parked on one error code; it takes no --request-id, --parked-pushes or admin intent.',+ 'Run gbrain sources writer retry-effects <source> --parked-code <code> [--dry-run]; doctor parked_effects lists each parked code with its command.');+ return (await import('./git-durability-administration.ts')).retrySourceParkedCode(engine, source(params.source_id), params.parked_code, params.dry_run === true);+ }if (params.parked_pushes === true) {if (params.request_id !== undefined || params.admin_intent !== undefined || params.expected_state !== undefined) throw invalid('--parked-pushes retries every parked push of the source; it takes no --request-id or admin intent.',@@ -282,6 +289,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioadmin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,// GBRA-133: effects that have waited on a busy canonical worktree for over 10 minutes.stalled_catchups: await (await import('./effect-catchup.ts')).readStalledCatchups(engine, params.source_id ? [params.source_id as string] : undefined),+ parked_groups: await (await import('./parked-groups.ts')).readParkedGroups(engine, params.source_id ? [params.source_id as string] : undefined),writer_versions: writerVersions, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}),// #6317 (B3): every process holding a consumer on this host, from the heartbeat rows (kind, pid, nonce, mode, age, wedge report).host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex 024ab19fa7..d03f3e51a1 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -62,8 +62,8 @@ export interface GitEffectOwner {interface GitSession { root: string; hooks: string; signal?: AbortSignal; timeoutMs: number; owner?: GitEffectOwner }-function run(session: GitSession, args: string[]) {- return execFileBounded('git', ['--literal-pathspecs', '-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args], {+function run(session: GitSession, args: string[], literal = true) {+ return execFileBounded('git', [...(literal ? ['--literal-pathspecs'] : []), '-C', session.root, '-c', `core.hooksPath=${session.hooks}`, '-c', 'commit.gpgsign=false', ...args], {timeout: session.timeoutMs, termGraceMs: GIT_TERM_GRACE_MS, maxBuffer: 1024 * 1024, signal: session.signal, env: gitChildEnv(GIT_ENV),});}@@ -161,6 +161,7 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{return { path: relativePath, state: 'unchanged' };}if (tracked.code === 0) return { path: relativePath, state: 'unchanged' };+ if (existsSync(path)) await refuseIgnoredTarget(session, relativePath);if (existsSync(path)) throw new OperationError('git_target_unsafe', 'Git cannot identify the existing canonical file by its native spelling.','Reconcile the index and worktree spelling before retrying publication.');let parent = dirname(path);@@ -185,6 +186,22 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{return { path: relativePath, skip: { git: 'skipped', reason: 'target_absent', push: 'skipped' } };}+/**+ * GBRA-133: an existing untracked file a .gitignore rule excludes cannot be committed while the rule stands. It refuses+ * as `git_target_ignored` naming the rule (`detail`), so the effect parks at once with the cause instead of looping.+ */+async function refuseIgnoredTarget(session: GitSession, relativePath: string): Promise<void> {+ const status = await git(session, ['status', '--porcelain', '--ignored=matching', '--untracked-files=all', '--', relativePath]);+ if (status.code !== 0 || !status.stdout.startsWith('!! ')) return;+ // check-ignore takes no literal pathspecs; it only names the rule for the message.+ const matched = await run(session, ['check-ignore', '-v', '--', relativePath], false);+ const rule = matched.error ? '.gitignore' : matched.stdout.split('\t')[0]!.replace(/^(.*?):(\d+):/, '$1:$2: ');+ const error = new OperationError('git_target_ignored', `Git ignores ${relativePath} (${rule}), so its Git effect cannot commit it.`,+ `Either remove or narrow the rule (${rule}) and commit that change, then retry the parked effects with gbrain sources writer retry-effects and --parked-code git_target_ignored for the source this checkout backs (gbrain sources writer status names it); or keep the file out of Git and leave the effect parked. The page itself is committed in the database.`);+ error.detail = rule;+ throw error;+}+/** A git session with an empty hooks directory; `scaled` sizes its step deadline by the checkout's index. */async function withSession<T>(root: string, signal: AbortSignal | undefined, owner: GitEffectOwner | undefined, scaled: boolean,work: (session: GitSession) => Promise<T>): Promise<T> {diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex 846ec0a845..8bc79c6034 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -33,7 +33,8 @@ export function fenceRepairCommit(path: string, classes: readonly string[], tierexport function contentRepairCommit(path: string, receipt: Pick<ContentRepairReceipt, 'tier' | 'confidence'>): GitCommitNote {return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };}-export interface ParkedTarget { slug?: string; error_code: string }+/** `rule`: for `git_target_ignored`, the .gitignore rule that excludes the file (`<file>:<line>: <pattern>`). */+export interface ParkedTarget { slug?: string; error_code: string; rule?: string }/** `page_body_segmented`: a segmented page an older binary's mirror or Git scan passed by; this one mirrors and commits it. *//** `preview_changed`: a `gbrain repair segmented-mirror` target whose file or render no longer has the hash its preview approved (`data.approved_file`). */export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' | 'withdrawal_not_mirrored' | 'preview_changed' }diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 89aa0a1ba3..04f93e470e 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -690,6 +690,8 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, err}const [current] = await engine.executeRaw<{ recovering: boolean }>('SELECT recovery IS NOT NULL AS recovering FROM persistence_effects WHERE id=$1', [effect.id]);if (current?.recovering) { await retryEffect(engine, effect, code, 30_000); return; }+ // GBRA-133: a target a .gitignore rule excludes fails the same way on every attempt; it parks at once, naming the rule.+ if (code === 'git_target_ignored') { await parkEffectTarget(engine, effect, code, target, (error as OperationError).detail); return; }// A retried parked target has exactly one authorized attempt; otherwise the// counter only accumulates while the same target keeps failing.const prior = target !== undefined && effect.data.retry_slugs?.includes(target) ? PARK_AFTER_FAILURES - 1@@ -739,10 +741,10 @@ const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim* or a failure outside any target, parks the whole effect. Parked work stays* retained until `gbrain sources writer retry-effects` authorizes another attempt.*/-async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect, code: string, target: string | undefined): Promise<void> {+async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect, code: string, target: string | undefined, rule?: string): Promise<void> {const { target_failures: _failures, failing_target: _target, retry_slugs: retrying = [], ...data } = effect.data;const scanning = target !== undefined && (targetedWithdrawalEffect(effect) || effect.data.source_scan === true);- const parked = [...(effect.data.parked ?? []), { ...(target ?? effect.data.slug ? { slug: target ?? effect.data.slug } : {}), error_code: code }];+ const parked = [...(effect.data.parked ?? []), { ...(target ?? effect.data.slug ? { slug: target ?? effect.data.slug } : {}), error_code: code, ...(rule ? { rule } : {}) }];if (!scanning) { await parkEffect(engine, effect, { ...data, ...(retrying.length ? { retry_slugs: retrying } : {}), parked }); return; }const remaining = retrying.filter(slug => slug !== target);// An embedding scan's next page starts with a full attempt budget, as when the cursor advances.diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.tsindex a4a94dd63f..1da55f0811 100644--- a/src/core/persistence/git-durability-administration.ts+++ b/src/core/persistence/git-durability-administration.ts@@ -188,13 +188,13 @@ const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_* `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<ParkedPushRetry> {+export async function retryParkedPushes(engine: BrainEngine, worktreeId: string, dryRun: boolean, codes: readonly string[] = GIT_PUSH_CODES): 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 eJOIN 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'=ANY($2::text[]))- ORDER BY e.source_id,request_id,id`, [worktreeId, [...GIT_PUSH_CODES]]);+ ORDER BY e.source_id,request_id,id`, [worktreeId, [...codes]]);let queued = 0, unchanged = 0;const refused: ParkedPushRefusal[] = [];for (const row of rows) {@@ -225,6 +225,17 @@ export async function retrySourceParkedPushes(engine: BrainEngine, sourceId: str...await retryParkedPushes(engine, binding.worktree_id, dryRun) };}+/**+ * GBRA-133: `retry-effects <source> --parked-code <code>`: one more attempt for every Git effect of the source's worktree+ * with a target parked on `code` (for example `git_target_ignored` after its .gitignore rule changed), each through+ * `retryParkedEffects` as `--parked-pushes` does.+ */+export async function retrySourceParkedCode(engine: BrainEngine, sourceId: string, code: string, dryRun: boolean): Promise<Record<string, unknown>> {+ const binding = await ownedBinding(engine, sourceId);+ return { action: 'writer_retry_parked_code', source_id: sourceId, worktree_id: binding.worktree_id, code, dry_run: dryRun,+ ...await retryParkedPushes(engine, binding.worktree_id, dryRun, [code]) };+}+async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<WorktreeBinding & { local_path: string }> {const hostId = existingLocalHostId();const binding = await getWorktreeBinding(engine, sourceId, hostId);diff --git a/src/core/persistence/parked-groups.ts b/src/core/persistence/parked-groups.tsnew file mode 100644index 0000000000..841319527b--- /dev/null+++ b/src/core/persistence/parked-groups.ts@@ -0,0 +1,27 @@+import type { BrainEngine } from '../engine.ts';+import { GIT_PUSH_CODES } from './git-push-holds.ts';++/** GBRA-133: one source's parked Git targets of one error code, with the one command that retries them all. */+export interface ParkedGroup { source_id: string; code: string; effects: number; targets: number; rule?: string; command: string[]; next: string }++/**+ * Parked Git targets per source and error code (doctor `parked_effects`, `sources writer status`). Each group names its+ * bulk retry (`--parked-pushes` for push codes, `--parked-code <code>` otherwise) as a preview. A `git_target_ignored`+ * group names the .gitignore rule and says the rule has to change first: a retry while it stands parks again.+ */+export async function readParkedGroups(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<ParkedGroup[]> {+ const rows = await engine.executeRaw<{ source_id: string; code: string; effects: number; targets: number; rule: string | null }>(+ `SELECT e.source_id, p->>'error_code' AS code, count(DISTINCT e.id)::int AS effects, count(*)::int AS targets, min(p->>'rule') AS rule+ FROM persistence_effects e CROSS JOIN LATERAL jsonb_array_elements(e.data->'parked') p+ WHERE e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND jsonb_typeof(e.data->'parked')='array'+ AND ($1::text[] IS NULL OR e.source_id=ANY($1::text[]))+ GROUP BY 1, 2 ORDER BY 1, 2`, [sourceIds ?? null]);+ return rows.map(({ rule, ...row }) => {+ const push = (GIT_PUSH_CODES as readonly string[]).includes(row.code);+ const command = ['gbrain', 'sources', 'writer', 'retry-effects', row.source_id, ...(push ? ['--parked-pushes'] : ['--parked-code', row.code]), '--dry-run'];+ const next = row.code === 'git_target_ignored'+ ? `Git ignores these files${rule ? ` (${rule})` : ''}, so a retry parks them again while the rule stands. Change the rule and commit it, then preview ${command.join(' ')} and rerun it without --dry-run; or keep the files out of Git and leave them parked (their pages are committed in the database).`+ : `Fix the cause, then preview ${command.join(' ')} and rerun it without --dry-run to authorize one more attempt per target.`;+ return { ...row, ...(rule ? { rule } : {}), command, next };+ });+}diff --git a/test/e2e/w5-persistence-postgres.test.ts b/test/e2e/w5-persistence-postgres.test.tsindex 2e7d58ad90..f00dbffeb7 100644--- a/test/e2e/w5-persistence-postgres.test.ts+++ b/test/e2e/w5-persistence-postgres.test.ts@@ -5,13 +5,14 @@*/import { describe, test } from 'bun:test';import {- capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts, failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark,+ capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts, failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark, ignoredTargetParksAtOnce,managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, managedStaleSweepManyPages, scanParksOneTargetAndContinues, singleTargetParksAndRetries, staleExtractionWithheldWhenItCannotRun,} from '../helpers/w5-scenarios.ts';const url = process.env.DATABASE_URL;describe.skipIf(!url)('Postgres managed capacity, parking and stale extraction', () => {test('a failing Git target parks and retries', () => singleTargetParksAndRetries(url), 180_000);+ test('a gitignored Git target parks at once and retries in bulk', () => ignoredTargetParksAtOnce(url), 180_000);test('a Git scan parks one target and continues', () => scanParksOneTargetAndContinues(url), 180_000);test('failures do not carry to another target', () => failuresDoNotCarryToAnotherTarget(url), 180_000);test('a healthy scan and contention never park', () => healthyScanAndContentionNeverPark(url), 180_000);diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.tsindex d28b2a3ae4..f6b8ec049d 100644--- a/test/helpers/w5-scenarios.ts+++ b/test/helpers/w5-scenarios.ts@@ -5,7 +5,7 @@*/import { expect } from 'bun:test';import { randomUUID } from 'node:crypto';-import { writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';import type { OperationContext } from '../../src/core/ops/contract.ts';@@ -13,6 +13,7 @@ import { submitPageMutation } from '../../src/core/persistence/page-mutations.tsimport { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';import { retryParkedEffects, retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { retrySourceParkedCode } from '../../src/core/persistence/git-durability-administration.ts';import { compactWriteReceipts } from '../../src/core/persistence/journal.ts';import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';import { localHostId } from '../../src/core/persistence/identity.ts';@@ -54,13 +55,22 @@ async function runOnly(engine: BrainEngine, ctx: OperationContext, id: number, tawait runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 1 });}}+const gitRepo = (root: string) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };const ignoredPages = (root: string) => { writeFileSync(join(root, '.gitignore'), 'aa/\n'); durableGitRepo(root, ['.gitignore']); };const unignore = (root: string) => { writeFileSync(join(root, '.gitignore'), '\n'); git(root, 'commit', '-q', '-am', 'Stop ignoring aa/'); };const committed = (root: string) => git(root, 'log', '--name-only', '--pretty=format:');+/** A target Git cannot stage (`git_target_unsafe`, counted toward parking): its page file replaced by a directory. Returns the repair. */+function unstageable(root: string, slug: string): () => void {+ const file = join(root, `${slug}.md`);+ const bytes = readFileSync(file);+ rmSync(file); mkdirSync(file);+ return () => { rmSync(file, { recursive: true }); writeFileSync(file, bytes); };+}export async function singleTargetParksAndRetries(databaseUrl?: string) {await managedBrain(async ({ engine, ctx, root }) => {- await put(ctx, 'aa/page', 'Ignored by Git.');+ await put(ctx, 'aa/page', 'Unstageable by Git.');+ const restore = unstageable(root, 'aa/page');const effect = await gitEffect(engine, 'aa/page');await resetEffect(engine, effect.id, { slug: 'aa/page', page_id: effect.data.page_id, relative_path: effect.data.relative_path, expected_hash: effect.data.expected_hash });await runOnly(engine, ctx, effect.id, 4);@@ -72,11 +82,12 @@ export async function singleTargetParksAndRetries(databaseUrl?: string) {expect((await gitEffect(engine, 'aa/page')).attempts).toBe(5);const doctor = await checkParkedEffects(engine);- expect(doctor).toMatchObject({ status: 'warn', details: { parked_effects: 1, exact: true, truncated: false } });- expect(doctor.message).toContain(`gbrain sources writer retry-effects default --request-id ${effect.request_id} --dry-run`);- expect(doctor.message).toContain('aa/page (git_target_unsafe)');+ expect(doctor).toMatchObject({ status: 'warn', details: { parked_effects: 1, exact: true, truncated: false,+ parked_groups: [{ source_id: 'default', code: 'git_target_unsafe', effects: 1, targets: 1 }] } });+ expect(doctor.message).toContain('default git_target_unsafe: 1 target(s) in 1 Git effect(s)');+ expect(doctor.message).toContain('gbrain sources writer retry-effects default --parked-code git_target_unsafe --dry-run');- unignore(root);+ restore();expect(await retryParkedEffects(engine, 'default', effect.request_id, true)).toMatchObject({ dry_run: true,effects: [{ kind: 'git', parked_targets: 1, state: 'parked', action: 'would_retry' }] });expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'failed', error_code: 'targets_parked' });@@ -94,6 +105,33 @@ export async function singleTargetParksAndRetries(databaseUrl?: string) {expect(await retryRequestEffects(engine, 'default', effect.request_id, true, ctx.config)).toMatchObject({ kind: 'embedding',parked_effects: [{ kind: 'git', state: 'committed', terminal: true }] });expect(await checkParkedEffects(engine)).toMatchObject({ status: 'ok', details: { parked_effects: 0 } });+ }, { databaseUrl, setup: ({ root }) => gitRepo(root) });+}++/** GBRA-133: a target a .gitignore rule excludes parks at once as git_target_ignored, naming the rule, and retries in bulk once the rule changes. */+export async function ignoredTargetParksAtOnce(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx, root }) => {+ await put(ctx, 'aa/page', 'Ignored by Git.');+ const effect = await gitEffect(engine, 'aa/page');+ await resetEffect(engine, effect.id, { slug: 'aa/page', page_id: effect.data.page_id, relative_path: effect.data.relative_path, expected_hash: effect.data.expected_hash });+ await runOnly(engine, ctx, effect.id, 3);+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'failed', error_code: 'targets_parked', attempts: 1,+ data: { parked: [{ slug: 'aa/page', error_code: 'git_target_ignored', rule: '.gitignore:1: aa/' }] } });++ const doctor = await checkParkedEffects(engine);+ expect(doctor.details).toMatchObject({ parked_effects: 1, parked_groups: [{ source_id: 'default', code: 'git_target_ignored', effects: 1, targets: 1,+ rule: '.gitignore:1: aa/', command: ['gbrain', 'sources', 'writer', 'retry-effects', 'default', '--parked-code', 'git_target_ignored', '--dry-run'] }] });+ expect(doctor.message).toContain('Git ignores these files (.gitignore:1: aa/), so a retry parks them again while the rule stands');+ expect(doctor.message).not.toContain('--request-id');++ expect(await retrySourceParkedCode(engine, 'default', 'git_target_ignored', true)).toMatchObject({ code: 'git_target_ignored', dry_run: true, requests: 1, queued: 1, refused: [] });+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'failed', error_code: 'targets_parked' });+ unignore(root);+ expect(await retrySourceParkedCode(engine, 'default', 'git_target_ignored', false)).toMatchObject({ requests: 1, queued: 1, refused: [] });+ await runOnly(engine, ctx, effect.id);+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'committed', error_code: null });+ expect(committed(root)).toContain('aa/page.md');+ expect((await checkParkedEffects(engine)).details).toMatchObject({ parked_effects: 0, parked_groups: [] });}, { databaseUrl, setup: ({ root }) => ignoredPages(root) });}@@ -102,9 +140,9 @@ export async function scanParksOneTargetAndContinues(databaseUrl?: string) {for (const slug of ['aa/page', 'bb', 'cc']) await put(ctx, slug, `Body of ${slug}.`);const scan = await gitEffect(engine, 'bb');await resetEffect(engine, scan.id, { source_scan: true });- await runOnly(engine, ctx, scan.id, 5);+ await runOnly(engine, ctx, scan.id);expect(await gitEffect(engine, 'bb')).toMatchObject({ state: 'queued', data: { after_slug: 'aa/page',- parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });+ parked: [{ slug: 'aa/page', error_code: 'git_target_ignored', rule: '.gitignore:1: aa/' }] } });await runOnly(engine, ctx, scan.id, 3);expect(await gitEffect(engine, 'bb')).toMatchObject({ state: 'failed', error_code: 'targets_parked', data: { after_slug: 'cc' } });expect(committed(root)).toContain('cc.md');@@ -120,19 +158,21 @@ export async function scanParksOneTargetAndContinues(databaseUrl?: string) {}export async function failuresDoNotCarryToAnotherTarget(databaseUrl?: string) {- await managedBrain(async ({ engine, ctx }) => {+ await managedBrain(async ({ engine, ctx, root }) => {for (const slug of ['aa/first', 'aa/second', 'cc']) await put(ctx, slug, `Body of ${slug}.`);+ const [restoreFirst] = ['aa/first', 'aa/second'].map(slug => unstageable(root, slug));const scan = await gitEffect(engine, 'cc');await resetEffect(engine, scan.id, { source_scan: true });await runOnly(engine, ctx, scan.id, 4);expect((await gitEffect(engine, 'cc')).data).toMatchObject({ target_failures: 4, failing_target: 'aa/first' });+ restoreFirst!();const first = (await engine.readPageSnapshot('aa/first', { sourceId: 'default' }))!;await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: 'aa/first', request_id: randomUUID(), expected_revision: first.revision, purge: true } });await runOnly(engine, ctx, scan.id);- expect(await gitEffect(engine, 'cc')).toMatchObject({ state: 'queued', error_code: 'git_target_unsafe',+ expect(await gitEffect(engine, 'cc')).toMatchObject({ state: 'queued', error_code: 'storage_error',data: { target_failures: 1, failing_target: 'aa/second' } });expect((await gitEffect(engine, 'cc')).data.parked).toBeUndefined();- }, { databaseUrl, setup: ({ root }) => ignoredPages(root) });+ }, { databaseUrl, setup: ({ root }) => gitRepo(root) });}export async function healthyScanAndContentionNeverPark(databaseUrl?: string) {diff --git a/test/persistence-effect-parking.test.ts b/test/persistence-effect-parking.test.tsindex 0aeae63c12..3c70175fb7 100644--- a/test/persistence-effect-parking.test.ts+++ b/test/persistence-effect-parking.test.ts@@ -5,9 +5,10 @@* Postgres arm: test/e2e/w5-persistence-postgres.test.ts.*/import { test } from 'bun:test';-import { failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark, scanParksOneTargetAndContinues, singleTargetParksAndRetries } from './helpers/w5-scenarios.ts';+import { failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark, ignoredTargetParksAtOnce, scanParksOneTargetAndContinues, singleTargetParksAndRetries } from './helpers/w5-scenarios.ts';test('a failing Git target parks after five failures and commits after an explicit retry', () => singleTargetParksAndRetries(), 120_000);+test('a gitignored Git target parks at once naming its rule and retries in bulk once the rule changes', () => ignoredTargetParksAtOnce(), 120_000);test('a Git scan parks its failing target, continues, and retries only that target', () => scanParksOneTargetAndContinues(), 120_000);test('a healthy multi-page scan and worktree contention never park', () => healthyScanAndContentionNeverPark(), 120_000);test('failures on a vanished target do not count against the next target', () => failuresDoNotCarryToAnotherTarget(), 120_000);diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.tsindex 0f29a50175..f5b12fd32b 100644--- a/test/persistence-effects.test.ts+++ b/test/persistence-effects.test.ts@@ -164,7 +164,7 @@ test('withdrawal redacts a present db_only cache file and keeps it out of a duraexpect(git(f.root, ['log', '--name-only', '--pretty=format:'])).not.toContain('conversations');});-test('a withdrawal Git scan parks a failing target after five failures and still commits the rest (#5612)', async () => {+test('a withdrawal Git scan parks a gitignored target at once and still commits the rest (#5612, GBRA-133)', async () => {const f = await fixture(body(), 'aa/page');await engine.putPage('page', page(body()), { sourceId: f.sourceId });const later = (await engine.readPageSnapshot('page', { sourceId: f.sourceId }))!;@@ -181,7 +181,7 @@ test('a withdrawal Git scan parks a failing target after five failures and stillawait runPersistenceEffects(engine, config, { hostId, limit: 1 });}expect(await effect()).toMatchObject({ state: 'failed', error_code: 'targets_parked', data: { after_slug: 'page',- parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });+ parked: [{ slug: 'aa/page', error_code: 'git_target_ignored', rule: '.gitignore:1: aa/' }] } });expect(git(f.root, ['log', '-1', '--name-only', '--pretty=format:'])).toBe('page.md');expect(await publicEffectsForRequest(engine, row.id)).toContainEqual({ kind: 'git', state: 'failed', reason: 'targets_parked' });});