Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): commit a tracked, absent Git target as a removal without trusting status (#6665)

time-attack0e8b2e852e99
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 477ccaf0e6..0332dec217 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1304,6 +1304,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_pending
+
+<a id="git_target_pending"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Git still lists a removed canonical file in the index; the removal was not committed yet. | 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_unsafe
<a id="git_target_unsafe"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 96b80a0f3f..e1039bc675 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -75,7 +75,7 @@ of making a duplicate.
| <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A connector on v0.60.11.0 or later sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |
| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Classic mode: write the file, commit, `gbrain sync --source <source>` (a remote agent asks the user to). Otherwise bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. Not retryable. See [unbound sources on Postgres](#unbound-sources-on-postgres). |
| <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. |
-| `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). Remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |
+| `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). Remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. An effect `error_code` of `git_target_pending` means Git still lists a removed page file in the index (on Windows, a program such as a sync watcher, an indexer or antivirus may still hold it open): close that program, check with `git -c core.fscache=false status` on the brain host, then run the `retry-effects` command. It is retried 30 seconds apart and parks after five attempts like other target failures. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |
| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |
| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |
| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |
diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.ts
index abd88b784c..1c31428ca3 100644
--- a/src/commands/doctor/checks/parked-effects.ts
+++ b/src/commands/doctor/checks/parked-effects.ts
@@ -48,7 +48,9 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string
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(' | ')}` +
- (count > rows.length ? ` (first ${rows.length} of ${count} shown)` : '') };
+ (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.' : '') };
} catch (error) {
return { name: 'parked_effects', status: 'warn',
message: `Parked effects could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 0a1b4b4541..d13b857680 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -219,6 +219,7 @@ export const CODES = {
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_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_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 6e0d6d272f..da478ddc2e 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -30,6 +30,12 @@ const rootGone = (relativePath: string) => opError('git_target_unsafe', 'The can
`The canonical checkout was moved or deleted while ${relativePath} was being committed, so nothing was committed for it; the page write itself is committed. Inspect the owner and tell the user: Git effects resume only once the checkout is back, and how to restore it is their decision.`,
{ fix: effectStatusFix });
+/** #6665: Git for Windows' cached directory listing can still show a delete-pending file; a removal is probed and committed without it. */
+const NO_FSCACHE = ['-c', 'core.fscache=false'];
+const targetPending = (path: string) => opError('git_target_pending', `Git still lists ${path} in the index although it is absent on disk.`,
+ `The removal of ${path} could not be staged, so nothing was committed for it; the page write itself is committed. The effect worker retries it and parks it after repeated failures. On Windows another program (a sync watcher, an indexer or antivirus) may still hold the file open: close it, check with git -c core.fscache=false status on the brain host, then retry the parked effect.`,
+ { fix: effectStatusFix });
+
const GIT_ENV = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_GLOB_PATHSPECS: '0', GIT_NOGLOB_PATHSPECS: '0',
GIT_ICASE_PATHSPECS: '0', LC_ALL: 'C' };
@@ -165,7 +171,11 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
const dirty = new Set((await list(['status', '--porcelain', '-z', '--no-renames', '--untracked-files=all'])).split('\0').filter(Boolean).map(entry => entry.slice(3)));
const changed: { requested: string; path: string }[] = [];
const staged: string[] = [];
+ // #6665: a tracked path absent on disk is staged as a removal without trusting status, which can
+ // still list a delete-pending file on Windows (core.fscache), so status said clean and nothing was committed.
+ const removed = new Set(paths.filter(path => tracked.has(path) && !existsSync(join(root, path))));
for (const [requested, path] of normalized) {
+ if (removed.has(path)) continue;
if (!tracked.has(path) && !(existsSync(join(root, path)) && dirty.has(path))) {
try {
const target = await stageTarget(root, hooks, requested, signal);
@@ -188,6 +198,22 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
else results.set(requested, { git: 'unchanged' });
}
}
+ if (removed.size) {
+ const removals = [...removed];
+ const rm = await git(root, hooks, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...removals], signal);
+ if (rm.code !== 0) throw gitFailure('Cannot stage the canonical Git target removal.', `git rm --cached failed for this group of ${removals.length} removed file(s).`);
+ const kept = await git(root, hooks, [...NO_FSCACHE, 'ls-files', '-z', '--', ...removals], signal);
+ const diff = await git(root, hooks, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...removals], signal);
+ if (kept.code !== 0 || diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target removal.', `git ls-files or git diff --cached failed for this group of ${removals.length} removed file(s).`);
+ const still = new Set(kept.stdout.split('\0').filter(Boolean));
+ const indexed = new Set(diff.stdout.split('\0').filter(Boolean));
+ for (const [requested, path] of normalized) {
+ if (!removed.has(path)) continue;
+ if (still.has(path)) results.set(requested, targetPending(path));
+ else if (indexed.has(path)) changed.push({ requested, path });
+ else results.set(requested, { git: 'unchanged' });
+ }
+ }
if (!changed.length) return;
// --only keeps unrelated staged paths out of this commit. After a lost
// database acknowledgment the same HEAD/file state is an exact no-op.
@@ -198,7 +224,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
: commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';
const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];
const trailers = [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.trailer ?? '')).filter(Boolean))];
- const result = await git(root, hooks, ['commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), ...(trailers.length ? ['-m', trailers.join('\n')] : []), '--', ...commitPaths], signal);
+ const result = await git(root, hooks, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), ...(trailers.length ? ['-m', trailers.join('\n')] : []), '--', ...commitPaths], signal);
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
for (const c of changed) results.set(c.requested, outcome);
diff --git a/test/git-target-pending-6665.test.ts b/test/git-target-pending-6665.test.ts
new file mode 100644
index 0000000000..baaef948d6
--- /dev/null
+++ b/test/git-target-pending-6665.test.ts
@@ -0,0 +1,70 @@
+/**
+ * #6665: a delete_page Git effect reported committed while the removal was never committed.
+ *
+ * Hypothesized mechanism (Windows, unconfirmed): a delete-pending file is gone for Node, but Git for
+ * Windows' cached directory listing (core.fscache) still shows it, so `git status` reports the
+ * tracked path clean and `commitGitTargets` returned `unchanged`. A PATH git shim models that cache:
+ * unless a command runs with `-c core.fscache=false`, `status` hides the path and `commit` sees the
+ * file present. The fix stages a tracked, absent path as a removal without trusting status, probes
+ * and commits it with core.fscache off, and refuses with retryable `git_target_pending` (counted
+ * toward parking, never reported as success) when the index still lists it. Doctor's named fix for a
+ * parked git_target_pending target is tested in test/parked-push-retry-6678.test.ts.
+ */
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+const realGit = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();
+
+function fixture() {
+ const base = mkdtempSync(join(tmpdir(), 'gbrain-6665-'));
+ const root = join(base, 'repo'); mkdirSync(root);
+ git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(root, 'gone.md'), 'Body\n');
+ writeFileSync(join(root, 'kept.md'), 'Kept\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');
+ rmSync(join(root, 'gone.md'));
+ const bin = join(base, 'bin'); mkdirSync(bin);
+ writeFileSync(join(bin, 'git'), `#!/bin/sh
+REAL='${realGit}'
+if [ -n "$SHIM_RM_NOOP" ]; then for arg in "$@"; do [ "$arg" = rm ] && exit 0; done; fi
+case " $* " in *" core.fscache=false "*) exec "$REAL" "$@" ;; esac
+for arg in "$@"; do
+ case "$arg" in
+ status) "$REAL" "$@" | tr '\\0' '\\n' | grep -v 'gone.md$' | tr '\\n' '\\0'; exit 0 ;;
+ commit) printf 'Body\\n' > '${root}/gone.md'; "$REAL" "$@"; code=$?; rm -f '${root}/gone.md'; exit $code ;;
+ esac
+done
+exec "$REAL" "$@"
+`);
+ chmodSync(join(bin, 'git'), 0o755);
+ return { base, root, path: `${bin}:${process.env.PATH}` };
+}
+
+test('a tracked path absent on disk is committed as a removal even when status hides it and commit would see it', async () => {
+ const { base, root, path } = fixture();
+ try {
+ const results = await withEnv({ PATH: path }, () => commitGitTargets(root, ['gone.md', 'kept.md']));
+ expect(results.get('gone.md')).toEqual({ git: 'committed' });
+ expect(results.get('kept.md')).toEqual({ git: 'unchanged' });
+ expect(git(root, 'ls-tree', '--name-only', 'HEAD')).not.toContain('gone.md');
+ expect(git(root, 'ls-tree', '--name-only', 'HEAD')).toContain('kept.md');
+ expect(existsSync(join(root, 'gone.md'))).toBe(false);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ } finally { rmSync(base, { recursive: true, force: true }); }
+});
+
+test('a removal the index still lists is git_target_pending, never reported as unchanged', async () => {
+ const { base, root, path } = fixture();
+ try {
+ const results = await withEnv({ PATH: path, SHIM_RM_NOOP: '1' }, () => commitGitTargets(root, ['gone.md']));
+ expect(results.get('gone.md')).toMatchObject({ code: 'git_target_pending', message: expect.stringContaining('gone.md') });
+ expect(git(root, 'ls-tree', '--name-only', 'HEAD')).toContain('gone.md');
+ } finally { rmSync(base, { recursive: true, force: true }); }
+});
diff --git a/test/parked-push-retry-6678.test.ts b/test/parked-push-retry-6678.test.ts
index 1689215065..3038b9c94c 100644
--- a/test/parked-push-retry-6678.test.ts
+++ b/test/parked-push-retry-6678.test.ts
@@ -246,3 +246,15 @@ describe('#6697 revoked writer: parked Git effect', () => {
expect(check.message).toContain(`doctor-healthy (git_push_unavailable); gbrain sources writer retry-effects ${sourceId} --request-id ${await publicId(healthy)} --dry-run`);
}), 120_000);
});
+
+describe('#6665 doctor parked_effects', () => {
+ test('names the fix for a parked git_target_pending target', () => isolated(async home => {
+ const root = await gitRoot(home);
+ const { sourceId } = await claimedSource(root);
+ await parked(root, sourceId, 'gone', {}, 'git_target_pending');
+ const check = await checkParkedEffects(engine, [sourceId]);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gone (git_target_pending)');
+ expect(check.message).toContain('git -c core.fscache=false status');
+ }), 120_000);
+});