Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): reclaim provably abandoned Git index locks; stop large indexes producing SIGKILLed git (#6932); advisor collector failures read as incomplete (#6936)

garrytand139723497db
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 170b1a263d..28b1c24d1d 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -39,7 +39,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 24924d8c5b..e75e70a6cd 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -77,7 +77,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` (`remember`: `unavailable` with `write_error: owner_unavailable`) | On Postgres, a page write or a `remember` about an existing page 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. 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. |
+| `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). The canonical writer removes such a lock by itself when it can prove no process holds it and no git runs in that checkout, and then retries the effects it parked; the error's `fix` says why it could not prove that (another platform, a container, a network filesystem, or a live git). Otherwise 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/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 077d49a562..c8e80478ff 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -376,7 +376,7 @@ src/core/persistence/connector-sync.ts prepareConnectorMutation field SEGW
src/core/persistence/core-guard.ts prepareCoreGuard field INLINE
src/core/persistence/effect-facts.ts bodyAlreadyOffered field META
src/core/persistence/effect-links.ts mentionTargets field INLINE inline arm; a segmented page streams its compiled truth through extractSegmentedPageLinks
-src/core/persistence/effects.ts gitPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize
+src/core/persistence/effects.ts publishGitPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize
src/core/persistence/effects.ts mirrorPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize; per-segment mirror in PR 2
src/core/persistence/embedding-settlement.ts listEmbeddingCandidates sql META
src/core/persistence/facts-maintenance.ts prepareManagedFactsSession field META
diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.ts
index 1c31428ca3..fb7ca27246 100644
--- a/src/commands/doctor/checks/parked-effects.ts
+++ b/src/commands/doctor/checks/parked-effects.ts
@@ -4,6 +4,26 @@ 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';
+import { indexLockReceiptPath, readIndexLockReclaims } from '../../../core/persistence/index-lock-reclaim.ts';
+
+const RECLAIM_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
+
+/**
+ * #6932: index locks this host's writer reclaimed in the last 7 days. Each one was left by a git that was
+ * killed before it could remove its lock, so a run of them points at git steps being killed (deadlines,
+ * job group kills, the OOM killer). Null when there were none.
+ */
+function recentIndexLockReclaims(): { last_7_days: number; latest: { at: string; checkout: string; lock: string; size: number; age_ms: number }; receipts: string } | null {
+ const recent = readIndexLockReclaims().filter(entry => Date.now() - Date.parse(entry.at) < RECLAIM_WINDOW_MS);
+ const latest = recent.at(-1);
+ if (!latest) return null;
+ return { last_7_days: recent.length, latest: { at: latest.at, checkout: latest.checkout, lock: latest.lock, size: latest.size, age_ms: latest.age_ms },
+ receipts: indexLockReceiptPath() };
+}
+
+const reclaimNote = (reclaims: NonNullable<ReturnType<typeof recentIndexLockReclaims>>) =>
+ ` The canonical writer reclaimed ${reclaims.last_7_days} abandoned Git index lock(s) in the last 7 days (latest ${reclaims.latest.at} in ${reclaims.latest.checkout}); `
+ + `each was left by a git process that was killed before it could remove its lock. Receipts: ${reclaims.receipts}.`;
/** #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> {
@@ -41,8 +61,9 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string
? `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 reclaims = recentIndexLockReclaims();
+ const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, ...(reclaims ? { index_lock_reclaims: reclaims } : {}) };
+ if (!count) return { name: 'parked_effects', status: 'ok', message: `No Git or withdrawal effect is parked.${reclaims ? reclaimNote(reclaims) : ''}`, details };
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}`);
return { name: 'parked_effects', status: 'warn', details,
@@ -50,7 +71,8 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string
`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)` : '') +
(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.' : '') };
+ ? '. 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.' : '') +
+ (reclaims ? reclaimNote(reclaims) : '') };
} 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/advisor/run.ts b/src/core/advisor/run.ts
index f563a88cc8..fefc4d4292 100644
--- a/src/core/advisor/run.ts
+++ b/src/core/advisor/run.ts
@@ -3,7 +3,8 @@
*
* Hardcoded v1 collector list (open-Q4): a static array keeps ordering
* deterministic and the surface auditable. Each collector runs in its OWN
- * try/catch so one failure never kills the whole report. Workspace-dependent
+ * try/catch so one failure never kills the whole report (it is reported as a
+ * warn `collector_failed:<id>` finding). Workspace-dependent
* collectors (A1) are dropped over MCP.
*/
@@ -65,7 +66,8 @@ export function rankFindings(findings: AdvisorFinding[], opts: { infoCap?: numbe
/**
* Run every collector and return a ranked report. Resilient: a collector that
- * throws contributes nothing and never aborts the others.
+ * throws never aborts the others, and surfaces as a warn `collector_failed:<id>`
+ * finding so a failed check can't read as a clean one.
*/
export async function runAdvisor(ctx: AdvisorContext): Promise<AdvisorReport> {
const all: AdvisorFinding[] = [];
@@ -78,7 +80,16 @@ export async function runAdvisor(ctx: AdvisorContext): Promise<AdvisorReport> {
all.push(f);
}
} catch {
- // one collector failing must not kill the report
+ // Static text only: the thrown error can carry connection strings or file contents.
+ all.push({
+ id: `collector_failed:${c.id}`,
+ severity: 'warn',
+ title: `Advisor check "${c.id}" could not complete, so its result is unknown (not healthy).`,
+ detail: 'This check failed to run, so this report does not cover it. Re-run `gbrain advisor`; if it keeps failing, run `gbrain doctor`.',
+ fix: { command_argv: null },
+ collector: c.id,
+ ask_user: true,
+ });
}
}
const ranked = rankFindings(all);
diff --git a/src/core/bounded-child-exec.ts b/src/core/bounded-child-exec.ts
index 5b38551646..ff52034a43 100644
--- a/src/core/bounded-child-exec.ts
+++ b/src/core/bounded-child-exec.ts
@@ -8,6 +8,7 @@
import { readFileSync } from 'fs';
import { execFile, type ChildProcess, type ExecFileException } from './spawn.ts';
+/** Default time a stopped child gets to exit after SIGTERM before SIGKILL; a caller passes `termGraceMs` for children that need longer to clean up. */
const BOUNDED_EXEC_TERM_GRACE_MS = 2_000;
/**
@@ -31,6 +32,7 @@ export interface BoundedExecOptions {
env?: NodeJS.ProcessEnv;
maxBuffer?: number;
signal?: AbortSignal;
+ termGraceMs?: number;
}
/**
@@ -45,10 +47,12 @@ export interface BoundedExecOptions {
* Stopping sends SIGTERM first so git can remove its lockfiles (a SIGKILLed
* `git add`/`commit` leaves `.git/index.lock` behind and every later git call
* in that worktree fails), then SIGKILLs after a short grace period and
- * settles from the timer even if the exit event never arrives.
+ * settles from the timer even if the exit event never arrives. A git stalled in
+ * uninterruptible I/O or memory reclaim acts on SIGTERM only seconds later, so
+ * git callers pass a longer `termGraceMs` (#6932).
*/
export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string; stderr: string }> {
- const { timeout, signal, ...rest } = options;
+ const { timeout, signal, termGraceMs = BOUNDED_EXEC_TERM_GRACE_MS, ...rest } = options;
return new Promise(resolve => {
let settled = false;
const finish = (error: ExecFileException | null, stdout: string, stderr = '') => {
@@ -80,7 +84,7 @@ export function execFileBounded(file: string, args: string[], options: BoundedEx
escalation = setTimeout(() => {
child.kill('SIGKILL');
settleStopped();
- }, BOUNDED_EXEC_TERM_GRACE_MS);
+ }, termGraceMs);
};
const timer = setTimeout(() => stop(`${file} did not finish within ${timeout}ms`, 'ETIMEDOUT'), timeout);
const onAbort = () => stop(`${file} was aborted`, 'ABORT_ERR');
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index da478ddc2e..9ae137e460 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -9,6 +9,9 @@ import type { GitCommitNote } from './effect-model.ts';
import { persistenceHome } from './identity.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { gitChildEnv } from '../git-env.ts';
+import type { Action } from '../agent-output.ts';
+import type { NativeLockHandle } from './native-lock.ts';
+import { proveIndexLockAbandoned, reclaimIndexLock, type IndexLockReclaim } from './index-lock-reclaim.ts';
/** An index lock younger than this is contention; an older one is reported as stale. */
const INDEX_LOCK_GRACE_MS = 10 * 60 * 1000;
@@ -36,45 +39,99 @@ const targetPending = (path: string) => opError('git_target_pending', `Git still
`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 });
+/** GIT_OPTIONAL_LOCKS=0: read-only steps (status) never take the index lock for an opportunistic refresh. */
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' };
+ GIT_ICASE_PATHSPECS: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' };
-async function run(root: string, hooks: string, args: string[], signal?: AbortSignal) {
- return execFileBounded('git', ['--literal-pathspecs', '-C', root, '-c', `core.hooksPath=${hooks}`, '-c', 'commit.gpgsign=false', ...args], {
- timeout: 20_000, maxBuffer: 1024 * 1024, signal, env: gitChildEnv(GIT_ENV),
+/** Every git step gets at least this long. */
+const GIT_STEP_TIMEOUT_MS = 20_000;
+/**
+ * #6932: each staging and commit step reads, and add/commit rewrite, the whole index, so a large checkout
+ * gets this much more per MiB of index, up to {@link GIT_STEP_TIMEOUT_CAP_MS}.
+ */
+const GIT_STEP_MS_PER_INDEX_MIB = 2_000;
+const GIT_STEP_TIMEOUT_CAP_MS = 120_000;
+/** A git stalled in I/O or memory reclaim acts on SIGTERM seconds late; SIGKILL before then leaves index.lock behind. */
+const GIT_TERM_GRACE_MS = 10_000;
+
+/** The canonical writer's hold on the checkout: it alone may reclaim an abandoned index lock there. */
+export interface GitEffectOwner {
+ writerLock: NativeLockHandle;
+ onReclaim?: (receipt: IndexLockReclaim) => void;
+}
+
+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], {
+ timeout: session.timeoutMs, termGraceMs: GIT_TERM_GRACE_MS, maxBuffer: 1024 * 1024, signal: session.signal, env: gitChildEnv(GIT_ENV),
});
}
+/** The deadline of one staging or commit step in a checkout whose index holds `indexBytes`. */
+export function gitStepTimeoutMs(indexBytes: number): number {
+ return Math.min(GIT_STEP_TIMEOUT_CAP_MS, GIT_STEP_TIMEOUT_MS + Math.ceil(Math.max(0, indexBytes) / (1024 * 1024)) * GIT_STEP_MS_PER_INDEX_MIB);
+}
+
+/** This checkout's step deadline; the floor when its index cannot be located. */
+async function stepTimeoutMs(session: GitSession): Promise<number> {
+ const located = await run(session, ['rev-parse', '--git-path', 'index']);
+ if (located.error) return GIT_STEP_TIMEOUT_MS;
+ try { return gitStepTimeoutMs(statSync(resolvePath(session.root, located.stdout.replace(/\n$/, ''))).size); }
+ catch { return GIT_STEP_TIMEOUT_MS; }
+}
+
+const staleLockFix = (root: string, lock: string, why: string): Action => ({
+ ask_user: true, actor: 'user', consent: [], requires_exclusive: false,
+ why: `gbrain did not remove the lock because it could not prove the lock is abandoned: ${why}.`,
+ user_message: `A Git index lock (${lock}) has blocked the canonical checkout ${root} for over 10 minutes, so Git backups of new page writes are parked. gbrain did not remove it because ${why}. Please check that no git command is running in that checkout; if none is, remove ${lock}, then run the retry command that gbrain sources writer status lists for each parked effect.`,
+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] },
+});
+
/**
* Git refused because another process holds this checkout's index lock. Only the checkout's own index lock
* (`git rev-parse --git-path index.lock`, so linked worktrees resolve) qualifies; a ref or remote lock with
- * the same wording does not. The lock is never removed here: its holder may be a live git of the user or of
- * this owner, and a timestamp cannot prove otherwise. A fresh lock is contention; one older than the grace,
- * or dated in the future, is `git_index_stale`, which counts toward parking and names the lock.
+ * the same wording does not. #6932: while the canonical writer holds its writer lock, a lock it proves
+ * abandoned (index-lock-reclaim.ts) is reclaimed and the step runs again ('reclaimed'). Otherwise the lock
+ * stays: a fresh one is contention; one older than the grace, or dated in the future, is `git_index_stale`,
+ * which counts toward parking, names the lock and says why it was not reclaimed.
*/
-async function indexLockError(root: string, hooks: string, stderr: string, signal?: AbortSignal): Promise<OperationError | null> {
+async function indexLockError(session: GitSession, stderr: string, mayReclaim: boolean): Promise<OperationError | 'reclaimed' | null> {
const refused = LOCK_REFUSAL.exec(stderr)?.[1];
if (!refused) return null;
- const located = await run(root, hooks, ['rev-parse', '--git-path', 'index.lock'], signal);
+ const located = await run(session, ['rev-parse', '--git-path', 'index.lock']);
if (located.error) return null;
- const lock = resolvePath(root, located.stdout.replace(/\n$/, ''));
- if (canonical(resolvePath(root, refused)) !== canonical(lock)) return null;
+ const lock = resolvePath(session.root, located.stdout.replace(/\n$/, ''));
+ if (canonical(resolvePath(session.root, refused)) !== canonical(lock)) return null;
let age: number;
try { age = Date.now() - statSync(lock).mtimeMs; } catch { return null; }
+ let why = 'this caller does not hold the checkout\'s writer lock';
+ if (session.owner && !session.owner.writerLock.released && mayReclaim) {
+ const verdict = proveIndexLockAbandoned(lock, session.root, INDEX_LOCK_GRACE_MS);
+ const receipt = verdict.abandoned ? reclaimIndexLock(lock, session.root, verdict) : null;
+ if (receipt) { session.owner.onReclaim?.(receipt); return 'reclaimed'; }
+ why = verdict.abandoned ? 'the lock changed while it was being reclaimed' : verdict.reason;
+ }
if (age >= 0 && age < INDEX_LOCK_GRACE_MS) {
return new OperationError('git_index_locked', 'Another Git process holds the canonical checkout index lock.', 'The effect is retried shortly.');
}
- return new OperationError('git_index_stale', `A Git index lock older than 10 minutes blocks the canonical checkout: ${lock}.`,
- `If no git command is running in that checkout, remove ${lock}, then retry the effect with gbrain sources writer retry-effects <source> --request-id <id>.`);
+ return opError('git_index_stale', `A Git index lock older than 10 minutes blocks the canonical checkout: ${lock}.`,
+ `gbrain did not remove it because ${why}. If no git command is running in that checkout, remove ${lock}, then retry the effect with gbrain sources writer retry-effects <source> --request-id <id>.`,
+ { detail: lock, fix: staleLockFix(session.root, lock, why) });
}
-async function git(root: string, hooks: string, args: string[], signal?: AbortSignal): Promise<{ stdout: string; code: number }> {
- const { error, stdout, stderr } = await run(root, hooks, args, signal);
- if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',
- 'A git command in the canonical checkout did not finish within 20 seconds or could not start.');
- const code = error?.code as number ?? 0;
- if (code !== 0) { const locked = await indexLockError(root, hooks, stderr, signal); if (locked) throw locked; }
- return { stdout, code };
+async function git(session: GitSession, args: string[]): Promise<{ stdout: string; code: number }> {
+ for (let reclaimed = false; ; reclaimed = true) {
+ const { error, stdout, stderr } = await run(session, args);
+ if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',
+ `A git command in the canonical checkout did not finish within ${Math.round(session.timeoutMs / 1000)} seconds or could not start.`);
+ const code = error?.code as number ?? 0;
+ if (code === 0) return { stdout, code };
+ const locked = await indexLockError(session, stderr, !reclaimed);
+ if (locked === 'reclaimed') continue;
+ if (locked) throw locked;
+ return { stdout, code };
+ }
}
export const INDEX_LOCK_GRACE_FOR_TESTS = INDEX_LOCK_GRACE_MS;
@@ -85,19 +142,20 @@ type GitOutcome = { git: string; reason?: string; push?: string };
* Stage one single-file target. Returns 'changed' when the index now differs
* for the path, 'unchanged', or a skip outcome for an absent target.
*/
-async function stageTarget(root: string, hooks: string, relativePath: string, signal?: AbortSignal): Promise<{ path: string; state: 'changed' | 'unchanged' } | { path: string; skip: GitOutcome }> {
+async function stageTarget(session: GitSession, relativePath: string): Promise<{ path: string; state: 'changed' | 'unchanged' } | { path: string; skip: GitOutcome }> {
+ const root = session.root;
const path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');
relativePath = relative(root, path).split(sep).join('/');
- const tracked = await git(root, hooks, ['ls-files', '-z', '--error-unmatch', '--', relativePath], signal);
+ const tracked = await git(session, ['ls-files', '-z', '--error-unmatch', '--', relativePath]);
if (tracked.code !== 0 && tracked.code !== 1) throw gitFailure('Cannot inspect the canonical Git target.', `git ls-files failed for ${relativePath}.`);
- const changed = await git(root, hooks, ['status', '--porcelain', '--untracked-files=all', '--', relativePath], signal);
+ const changed = await git(session, ['status', '--porcelain', '--untracked-files=all', '--', relativePath]);
if (changed.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git status failed for ${relativePath}.`);
if (changed.stdout.trim()) {
if (tracked.code === 0 || existsSync(path)) {
- const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);
+ const add = await git(session, ['add', '-A', '--', relativePath]);
if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for ${relativePath}.`);
}
- const diff = await git(root, hooks, ['diff', '--cached', '--quiet', '--', relativePath], signal);
+ const diff = await git(session, ['diff', '--cached', '--quiet', '--', relativePath]);
if (diff.code === 1) return { path: relativePath, state: 'changed' };
if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for ${relativePath}.`);
return { path: relativePath, state: 'unchanged' };
@@ -111,8 +169,8 @@ async function stageTarget(root: string, hooks: string, relativePath: string, si
parent = dirname(parent);
}
const scope = relative(root, parent).split(sep).join('/') || '.';
- const deleted = await git(root, hooks, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);
- const staged = await git(root, hooks, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);
+ const deleted = await git(session, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
+ const staged = await git(session, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
if (deleted.code !== 0 || staged.code !== 0) throw gitFailure('Cannot inspect canonical Git deletions.', `git diff could not list the deletions under ${scope}.`);
for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {
if (existsSync(join(root, entry))) continue;
@@ -127,11 +185,17 @@ async function stageTarget(root: string, hooks: string, relativePath: string, si
return { path: relativePath, skip: { git: 'skipped', reason: 'target_absent', push: 'skipped' } };
}
-function withHooks<T>(run: (hooks: string) => Promise<T>): Promise<T> {
+/** 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> {
const base = join(persistenceHome(), 'empty-hooks');
mkdirSync(base, { recursive: true, mode: 0o700 });
const hooks = mkdtempSync(join(base, 'effect-'));
- return run(hooks).finally(() => rmSync(hooks, { recursive: true, force: true }));
+ try {
+ const session: GitSession = { root, hooks, signal, owner, timeoutMs: GIT_STEP_TIMEOUT_MS };
+ if (scaled) session.timeoutMs = await stepTimeoutMs(session);
+ return await work(session);
+ } finally { rmSync(hooks, { recursive: true, force: true }); }
}
const commitText = (text: string) => text.replace(/[\u0000-\u001f\u007f]/g, '');
@@ -148,11 +212,14 @@ const commitText = (text: string) => text.replace(/[\u0000-\u001f\u007f]/g, '');
* order. A note's `gbrain-repair:` trailer goes in the message's last
* paragraph (one line per noted path), where Git reads trailers. Control
* characters are stripped from all three.
+ *
+ * `owner` is the caller's writer lock on this checkout: with it, an index lock
+ * that is provably abandoned is reclaimed and the step retried (#6932).
*/
export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal,
- notes?: ReadonlyMap<string, GitCommitNote>): Promise<Map<string, GitOutcome | OperationError>> {
+ notes?: ReadonlyMap<string, GitCommitNote>, owner?: GitEffectOwner): Promise<Map<string, GitOutcome | OperationError>> {
const results = new Map<string, GitOutcome | OperationError>();
- await withHooks(async hooks => {
+ await withSession(root, signal, owner, true, async session => {
// One ls-files, one status, one add and one diff for the group; targets
// that are neither tracked nor present take the per-target path, which
// owns the absent-target and native-spelling refusals.
@@ -163,7 +230,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
}
const paths = [...new Set(normalized.values())];
const list = async (args: string[]) => {
- const out = paths.length ? await git(root, hooks, [...args, '--', ...paths], signal) : { stdout: '', code: 0 };
+ const out = paths.length ? await git(session, [...args, '--', ...paths]) : { stdout: '', code: 0 };
if (out.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git ${args[0]} failed for this group of ${paths.length} file(s).`);
return out.stdout;
};
@@ -178,7 +245,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
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);
+ const target = await stageTarget(session, requested);
if ('skip' in target) results.set(requested, target.skip);
else if (target.state === 'changed') changed.push({ requested, path: target.path });
else results.set(requested, { git: 'unchanged' });
@@ -187,9 +254,9 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
else results.set(requested, { git: 'unchanged' });
}
if (staged.length) {
- const add = await git(root, hooks, ['add', '-A', '--', ...new Set(staged)], signal);
+ const add = await git(session, ['add', '-A', '--', ...new Set(staged)]);
if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for this group of ${new Set(staged).size} file(s).`);
- const diff = await git(root, hooks, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...new Set(staged)], signal);
+ const diff = await git(session, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...new Set(staged)]);
if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for this group of ${new Set(staged).size} file(s).`);
const indexed = new Set(diff.stdout.split('\0').filter(Boolean));
for (const [requested, path] of normalized) {
@@ -200,10 +267,10 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
}
if (removed.size) {
const removals = [...removed];
- const rm = await git(root, hooks, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...removals], signal);
+ const rm = await git(session, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...removals]);
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);
+ const kept = await git(session, [...NO_FSCACHE, 'ls-files', '-z', '--', ...removals]);
+ const diff = await git(session, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...removals]);
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));
@@ -224,7 +291,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, [...(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 result = await git(session, [...(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]);
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);
@@ -234,13 +301,13 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
/** Push the current branch to its tracking remote once. A plain push is idempotent and cannot import remote canonical content. */
export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{ push: 'committed' } | { push: 'skipped'; reason: 'no_tracking_remote' }> {
- return withHooks(async hooks => {
- const branch = await git(root, hooks, ['symbolic-ref', '--quiet', '--short', 'HEAD'], signal);
+ return withSession(root, signal, undefined, false, async session => {
+ const branch = await git(session, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
if (branch.code !== 0) return { push: 'skipped', reason: 'no_tracking_remote' } as const;
- const remote = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.remote`], signal);
- const merge = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.merge`], signal);
+ const remote = await git(session, ['config', '--get', `branch.${branch.stdout.trim()}.remote`]);
+ const merge = await git(session, ['config', '--get', `branch.${branch.stdout.trim()}.merge`]);
if (remote.code !== 0 || merge.code !== 0 || !remote.stdout.trim() || remote.stdout.trim() === '.') return { push: 'skipped', reason: 'no_tracking_remote' } as const;
- const push = await git(root, hooks, ['push', '--', remote.stdout.trim(), `HEAD:${merge.stdout.trim()}`], signal);
+ const push = await git(session, ['push', '--', remote.stdout.trim(), `HEAD:${merge.stdout.trim()}`]);
if (push.code !== 0) throw opError('git_push_unavailable', 'The canonical commit is durable locally; its push will retry.',
`git push to ${remote.stdout.trim()} failed (network, credentials or a rejected non-fast-forward). Nothing is lost locally and the worker pushes again on a later pass; gbrain never pulls or rebases the checkout. If it keeps failing, check the remote and its credentials with git push on the brain host.`,
{ fix: effectStatusFix });
@@ -259,9 +326,9 @@ export const DURABILITY_NOT_ENABLED = { git: 'skipped', reason: 'durability_not_
* and an unrecorded binding falls back to the probe, fail-closed.
*/
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,
- hardened?: boolean, note?: GitCommitNote, binding?: Pick<WorktreeBinding, 'git_durability'> | null): Promise<Record<string, unknown>> {
+ hardened?: boolean, note?: GitCommitNote, binding?: Pick<WorktreeBinding, 'git_durability'> | null, owner?: GitEffectOwner): Promise<Record<string, unknown>> {
if (!(hardened ?? (await gitDurabilityPolicy(binding, root)).durable)) return { ...DURABILITY_NOT_ENABLED };
- const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined)).get(relativePath)!;
+ const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined, owner)).get(relativePath)!;
if (outcome instanceof OperationError) throw outcome;
if (outcome.reason === 'target_absent') return outcome;
const pushed = await pushGitRoot(root, signal);
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index 0d4854592f..5dbc653ee0 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -170,6 +170,34 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
});
}
+/** Park codes an abandoned index lock produces; a reclaim removes their cause. */
+const INDEX_LOCK_PARK_CODES = ['git_index_stale', 'git_index_locked'];
+
+/**
+ * #6932: after the canonical writer reclaims an abandoned index lock in a worktree, each request there whose
+ * parked targets were all parked by that lock gets the one more attempt `retry-effects` would authorize,
+ * through the same checks (stored authority, claims, recovery). A request it cannot retry stays parked for
+ * the operator. Returns the number of requests requeued; never throws, so a reclaim's own outcome stands.
+ */
+export async function retryIndexLockParks(engine: BrainEngine, worktreeId: string): Promise<number> {
+ let requeued = 0;
+ try {
+ const requests = await engine.executeRaw<{ id: string; source_id: string; request_id: string }>(
+ `SELECT DISTINCT r.id,r.source_id,r.request_id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND e.data ? 'parked'
+ AND NOT EXISTS (SELECT 1 FROM persistence_effects o CROSS JOIN LATERAL jsonb_array_elements(COALESCE(o.data->'parked','[]'::jsonb)) AS p(target)
+ WHERE o.request_id=e.request_id AND (o.state<>'committed' AND o.data ? 'parked') AND COALESCE(p.target->>'error_code','') <> ALL($2::text[]))
+ LIMIT 100`, [worktreeId, INDEX_LOCK_PARK_CODES]);
+ for (const request of requests) {
+ try {
+ const result = await retryParkedEffects(engine, request.source_id, request.request_id, false, { internalId: request.id });
+ if ((result?.effects as { action?: string }[] | undefined)?.some(effect => effect.action === 'retry_queued')) requeued++;
+ } catch { /* refused (authority, claim, host identity): it stays parked with its retry command */ }
+ }
+ } catch { /* the parked effects keep their retry commands */ }
+ return requeued;
+}
+
/**
* `retry-effects` dispatch: parked Git/withdrawal work that still needs action
* wins; otherwise the embedding obligation is handled, with any settled parked
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index d1706ca832..b8f7585457 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -36,7 +36,8 @@ import { prepareFileTarget } from './page-prepare.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';
import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';
-import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot } from './effect-git.ts';
+import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';
+import { retryIndexLockParks } from './effect-retry.ts';
import { gitDurabilityPolicy } from './git-durability-policy.ts';
import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
@@ -47,7 +48,7 @@ import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
-import { isLockOpenFailure } from './native-lock.ts';
+import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';
import { planPageEmbedding } from '../page-embedding-budget.ts';
import { chunkGenerationFilter, chunkManifestReads } from '../search/safe-chunks.ts';
@@ -238,14 +239,23 @@ function gitCommitNote(effect: PersistenceEffect): GitCommitNote | undefined {
}
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
- attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {
+ attempt: EffectAttempt, hardened: boolean | undefined, writerLock: NativeLockHandle | null): Promise<void> {
if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }
// #5409: a read-only mirror's checkout is never committed to; its publications wrote no file.
if (await sourceMirrorReadOnly(engine, effect.source_id)) { await completeEffect(engine, effect, { git: 'skipped', reason: 'mirror_read_only' }); return; }
const root = binding.local_path;
+ let reclaimed = false;
+ const owner = writerLock ? { writerLock, onReclaim: () => { reclaimed = true; } } : undefined;
+ try { await publishGitPage(engine, effect, { ...binding, local_path: root }, opts, attempt, hardened, owner); }
+ finally { if (reclaimed && effect.worktree_id) await retryIndexLockParks(engine, effect.worktree_id); }
+}
+
+async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding & { local_path: string }, opts: EffectWorkerOptions,
+ attempt: EffectAttempt, hardened: boolean | undefined, owner: GitEffectOwner | undefined): Promise<void> {
+ const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
- if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, gitCommitNote(effect)));
+ if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, gitCommitNote(effect), undefined, owner));
return;
}
// Only a page walk reads snapshots; a single-file effect completes by its recorded hash.
@@ -274,7 +284,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });
return;
}
- const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect));
+ const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened, gitCommitNote(effect), undefined, owner);
if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);
else await finishPage(engine, effect, snapshot, result);
}
@@ -609,7 +619,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
});
effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);
if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts, attempt);
- else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt, hardened);
+ else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt, hardened, lock);
else await withAIAttribution({ request_id: effect.request_id, effect: effect.kind }, () => effect.kind === 'facts-backstop'
? dispatchFactsBackstopEffect(engine, effect, opts.hostId)
: effect.kind === 'links' ? runLinksEffect(engine, effect, opts.hostId)
@@ -662,6 +672,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
return;
}
const targets: { effect: PersistenceEffect; path: string; attempt: EffectAttempt }[] = [];
+ let reclaimed = false;
try {
for (const effect of effects) {
const attempt: EffectAttempt = {};
@@ -681,7 +692,8 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
}
const notes = new Map(targets.flatMap(({ effect, path }) => { const note = gitCommitNote(effect); return note ? [[path, note] as const] : []; }));
- const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal, notes) : new Map();
+ const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal, notes,
+ { writerLock: lock, onReclaim: () => { reclaimed = true; } }) : new Map();
const pending = unpushed.get(binding.local_path) ?? { binding, items: [] };
for (const { effect, path, attempt } of targets) {
const outcome = outcomes.get(path)!;
@@ -692,7 +704,11 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
if (pending.items.length) unpushed.set(binding.local_path, pending);
} catch (error) {
for (const { effect, attempt } of targets) await recordFailure(engine, effect, error, opts.signal, attempt.target);
- } finally { await lock.release(); }
+ } finally {
+ // #6932: the reclaimed lock may have parked earlier effects of this worktree; they get one more attempt.
+ if (reclaimed) await retryIndexLockParks(engine, effects[0]!.worktree_id!);
+ await lock.release();
+ }
};
// A group of single-file Git effects in a root without the durability hook
// runs no git command: each effect only records its outcome. The group takes
diff --git a/src/core/persistence/index-lock-reclaim.ts b/src/core/persistence/index-lock-reclaim.ts
new file mode 100644
index 0000000000..caabd1bec4
--- /dev/null
+++ b/src/core/persistence/index-lock-reclaim.ts
@@ -0,0 +1,192 @@
+/**
+ * #6932: reclaim a Git index lock that provably belongs to no live process.
+ *
+ * A git killed with SIGKILL after it created `index.lock` (a bounded step that
+ * missed its deadline, a job group killed after its grace) leaves the lock
+ * behind, and every later git in that checkout refuses to run. Only the
+ * checkout's writer, while it holds the writer lock, may reclaim one, and only
+ * when it can prove the lock is abandoned:
+ *
+ * - Linux with a full view of the process table: `/proc` is not mounted with
+ * `hidepid`, and this process is not in a nested PID namespace (a container
+ * cannot see a git running on its host).
+ * - The lock is on a local filesystem; a git on another machine sharing a
+ * network mount is invisible here.
+ * - No process has the lock open, and no git process runs with its working
+ * directory, `GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR` or
+ * `GIT_INDEX_FILE` inside the checkout or its git directory. A git process
+ * whose open files or environment cannot be read fails the proof. Another
+ * user's processes that are not git cannot be read and are not checked: only
+ * git creates this lock, and their git processes still fail the proof.
+ * - The lock is empty and at least {@link RECLAIM_MIN_AGE_MS} old, or older
+ * than the stale threshold.
+ *
+ * Anything short of that proof leaves the lock in place. A reclaim moves the
+ * lock aside, checks it is still the file that was proven, removes it, and
+ * appends a receipt to {@link indexLockReceiptPath} that doctor reports.
+ */
+import { appendFileSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, statfsSync, statSync,
+ unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
+import { persistenceHome } from './identity.ts';
+
+/** An empty lock younger than this is left to its git, which may have just created it. */
+export const RECLAIM_MIN_AGE_MS = 5_000;
+/** Receipts kept after a trim; the file is trimmed once it passes twice this many lines. */
+const RECEIPTS_KEPT = 100;
+
+/** statfs magic numbers of network and userspace filesystems, where another machine's git may hold the lock. */
+const SHARED_FILESYSTEMS = new Set([
+ 0x6969, // nfs
+ 0x517b, // smb
+ 0xff534d42, // cifs
+ 0xfe534d42, // smb2
+ 0x65735546, // fuse
+ 0x00c36400, // ceph
+ 0x01021997, // 9p
+ 0x5346414f, // afs
+ 0x47504653, // gpfs
+ 0x0bd00bd0, // lustre
+ 0x013111a8, // ibrix
+ 0x6b414653, // kafs
+]);
+
+export interface IndexLockProof { abandoned: true; size: number; ageMs: number; dev: number; ino: number }
+export interface IndexLockDoubt { abandoned: false; reason: string }
+export type IndexLockVerdict = IndexLockProof | IndexLockDoubt;
+
+export interface IndexLockReclaim {
+ at: string;
+ checkout: string;
+ lock: string;
+ size: number;
+ age_ms: number;
+ pid: number;
+}
+
+const doubt = (reason: string): IndexLockDoubt => ({ abandoned: false, reason });
+const canonical = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };
+const inside = (path: string, roots: string[]) => roots.some(root => path === root || path.startsWith(root.endsWith(sep) ? root : root + sep));
+const gone = (error: unknown) => ['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code ?? '');
+
+/** Why this process cannot see every process that could hold a lock, or null when it can. */
+export function processTableBlind(): string | null {
+ if (process.platform !== 'linux') return `this platform (${process.platform}) gives no way to list the processes that hold a file open`;
+ try {
+ const nspid = /^NSpid:\s*(.*)$/m.exec(readFileSync('/proc/self/status', 'utf8'))?.[1]?.trim().split(/\s+/) ?? [];
+ if (nspid.length > 1) return 'gbrain runs in a nested PID namespace (a container), so a git running outside it is invisible';
+ for (const line of readFileSync('/proc/self/mountinfo', 'utf8').split('\n')) {
+ const [mount, options] = line.split(' - ');
+ if (mount?.split(' ')[4] === '/proc' && /(^|,)hidepid=(1|2|invisible|noaccess)(,|$)/.test(options?.split(' ')[2] ?? '')) {
+ return '/proc is mounted with hidepid, so other users\' processes are invisible';
+ }
+ }
+ } catch { return 'the process table under /proc could not be read'; }
+ return null;
+}
+
+/** The git environment variables that place a process's repository or index. */
+const GIT_LOCATION_VARIABLES = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE'];
+
+/** A process that holds the lock or runs git in the checkout, or a git process this process cannot inspect. */
+function liveHolder(lock: { dev: number; ino: number }, roots: string[]): string | null {
+ for (const pid of readdirSync('/proc')) {
+ if (!/^\d+$/.test(pid)) continue;
+ let comm: string;
+ try { comm = readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); } catch { continue; }
+ let fds: string[] | null = null;
+ try { fds = readdirSync(`/proc/${pid}/fd`); } catch (error) { if (gone(error)) continue; }
+ for (const fd of fds ?? []) {
+ let opened;
+ try { opened = statSync(`/proc/${pid}/fd/${fd}`); } catch { continue; }
+ if (opened.dev === lock.dev && opened.ino === lock.ino) return `process ${pid} (${comm}) has the lock open`;
+ }
+ if (!comm.startsWith('git')) continue;
+ if (fds === null) return `git process ${pid} (${comm}) belongs to another user, so its open files cannot be checked`;
+ let cwd: string;
+ let environ: string;
+ try {
+ cwd = readlinkSync(`/proc/${pid}/cwd`).replace(/ \(deleted\)$/, '');
+ environ = readFileSync(`/proc/${pid}/environ`, 'utf8');
+ } catch (error) {
+ if (gone(error)) continue;
+ return `git process ${pid} (${comm}) could not be inspected`;
+ }
+ if (inside(cwd, roots)) return `git process ${pid} (${comm}) is running in the checkout`;
+ for (const entry of environ.split('\0')) {
+ const at = entry.indexOf('=');
+ if (at < 0 || !GIT_LOCATION_VARIABLES.includes(entry.slice(0, at))) continue;
+ const value = entry.slice(at + 1);
+ if (value && inside(canonical(isAbsolute(value) ? value : resolve(cwd, value)), roots)) return `git process ${pid} (${comm}) uses this repository through ${entry.slice(0, at)}`;
+ }
+ }
+ return null;
+}
+
+/**
+ * Whether `lock` (the checkout's own index lock) is provably abandoned. `checkout` is the worktree root;
+ * the lock's directory is the git directory that owns the index. A lock older than `staleMs` qualifies
+ * whatever its size; a younger one only when it is empty and at least {@link RECLAIM_MIN_AGE_MS} old.
+ */
+export function proveIndexLockAbandoned(lock: string, checkout: string, staleMs: number): IndexLockVerdict {
+ const blind = processTableBlind();
+ if (blind) return doubt(blind);
+ let before;
+ try { before = lstatSync(lock); } catch { return doubt('the lock disappeared while it was checked'); }
+ if (!before.isFile()) return doubt('the lock is not a regular file');
+ const ageMs = Date.now() - before.mtimeMs;
+ if (ageMs < 0) return doubt('the lock is dated in the future, so its age proves nothing');
+ if (before.size > 0 && ageMs < staleMs) return doubt(`the lock holds ${before.size} bytes and is younger than ${Math.round(staleMs / 60_000)} minutes, so a git may still be writing it`);
+ if (ageMs < RECLAIM_MIN_AGE_MS) return doubt('the lock was created moments ago');
+ try {
+ if (SHARED_FILESYSTEMS.has(Number(statfsSync(dirname(lock)).type) >>> 0)) return doubt('the checkout is on a network or userspace filesystem, where a git on another machine is invisible');
+ } catch { return doubt('the filesystem holding the lock could not be identified'); }
+ let holder: string | null;
+ try { holder = liveHolder(before, [canonical(checkout), canonical(dirname(lock))]); }
+ catch { return doubt('the process table under /proc could not be read'); }
+ if (holder) return doubt(holder);
+ let after;
+ try { after = lstatSync(lock); } catch { return doubt('the lock disappeared while it was checked'); }
+ if (after.ino !== before.ino || after.dev !== before.dev || after.size !== before.size || after.mtimeMs !== before.mtimeMs) return doubt('the lock changed while it was checked');
+ return { abandoned: true, size: before.size, ageMs, dev: before.dev, ino: before.ino };
+}
+
+/**
+ * Remove a proven lock. It is renamed aside first, so a lock that a new git created after the proof is
+ * never the one removed: a renamed file that is not the proven one is put back and nothing is reclaimed.
+ */
+export function reclaimIndexLock(lock: string, checkout: string, proof: IndexLockProof): IndexLockReclaim | null {
+ const aside = `${lock}.gbrain-reclaim-${process.pid}-${Date.now()}`;
+ try { renameSync(lock, aside); } catch { return null; }
+ const moved = lstatSync(aside);
+ if (moved.dev !== proof.dev || moved.ino !== proof.ino) {
+ try { renameSync(aside, lock); } catch { /* a newer lock now holds the name; the moved file stays aside for the operator */ }
+ return null;
+ }
+ unlinkSync(aside);
+ const receipt = { at: new Date().toISOString(), checkout, lock, size: proof.size, age_ms: Math.round(proof.ageMs), pid: process.pid };
+ try { recordReceipt(receipt); } catch { /* the log line below still records it */ }
+ console.error(`[gbrain] reclaimed an abandoned Git index lock in ${checkout}: ${lock} (${proof.size} bytes, ${Math.round(proof.ageMs / 1000)}s old, no live process held it); retrying the Git effect`);
+ return receipt;
+}
+
+/** Host-local receipts of reclaimed index locks, newest last. */
+export function indexLockReceiptPath(): string { return join(persistenceHome(), 'index-lock-reclaims.jsonl'); }
+
+function recordReceipt(receipt: IndexLockReclaim): void {
+ const path = indexLockReceiptPath();
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ appendFileSync(path, `${JSON.stringify(receipt)}\n`, { mode: 0o600 });
+ const lines = readFileSync(path, 'utf8').split('\n').filter(Boolean);
+ if (lines.length > RECEIPTS_KEPT * 2) writeFileSync(path, `${lines.slice(-RECEIPTS_KEPT).join('\n')}\n`, { mode: 0o600 });
+}
+
+/** Receipts recorded on this host, oldest first; an unreadable file or line reads as none. */
+export function readIndexLockReclaims(): IndexLockReclaim[] {
+ let text: string;
+ try { text = readFileSync(indexLockReceiptPath(), 'utf8'); } catch { return []; }
+ return text.split('\n').flatMap(line => {
+ try { const entry = JSON.parse(line) as IndexLockReclaim; return typeof entry?.at === 'string' && typeof entry.lock === 'string' ? [entry] : []; }
+ catch { return []; }
+ });
+}
diff --git a/test/advisor-cli.test.ts b/test/advisor-cli.test.ts
index 15383ab97b..48d938c2d4 100644
--- a/test/advisor-cli.test.ts
+++ b/test/advisor-cli.test.ts
@@ -35,7 +35,8 @@ import { LATEST_VERSION } from '../src/core/migrate.ts';
import { DEFAULT_EMBEDDING_MODEL } from '../src/core/ai/defaults.ts';
import { getRecipe } from '../src/core/ai/recipes/index.ts';
import type { BrainEngine } from '../src/core/engine.ts';
-import type { AdvisorReport } from '../src/core/advisor/types.ts';
+import { COLLECTORS } from '../src/core/advisor/run.ts';
+import type { AdvisorCollector, AdvisorFinding, AdvisorReport } from '../src/core/advisor/types.ts';
import { withEnv, emptyHome } from './helpers/with-env.ts';
/** The env key the EFFECTIVE default embedding model requires (dynamic so a
@@ -172,6 +173,99 @@ describe('runAdvisorCli exit-verdict mapping (E2 contract: 0 clean / 1 warn / 2
});
});
+const CLI_THROWN_SECRET = 'connect ECONNREFUSED postgres://alice-example:[email protected]:5432/brain';
+
+const throwingCollector: AdvisorCollector = {
+ id: 'throwing-check',
+ collect: async () => { throw new Error(CLI_THROWN_SECRET); },
+};
+const cleanCollector: AdvisorCollector = { id: 'clean-check', collect: async () => [] };
+const criticalCollector: AdvisorCollector = {
+ id: 'critical-check',
+ collect: async () => [{
+ id: 'crit', severity: 'critical', title: 'a critical thing', fix: { command_argv: null },
+ collector: 'critical-check', ask_user: true,
+ } satisfies AdvisorFinding],
+};
+
+/** Swap the shared COLLECTORS array contents for fn (restored in finally). */
+async function withCollectors<T>(swap: AdvisorCollector[], fn: () => Promise<T>): Promise<T> {
+ const saved = COLLECTORS.slice();
+ COLLECTORS.splice(0, COLLECTORS.length, ...swap);
+ try {
+ return await fn();
+ } finally {
+ COLLECTORS.splice(0, COLLECTORS.length, ...saved);
+ }
+}
+
+describe('runAdvisorCli collector failure (#6936: a failed check must not read healthy)', () => {
+ test('--json: a thrown collector → collector_failed warn finding, exit 1, no leaked error text', async () => {
+ await withEnv(hermeticEnv(), async () => {
+ const run = await withCollectors([throwingCollector, cleanCollector], () => runCaptured(fakeEngine(), ['--json']));
+ const report = parseReport(run.stdout);
+ expect(report.findings.map((f) => f.id)).toEqual(['collector_failed:throwing-check']);
+ expect(report.findings[0]!.fix.dispatch_id).toBeUndefined();
+ expect(report.worst).toBe('warn');
+ expect(run.exitCode).toBe(1);
+ const all = run.stdout + run.stderrLines.join('\n');
+ expect(all).not.toContain('hunter2');
+ expect(all).not.toContain('ECONNREFUSED');
+ expect(all).not.toContain('db.example.invalid');
+ });
+ });
+
+ test('human render: not healthy, names the failed check, exit 1, no leaked error text', async () => {
+ await withEnv(hermeticEnv(), async () => {
+ const run = await withCollectors([throwingCollector, cleanCollector], () => runCaptured(fakeEngine(), []));
+ expect(run.stdout).not.toContain('looks healthy');
+ expect(run.stdout).toContain('throwing-check');
+ expect(run.stdout).toContain('could not complete');
+ expect(run.exitCode).toBe(1);
+ const all = run.stdout + run.stderrLines.join('\n');
+ expect(all).not.toContain('hunter2');
+ expect(all).not.toContain('ECONNREFUSED');
+ });
+ });
+
+ test('critical from another collector still wins: worst critical, exit 2, failure also listed', async () => {
+ await withEnv(hermeticEnv(), async () => {
+ const run = await withCollectors([throwingCollector, criticalCollector], () => runCaptured(fakeEngine(), ['--json']));
+ const report = parseReport(run.stdout);
+ expect(report.findings.map((f) => f.id)).toEqual(['crit', 'collector_failed:throwing-check']);
+ expect(report.worst).toBe('critical');
+ expect(run.exitCode).toBe(2);
+ });
+ });
+
+ test('a clean run with no failures still exits 0 and renders healthy', async () => {
+ await withEnv(hermeticEnv(), async () => {
+ const human = await withCollectors([cleanCollector], () => runCaptured(fakeEngine(), []));
+ expect(human.stdout).toContain('looks healthy');
+ expect(human.exitCode).toBe(0);
+ const json = await withCollectors([cleanCollector], () => runCaptured(fakeEngine(), ['--json']));
+ expect(parseReport(json.stdout)).toMatchObject({ findings: [], worst: null });
+ expect(json.exitCode).toBe(0);
+ });
+ });
+
+ test('--apply can never run a collector_failed finding', async () => {
+ const spawnSpy = spyOn(childProcess, 'spawn');
+ try {
+ await withEnv({ ...hermeticEnv(), GBRAIN_NON_INTERACTIVE: '1' }, async () => {
+ const run = await withCollectors([throwingCollector], () =>
+ runCaptured(fakeEngine(), ['--apply', 'collector_failed:throwing-check', '--yes']),
+ );
+ expect(run.exitCode).toBe(2);
+ expect(run.stderrLines.join('\n')).toContain('No runnable finding');
+ expect(spawnSpy.mock.calls.length).toBe(0);
+ });
+ } finally {
+ spawnSpy.mockRestore();
+ }
+ });
+});
+
describe('runAdvisorCli --apply', () => {
test('C4: non-interactive without --yes → exit 3, consent payload names the command and its cost, nothing spawned', async () => {
const spawned: string[][] = [];
diff --git a/test/advisor-core.test.ts b/test/advisor-core.test.ts
index abf2b93846..7e023754c1 100644
--- a/test/advisor-core.test.ts
+++ b/test/advisor-core.test.ts
@@ -7,13 +7,13 @@ import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { rankFindings, runAdvisor } from '../src/core/advisor/run.ts';
+import { COLLECTORS, rankFindings, runAdvisor } from '../src/core/advisor/run.ts';
import { collectUsageShape } from '../src/core/advisor/collect-usage-shape.ts';
import { collectStalledJobs } from '../src/core/advisor/collect-stalled-jobs.ts';
import { collectSetupSmells } from '../src/core/advisor/collect-setup-smells.ts';
import { appendAdvisorRun, summarizeDeltas } from '../src/core/advisor/history.ts';
import { renderAdvisorReport } from '../src/core/advisor/render.ts';
-import type { AdvisorContext, AdvisorFinding, AdvisorReport } from '../src/core/advisor/types.ts';
+import type { AdvisorCollector, AdvisorContext, AdvisorFinding, AdvisorReport } from '../src/core/advisor/types.ts';
function finding(over: Partial<AdvisorFinding>): AdvisorFinding {
return {
@@ -82,6 +82,75 @@ describe('runAdvisor resilience', () => {
});
});
+const THROWN_SECRET = 'postgres://alice-example:[email protected]:5432/brain connect ECONNREFUSED';
+
+const throwingCollector: AdvisorCollector = {
+ id: 'throwing-check',
+ collect: async () => { throw new Error(THROWN_SECRET); },
+};
+const cleanCollector: AdvisorCollector = { id: 'clean-check', collect: async () => [] };
+const criticalCollector: AdvisorCollector = {
+ id: 'critical-check',
+ collect: async () => [finding({ id: 'crit', severity: 'critical', collector: 'critical-check' })],
+};
+
+/** Swap the shared COLLECTORS array contents for the duration of fn (restored in finally). */
+async function withCollectors<T>(swap: AdvisorCollector[], fn: () => Promise<T>): Promise<T> {
+ const saved = COLLECTORS.slice();
+ COLLECTORS.splice(0, COLLECTORS.length, ...swap);
+ try {
+ return await fn();
+ } finally {
+ COLLECTORS.splice(0, COLLECTORS.length, ...saved);
+ }
+}
+
+describe('runAdvisor collector failure (#6936)', () => {
+ test('a thrown collector is a warn finding, never a clean report', async () => {
+ const report = await withCollectors([throwingCollector, cleanCollector], () => runAdvisor(ctx({})));
+ expect(report.findings.map((f) => f.id)).toEqual(['collector_failed:throwing-check']);
+ const f = report.findings[0]!;
+ expect(f.severity).toBe('warn');
+ expect(f.collector).toBe('throwing-check');
+ expect(f.fix.command_argv).toBeNull();
+ expect(f.fix.dispatch_id).toBeUndefined();
+ expect(report.worst).toBe('warn');
+ });
+
+ test('the thrown message, stack and connection details never reach the report', async () => {
+ const report = await withCollectors([throwingCollector], () => runAdvisor(ctx({})));
+ const out = JSON.stringify(report) + renderAdvisorReport(report);
+ expect(out).not.toContain('hunter2');
+ expect(out).not.toContain('ECONNREFUSED');
+ expect(out).not.toContain('db.example.invalid');
+ expect(out).not.toContain('alice-example');
+ expect(out).not.toContain('Error:');
+ });
+
+ test('findings from unaffected collectors are kept and a critical still wins', async () => {
+ const report = await withCollectors([throwingCollector, criticalCollector], () => runAdvisor(ctx({})));
+ expect(report.findings.map((f) => f.id)).toEqual(['crit', 'collector_failed:throwing-check']);
+ expect(report.worst).toBe('critical');
+ });
+
+ test('a fully successful clean run still reports nothing', async () => {
+ const report = await withCollectors([cleanCollector], () => runAdvisor(ctx({})));
+ expect(report.findings).toEqual([]);
+ expect(report.worst).toBeNull();
+ });
+
+ test('remote runs still drop workspace-dependent findings and still report the failure', async () => {
+ const wd: AdvisorCollector = {
+ id: 'wd-check',
+ collect: async () => [finding({ id: 'wd', workspace_dependent: true, collector: 'wd-check' })],
+ };
+ const remote = await withCollectors([wd, throwingCollector], () => runAdvisor(ctx({}, { remote: true })));
+ expect(remote.findings.map((f) => f.id)).toEqual(['collector_failed:throwing-check']);
+ const local = await withCollectors([wd, throwingCollector], () => runAdvisor(ctx({}, { remote: false })));
+ expect(local.findings.map((f) => f.id).sort()).toEqual(['collector_failed:throwing-check', 'wd']);
+ });
+});
+
describe('collect-usage-shape', () => {
test('flags low embed coverage + orphans', async () => {
const engine = {
@@ -167,4 +236,14 @@ describe('renderAdvisorReport', () => {
const txt = renderAdvisorReport({ version: '0.43.0.0', generated_at: 'x', findings: [], worst: null });
expect(txt).toContain('looks healthy');
});
+
+ test('a failed collector is rendered as an incomplete check, never as healthy (#6936)', async () => {
+ const report = await withCollectors([throwingCollector], () => runAdvisor(ctx({})));
+ const txt = renderAdvisorReport(report);
+ expect(txt).not.toContain('looks healthy');
+ expect(txt).toContain('[WARN]');
+ expect(txt).toContain('throwing-check');
+ expect(txt).toContain('could not complete');
+ expect(txt).not.toContain('--apply <id>');
+ });
});
diff --git a/test/bounded-child-exec.test.ts b/test/bounded-child-exec.test.ts
index 5e009208d5..9afc828e2c 100644
--- a/test/bounded-child-exec.test.ts
+++ b/test/bounded-child-exec.test.ts
@@ -118,3 +118,23 @@ test('a stopped child gets SIGTERM first so it can remove its lockfile, then SIG
expect(stubborn.error).toMatchObject({ code: 'ETIMEDOUT', killed: true });
expect(performance.now() - started).toBeLessThan(5000);
});
+
+test('#6932: a caller-set termGraceMs lets a slow-to-clean-up child remove its lock before SIGKILL', async () => {
+ const lock = join(dir, 'slow-cleanup.lock');
+ const ready = join(dir, 'slow-cleanup.ready');
+ // Stands in for a git stalled in I/O: it acts on SIGTERM only after 3 seconds, past the default 2-second grace.
+ const script = `trap "sleep 3; rm -f '${lock}'; exit 143" TERM; touch '${lock}' '${ready}'; while :; do sleep 0.05; done`;
+ const stop = async (termGraceMs?: number) => {
+ rmSync(ready, { force: true });
+ const abort = new AbortController();
+ const running = execFileBounded('sh', ['-c', script], { timeout: 60_000, signal: abort.signal, ...(termGraceMs === undefined ? {} : { termGraceMs }) });
+ for (const deadline = performance.now() + 10_000; !(await Bun.file(ready).exists()) && performance.now() < deadline;) await Bun.sleep(20);
+ expect(await Bun.file(ready).exists()).toBe(true);
+ abort.abort();
+ expect((await running).error).toMatchObject({ code: 'ABORT_ERR', killed: true });
+ return Bun.file(lock).exists();
+ };
+ expect(await stop()).toBe(true);
+ rmSync(lock, { force: true });
+ expect(await stop(10_000)).toBe(false);
+}, 30_000);
diff --git a/test/persistence-index-lock-reclaim-6932.test.ts b/test/persistence-index-lock-reclaim-6932.test.ts
new file mode 100644
index 0000000000..0423abf91f
--- /dev/null
+++ b/test/persistence-index-lock-reclaim-6932.test.ts
@@ -0,0 +1,279 @@
+/**
+ * #6932: the canonical writer reclaims a Git index lock that provably belongs to no live process, and never one
+ * that a live process may own.
+ *
+ * Protects: a git step SIGKILLed after it created `index.lock` (a bounded step past its deadline, a job group
+ * killed after its grace, the OOM killer) left a 0-byte lock, and every later Git effect in that checkout
+ * reported git_index_locked, then git_index_stale, and parked until a person removed the lock. Now the writer,
+ * while it holds its writer lock, proves the lock abandoned (no process has it open, no git runs in the checkout,
+ * it is empty or stale) and reclaims it with a receipt; anything short of proof keeps the lock and names why.
+ * Seams: none for git. Real repositories, a real git killed with SIGKILL while it holds the lock (a clean
+ * filter that blocks inside `git add`), real live holders, a real native writer lock. Where this process
+ * cannot see the whole process table (macOS, a container, hidepid), the same cases assert the refusal instead.
+ */
+import { afterEach, expect, test } from 'bun:test';
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
+import { existsSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync, closeSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { commitGitTargets, gitStepTimeoutMs, INDEX_LOCK_GRACE_FOR_TESTS } from '../src/core/persistence/effect-git.ts';
+import { processTableBlind, readIndexLockReclaims, RECLAIM_MIN_AGE_MS } from '../src/core/persistence/index-lock-reclaim.ts';
+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';
+import { checkParkedEffects } from '../src/commands/doctor/checks/parked-effects.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { randomUUID } from 'node:crypto';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { durableGitRepo } from './helpers/git-publication.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+const blind = processTableBlind();
+const scratch: string[] = [];
+const children: ChildProcess[] = [];
+afterEach(() => {
+ for (const child of children.splice(0)) child.kill('SIGKILL');
+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function repo(): { root: string; home: string; lock: string } {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-reclaim-'));
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-reclaim-home-'));
+ scratch.push(root, home);
+ git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(root, 'a.md'), 'first\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');
+ writeFileSync(join(root, 'a.md'), 'second\n');
+ return { root, home, lock: join(root, '.git', 'index.lock') };
+}
+const age = (path: string, ms: number) => { const t = (Date.now() - ms) / 1000; utimesSync(path, t, t); };
+const until = async (done: () => boolean, ms = 20_000) => {
+ for (const deadline = Date.now() + ms; !done() && Date.now() < deadline;) await Bun.sleep(10);
+ expect(done()).toBe(true);
+};
+const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+
+async function writerLock(home: string) {
+ const lock = await tryAcquireNativeLock(join(home, 'writer.lock'));
+ expect(lock).not.toBeNull();
+ return lock!;
+}
+
+/**
+ * A real `git add` that creates the index lock and then blocks in a clean filter, so it holds an empty
+ * index.lock for as long as the test wants. Returns git's pid (the filter's parent) and the filter's.
+ */
+async function gitHoldingLock(root: string, lock: string): Promise<{ git: number; filter: number }> {
+ const pids = join(root, '.git', 'filter-pids');
+ git(root, 'config', 'filter.blocking.clean', `echo "$PPID $$" > '${pids}'; exec sleep 120`);
+ writeFileSync(join(root, '.git', 'info', 'attributes'), 'a.md filter=blocking\n');
+ const child = spawn('git', ['-C', root, 'add', 'a.md'], { stdio: 'ignore' });
+ children.push(child);
+ await until(() => existsSync(pids) && readFileSync(pids, 'utf8').trim().split(' ').length === 2);
+ const [gitPid, filterPid] = readFileSync(pids, 'utf8').trim().split(' ').map(Number);
+ expect(existsSync(lock)).toBe(true);
+ expect(statSync(lock).size).toBe(0);
+ return { git: gitPid!, filter: filterPid! };
+}
+function dropFilter(root: string) {
+ writeFileSync(join(root, '.git', 'info', 'attributes'), '');
+ git(root, 'config', '--unset', 'filter.blocking.clean');
+}
+
+test('probe: a git SIGKILLed while it holds the index lock leaves a 0-byte lock, and the writer reclaims it and commits', async () => {
+ const { root, home, lock } = repo();
+ const held = await gitHoldingLock(root, lock);
+ process.kill(held.git, 'SIGKILL');
+ process.kill(held.filter, 'SIGKILL');
+ await until(() => !alive(held.git) && !alive(held.filter));
+ dropFilter(root);
+ expect(existsSync(lock)).toBe(true);
+ expect(statSync(lock).size).toBe(0);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const writer = await writerLock(home);
+ const reclaims: unknown[] = [];
+ const owner = { writerLock: writer, onReclaim: (receipt: unknown) => { reclaims.push(receipt); } };
+ // A lock created moments ago may belong to a git that just started: it is waited out as contention.
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, owner)).rejects.toMatchObject({ code: 'git_index_locked' });
+ expect(existsSync(lock)).toBe(true);
+ age(lock, RECLAIM_MIN_AGE_MS + 1_000);
+ if (blind) {
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, owner)).rejects.toMatchObject({ code: 'git_index_locked' });
+ expect(existsSync(lock)).toBe(true);
+ expect(reclaims).toEqual([]);
+ } else {
+ expect((await commitGitTargets(root, ['a.md'], undefined, undefined, owner)).get('a.md')).toEqual({ git: 'committed' });
+ expect(existsSync(lock)).toBe(false);
+ expect(git(root, 'show', 'HEAD:a.md')).toBe('second\n');
+ expect(reclaims).toEqual([expect.objectContaining({ checkout: root, lock, size: 0 })]);
+ expect(readIndexLockReclaims()).toEqual([expect.objectContaining({ checkout: root, lock, size: 0, pid: process.pid })]);
+ const doctor = await checkParkedEffects({ executeRaw: async (sql: string) => sql.includes('COUNT(*)') ? [{ count: 0 }] : [] } as unknown as BrainEngine);
+ expect(doctor).toMatchObject({ status: 'ok', details: { parked_effects: 0, index_lock_reclaims: { last_7_days: 1, latest: { checkout: root, lock, size: 0 } } } });
+ expect(doctor.message).toContain('reclaimed 1 abandoned Git index lock(s) in the last 7 days');
+ }
+ await writer.release();
+ });
+}, 60_000);
+
+test('probe: a lock a live git holds is never reclaimed, however old, and the refusal names the live git', async () => {
+ const { root, home, lock } = repo();
+ const held = await gitHoldingLock(root, lock);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const writer = await writerLock(home);
+ const owner = { writerLock: writer };
+ age(lock, RECLAIM_MIN_AGE_MS + 30_000);
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, owner)).rejects.toMatchObject({ code: 'git_index_locked' });
+ expect(existsSync(lock)).toBe(true);
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ const stale = await commitGitTargets(root, ['a.md'], undefined, undefined, owner).catch(error => error);
+ expect(stale).toMatchObject({ code: 'git_index_stale', detail: lock,
+ suggestion: expect.stringContaining(blind ?? `process ${held.git} (git`),
+ fix: { ask_user: true, actor: 'user', user_message: expect.stringContaining(lock), verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] } } });
+ expect(existsSync(lock)).toBe(true);
+ expect(alive(held.git)).toBe(true);
+ expect(readIndexLockReclaims()).toEqual([]);
+ await writer.release();
+ });
+}, 60_000);
+
+test('probe: a lock any live process holds open is never reclaimed', async () => {
+ const { root, home, lock } = repo();
+ writeFileSync(lock, '');
+ const fd = openSync(lock, 'r');
+ const holder = spawn('sleep', ['120'], { stdio: [fd, 'ignore', 'ignore'] });
+ children.push(holder);
+ closeSync(fd);
+ await until(() => holder.pid !== undefined && existsSync(`/proc/${holder.pid}/fd/0`) || process.platform !== 'linux');
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const writer = await writerLock(home);
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: writer })).rejects.toMatchObject({ code: 'git_index_stale',
+ suggestion: expect.stringContaining(blind ?? `process ${holder.pid} (sleep) has the lock open`) });
+ expect(existsSync(lock)).toBe(true);
+ await writer.release();
+ });
+}, 60_000);
+
+test('probe: a live git running in the checkout, or pointed at it through GIT_DIR, blocks a reclaim even when no process has the lock open', async () => {
+ const { root, home, lock } = repo();
+ writeFileSync(lock, '');
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ const elsewhere = mkdtempSync(join(tmpdir(), 'gbrain-reclaim-elsewhere-'));
+ scratch.push(elsewhere);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const writer = await writerLock(home);
+ for (const [args, options] of [[['-C', root, 'hash-object', '--stdin'], {}], [['cat-file', '--batch'], { cwd: elsewhere, env: { ...process.env, GIT_DIR: join(root, '.git') } }]] as const) {
+ const live = spawn('git', [...args], { stdio: ['pipe', 'ignore', 'ignore'], ...options });
+ children.push(live);
+ await until(() => live.pid !== undefined && alive(live.pid));
+ await Bun.sleep(200);
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: writer })).rejects.toMatchObject({ code: 'git_index_stale',
+ suggestion: expect.stringContaining(blind ?? 'git process ') });
+ expect(existsSync(lock)).toBe(true);
+ live.kill('SIGKILL');
+ await until(() => !alive(live.pid!));
+ }
+ if (!blind) {
+ expect((await commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: writer })).get('a.md')).toEqual({ git: 'committed' });
+ expect(existsSync(lock)).toBe(false);
+ }
+ await writer.release();
+ });
+}, 60_000);
+
+test('without the writer lock, or with a lock that holds content and is not stale, nothing is reclaimed', async () => {
+ const { root, home, lock } = repo();
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ writeFileSync(lock, '');
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ const writer = await writerLock(home);
+ await writer.release();
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: writer })).rejects.toMatchObject({ code: 'git_index_stale',
+ suggestion: expect.stringContaining('does not hold the checkout\'s writer lock') });
+ await expect(commitGitTargets(root, ['a.md'])).rejects.toMatchObject({ code: 'git_index_stale' });
+ expect(existsSync(lock)).toBe(true);
+ writeFileSync(lock, 'partial index');
+ age(lock, RECLAIM_MIN_AGE_MS + 60_000);
+ const held = await writerLock(home);
+ await expect(commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: held })).rejects.toMatchObject({ code: 'git_index_locked' });
+ expect(readFileSync(lock, 'utf8')).toBe('partial index');
+ if (!blind) {
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ expect((await commitGitTargets(root, ['a.md'], undefined, undefined, { writerLock: held })).get('a.md')).toEqual({ git: 'committed' });
+ expect(existsSync(lock)).toBe(false);
+ }
+ await held.release();
+ });
+}, 60_000);
+
+test('a git step deadline grows with the index size, between 20 seconds and 2 minutes', () => {
+ const MiB = 1024 * 1024;
+ expect(gitStepTimeoutMs(0)).toBe(20_000);
+ expect(gitStepTimeoutMs(200 * 1024)).toBe(22_000);
+ expect(gitStepTimeoutMs(39 * MiB)).toBe(98_000);
+ expect(gitStepTimeoutMs(1024 * MiB)).toBe(120_000);
+});
+
+type GitEffect = { id: number; state: string; error_code: string | null; data: { parked?: { slug?: string; error_code: string }[] } };
+const gitEffect = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<GitEffect>(`SELECT e.id,e.state,e.error_code,e.data
+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND r.slug=$1`, [slug]))[0]!;
+const put = (ctx: OperationContext, slug: string) => submitPageMutation(ctx, { operation: 'put_page',
+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\nBody of ${slug}.\n` } });
+/** One writer pass over this effect alone, every other effect deferred. */
+async function runOnly(engine: BrainEngine, ctx: OperationContext, id: number) {
+ await disposePersistenceConsumer(engine);
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("UPDATE persistence_effects SET next_attempt_at=CASE WHEN id=$1 THEN now() ELSE now()+interval '1 hour' END", [id]);
+ });
+ await runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 1 });
+}
+
+test('probe: the writer recovers on its own: a Git effect parked by a held lock commits after the lock is abandoned and reclaimed', async () => {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ const lock = join(root, '.git', 'index.lock');
+ writeFileSync(lock, '');
+ age(lock, INDEX_LOCK_GRACE_FOR_TESTS + 60_000);
+ const fd = openSync(lock, 'r');
+ const holder = spawn('sleep', ['120'], { stdio: [fd, 'ignore', 'ignore'] });
+ children.push(holder);
+ closeSync(fd);
+ await put(ctx, 'notes/first');
+ const first = await gitEffect(engine, 'notes/first');
+ for (let i = 0; i < 10 && (await gitEffect(engine, 'notes/first')).state !== 'failed'; i++) await runOnly(engine, ctx, first.id);
+ // While a live process holds it, the lock parks the effect exactly as before: it is never removed.
+ expect(await gitEffect(engine, 'notes/first')).toMatchObject({ state: 'failed', error_code: 'targets_parked',
+ data: { parked: [{ slug: 'notes/first', error_code: 'git_index_stale' }] } });
+ expect(existsSync(lock)).toBe(true);
+ holder.kill('SIGKILL');
+ await until(() => !alive(holder.pid!));
+
+ // The holder is gone. The next write's Git effect proves the lock abandoned, reclaims it, commits, and
+ // gives the effect the lock had parked its one more attempt, with no operator step.
+ await put(ctx, 'notes/second');
+ const second = await gitEffect(engine, 'notes/second');
+ await runOnly(engine, ctx, second.id);
+ if (blind) {
+ expect(existsSync(lock)).toBe(true);
+ expect(await gitEffect(engine, 'notes/first')).toMatchObject({ state: 'failed', error_code: 'targets_parked' });
+ return;
+ }
+ expect(existsSync(lock)).toBe(false);
+ expect(await gitEffect(engine, 'notes/second')).toMatchObject({ state: 'committed', error_code: null });
+ expect(await gitEffect(engine, 'notes/first')).toMatchObject({ state: 'queued' });
+ await runOnly(engine, ctx, first.id);
+ expect(await gitEffect(engine, 'notes/first')).toMatchObject({ state: 'committed', error_code: null });
+ const log = git(root, 'log', '--name-only', '--pretty=format:');
+ expect(log).toContain('notes/first.md');
+ expect(log).toContain('notes/second.md');
+ expect(readIndexLockReclaims()).toEqual([expect.objectContaining({ lock, size: 0 })]);
+ const doctor = await checkParkedEffects(engine);
+ expect(doctor).toMatchObject({ status: 'ok', details: { parked_effects: 0, index_lock_reclaims: { last_7_days: 1 } } });
+ }, { setup: ({ root }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); } });
+}, 120_000);