Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): push a removal commit whose first push failed (#7089)

garrytanf8c18194a33d
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 6a95a5e929..93f0cdb299 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/extraction-input.ts` — `extraction_input_truncated` (large pages A7, BRAIN, registered after `fence_integrity`, before `search_mode`). Groups the live pages with an `input_truncated` receipt in `page_extraction_state` by pipeline and kind (`facts_backstop/head|tail_window`, `extract_atoms/head|tail_window`, `conversation_facts/skipped_too_large`) with three recent `source:slug` samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is `gbrain config set cycle.extract_atoms.max_input_chars <n>` (`ask_user`, consent `paid`), otherwise `fix_unavailable_reason: operator_judgement`. Facts-only receipts are `ok` with `severity: info`, `readiness_state: degraded` (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`, `test/conversation-facts-oversized-sidecar.test.ts`.
- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`. Wave B decision #10: `withSkippedSegmented(check, n)` (`src/commands/doctor/check-fix.ts`) adds `Check.skipped_segmented: n` and a `skipped (segmented): n` message tail (unchanged at n = 0) to every check whose scan reads whole bodies: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity` (segmented pages without a walked checkout file), `core_memory`, and `extract_health` via `readFactsReconcileBacklog`'s `skipped_segmented`; each count is one COUNT query that falls back to 0 on a schema without `body_storage`. Test: `test/large-pages/doctor-skipped-segmented.test.ts` (+ Postgres arm).
-- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
+- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (`stranded: true` in `details.roots`, #7089) with an agent fix `gbrain git commit-push --push-only --keep-checkout --path <root>` and verify `gbrain doctor --only git_convergence --json`; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `persistence-git-removal-push-7089.test.ts` (stranded roots, both engines), `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index c052c89555..d6c8c21a85 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -38,7 +38,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), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): 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). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). 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); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. 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/{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. That holds for a removal too (#7089): its retry finds the path untracked and absent (`target_absent`), and it joins the push while the root is ahead of its upstream (`gitRootAhead`, a local `rev-list @{upstream}..HEAD`, no upstream is not ahead), as does `publishGitEffect`, recording `target_absent` with the push result; on a root that is not ahead it completes without a push, so a down remote never parks it. A Git page walk that ends while its durable root is ahead pushes before completing (`test/persistence-git-removal-push-7089.test.ts` + Postgres wrapper). 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), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): 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). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). 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); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. 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/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index 0a9c71c6c9..2b878e98db 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -11,10 +11,15 @@
* older than 6 hours, never fail (they may be deliberate work in progress).
* Being behind is reported, not judged: sync pulls.
*
+ * #7089: a managed canonical checkout this host owns, with Git durability on,
+ * whose commits are not on the upstream while no Git effect of its worktree is
+ * queued, running or parked, warns at once (`stranded`): nothing will push
+ * them, so the fix pushes them with the keep-checkout publish.
+ *
* The same entry emits `tracked_ownership_marker` (#5186) for the same roots.
*/
import { execFileSync } from '../../../core/spawn.ts';
-import { statSync } from 'node:fs';
+import { realpathSync, statSync } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
@@ -22,6 +27,8 @@ import { parseSourceConfig } from '../../../core/sources-load.ts';
import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
import { isPhysicalRootMetadata } from '../../../core/persistence/root-metadata.ts';
import { isManagedFilesystemPath } from '../../../core/persistence/filesystem-guard.ts';
+import { existingLocalHostId } from '../../../core/persistence/identity.ts';
+import { gitDurabilityPolicy } from '../../../core/persistence/git-durability-policy.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { doctorVerify } from '../check-fix.ts';
@@ -32,7 +39,28 @@ const MAX_ROOTS = 50;
const MAX_DIRTY_PATHS = 200;
interface RootReport { root: string; source_ids: string[]; branch: string | null; ahead: number; behind: number; dirty: number;
- oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail' }
+ oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail'; stranded?: true }
+
+const canonicalPath = (path: string) => { try { return realpathSync(path); } catch { return path; } };
+
+/**
+ * #7089: the canonical checkouts this host owns with Git durability on and no Git effect of their worktree queued,
+ * running or parked: commits there that are not on the upstream have no effect left to push them.
+ */
+async function unwatchedDurableRoots(engine: BrainEngine): Promise<Set<string>> {
+ const hostId = existingLocalHostId();
+ if (!hostId) return new Set();
+ const bindings = await engine.executeRaw<{ local_path: string; git_durability: 'enabled' | 'disabled' | null }>(
+ `SELECT h.local_path,h.git_durability FROM persistence_host_bindings h WHERE h.host_id=$1::uuid AND NOT EXISTS (
+ SELECT 1 FROM persistence_effects e WHERE e.worktree_id=h.worktree_id AND e.kind='git' AND e.state IN ('queued','running','failed'))`,
+ [hostId]).catch(() => []);
+ const roots = new Set<string>();
+ for (const binding of bindings) {
+ const durable = await gitDurabilityPolicy(binding, binding.local_path).then(policy => policy.durable, () => false);
+ if (durable) roots.add(canonicalPath(binding.local_path));
+ }
+ return roots;
+}
function git(root: string, args: string[]): string | null {
try { return execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: GIT_TIMEOUT_MS }).toString(); }
@@ -88,6 +116,12 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
byTop.set(report.root, prior ? { ...prior, source_ids: [...prior.source_ids, ...ids] } : report);
}
const reports = [...byTop.values()].filter((r): r is RootReport => !('skipped' in r));
+ const unwatched = reports.some(r => r.ahead > 0) ? await unwatchedDurableRoots(engine) : new Set<string>();
+ for (const report of reports) {
+ if (report.ahead === 0 || !unwatched.has(canonicalPath(report.root))) continue;
+ report.stranded = true;
+ if (report.status === 'ok') report.status = 'warn';
+ }
const skipped = [...byTop.values()].filter((r): r is { root: string; source_ids: string[]; skipped: string } => 'skipped' in r);
const details = { roots: reports, skipped, ...(roots.size > MAX_ROOTS ? { not_probed: roots.size - MAX_ROOTS } : {}),
warn_after_hours: GIT_CONVERGENCE_WARN_MS / 3_600_000, fail_after_hours: GIT_CONVERGENCE_FAIL_MS / 3_600_000, fetched: false };
@@ -104,7 +138,17 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const remedy = bad.some(r => isManagedFilesystemPath(r.root))
? 'Commit and push them: on a managed canonical worktree the persistence owner commits and pushes page writes (gbrain sources writer status <source> --json shows parked pushes; gbrain sources writer git-durability <source> --enable turns them on), and files that are not pages are committed and pushed with plain git in the checkout, never pulled or rebased; elsewhere gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout'
: 'Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout)';
- return { name: 'git_convergence', status: bad.some(r => r.status === 'fail') ? 'fail' : 'warn', details,
+ const stranded = bad.filter(r => r.stranded);
+ const status = bad.some(r => r.status === 'fail') ? 'fail' : 'warn';
+ if (stranded.length) {
+ const first = stranded[0]!;
+ return { name: 'git_convergence', status, details,
+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${stranded.map(r => r.root).join(', ')} ${stranded.length === 1 ? 'is a managed checkout' : 'are managed checkouts'} with Git durability on and no Git effect queued, running or parked, so no effect will push ${stranded.length === 1 ? 'its' : 'their'} commits; push them with the keep-checkout publish, which merges a moved remote in memory and never moves the checkout. ${remedy}; this compares with the last fetched upstream and does not fetch.`,
+ fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', first.root], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `${first.root} has ${first.ahead} commit(s) not on its upstream and no Git effect left to push them (#7089); this publishes the commits already on the branch and commits nothing. A conflict with the remote is reported with the user's choice as its fix.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) need the same, see details.roots (stranded).` : ''}`,
+ verify: doctorVerify('git_convergence') } };
+ }
+ return { name: 'git_convergence', status, details,
message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${remedy}; this compares with the last fetched upstream and does not fetch.` };
}
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index d9b5b59582..14fbe895b0 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -299,6 +299,18 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
return results;
}
+/**
+ * #7089: whether `root`'s branch has commits its upstream (the local remote-tracking ref, never fetched) lacks; false
+ * without an upstream. A Git effect whose target is absent asks this before completing: its removal may have been
+ * committed by an earlier attempt whose push failed, and only a root that is ahead owes a push.
+ */
+export async function gitRootAhead(root: string, signal?: AbortSignal): Promise<boolean> {
+ return withSession(root, signal, undefined, false, async session => {
+ const count = await git(session, ['rev-list', '--count', '@{upstream}..HEAD']);
+ return count.code === 0 && Number(count.stdout.trim()) > 0;
+ });
+}
+
/** Git's refusal of a push because the remote branch moved (LC_ALL=C keeps it untranslated). */
const NON_FAST_FORWARD = /\[rejected\][^\n]*\((?:non-fast-forward|fetch first)\)/;
@@ -385,13 +397,16 @@ export const DURABILITY_NOT_ENABLED = { git: 'skipped', reason: 'durability_not_
* locked the worktree. Without one, the binding's recorded git_durability
* decides (#5182): `enabled`/`disabled` never consult the legacy hook probe,
* and an unrecorded binding falls back to the probe, fail-closed.
+ * #7089: an absent target pushes when the root is ahead of its upstream (an
+ * earlier attempt may have committed its removal and failed to push); on a
+ * root that is not ahead it completes without a push, as before.
*/
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,
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, owner)).get(relativePath)!;
if (outcome instanceof OperationError) throw outcome;
- if (outcome.reason === 'target_absent') return outcome;
+ if (outcome.reason === 'target_absent' && !(await gitRootAhead(root, signal))) return outcome;
const pushed = await pushGitRoot(root, signal);
- return { git: outcome.git, ...pushed };
+ return { ...outcome, ...pushed };
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 4dbebffaec..99a9a6ee15 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -38,7 +38,7 @@ import { atomicStagingPath } from '../atomic-write.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimKeeper, failEffect, hasRearmableTargets, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';
import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';
-import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';
+import { commitGitTargets, DURABILITY_NOT_ENABLED, gitRootAhead, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';
import { retryIndexLockParks } from './effect-retry.ts';
import { assertSegmentedMirrorGate, resumeGatedMirrors } from './segmented-mirror-gate.ts';
import { gitDurabilityPolicy } from './git-durability-policy.ts';
@@ -327,7 +327,13 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, bi
}
// Only a page walk reads snapshots; a single-file effect completes by its recorded hash.
const snapshot = await selectedEffectPage(engine, effect);
- if (!snapshot) { await completeEffect(engine, effect); return; }
+ if (!snapshot) {
+ // #7089: a page an earlier attempt committed but failed to push may since have been skipped (its file removed or
+ // edited), so a walk that ends while the root is ahead of its upstream pushes before it completes.
+ const durable = hardened ?? (await gitDurabilityPolicy(binding, root)).durable;
+ await completeEffect(engine, effect, durable && await gitRootAhead(root, opts.signal) ? await pushGitRoot(root, opts.signal) : {});
+ return;
+ }
attempt.target = snapshot.page.slug;
const verdict = await mirrorVerdict(engine, effect, attempt, snapshot.page.slug);
if (verdict === 'handled') return;
@@ -813,7 +819,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
type DurabilityProbe = { durable: boolean } | { error: unknown };
const probes = new Map<string, Promise<DurabilityProbe>>();
const deferred: { effects: PersistenceEffect[]; binding: WorktreeBinding; hardened: Promise<DurabilityProbe> }[] = [];
- const unpushed = new Map<string, { binding: WorktreeBinding; items: { effect: PersistenceEffect; git: string; target?: string }[] }>();
+ const unpushed = new Map<string, { binding: WorktreeBinding; items: { effect: PersistenceEffect; outcome: Record<string, unknown>; target?: string }[] }>();
const commitGroup = async (effects: PersistenceEffect[], binding: WorktreeBinding & { local_path: string }) => {
// A group yields to publications still queued for its worktree: a serial
// producer (the grandfather step) publishes ahead and its Git work arrives
@@ -866,11 +872,15 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
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: [] };
+ // #7089: an absent target whose removal an earlier attempt committed (its push failed) joins the push like an
+ // unchanged one while the root is ahead of its upstream; on a root that is not ahead it completes without a push.
+ const ahead = [...outcomes.values()].some(outcome => !(outcome instanceof OperationError) && outcome.reason === 'target_absent')
+ && await gitRootAhead(binding.local_path, opts.signal);
for (const { effect, path, attempt } of targets) {
const outcome = outcomes.get(path)!;
if (outcome instanceof OperationError) await recordFailure(engine, effect, outcome, opts.signal, attempt.target);
- else if (outcome.reason === 'target_absent') await completeEffect(engine, effect, outcome);
- else pending.items.push({ effect, git: outcome.git, target: attempt.target });
+ else if (outcome.reason === 'target_absent' && !ahead) await completeEffect(engine, effect, outcome);
+ else pending.items.push({ effect, outcome, target: attempt.target });
}
if (pending.items.length) unpushed.set(binding.local_path, pending);
} catch (error) {
@@ -985,10 +995,10 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
if (!lock) throw writerBusy(items[0]!.effect);
pushed = await pushGitRoot(root, opts.signal);
} catch (error) { failure = error; } finally { await lock?.release(); }
- for (const { effect, git, target } of items) {
+ for (const { effect, outcome, target } of items) {
try {
if (!pushed) throw failure;
- await completeEffect(engine, effect, { git, ...pushed });
+ await completeEffect(engine, effect, { ...outcome, ...pushed });
} catch (error) { await recordFailure(engine, effect, error, opts.signal, target); }
}
}
diff --git a/test/e2e/persistence-git-removal-push-7089-postgres.test.ts b/test/e2e/persistence-git-removal-push-7089-postgres.test.ts
new file mode 100644
index 0000000000..d4276632ab
--- /dev/null
+++ b/test/e2e/persistence-git-removal-push-7089-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-git-removal-push-7089.test.ts'));
diff --git a/test/persistence-git-removal-push-7089.test.ts b/test/persistence-git-removal-push-7089.test.ts
new file mode 100644
index 0000000000..8aa62988c7
--- /dev/null
+++ b/test/persistence-git-removal-push-7089.test.ts
@@ -0,0 +1,159 @@
+/**
+ * #7089: a page delete's removal commit must reach the remote even when its first push fails.
+ *
+ * The grouped runner commits the removal and queues its Git effect on the end-of-pass push; a push failure
+ * requeues the effect. On master the retry found the removed path untracked and absent (`target_absent`) and
+ * completed the effect without pushing, so the removal commit stayed local while writer status and doctor
+ * reported nothing pending. Now an absent target joins the push while the root is ahead of its upstream, a
+ * page walk that ends on such a root pushes, and doctor `git_convergence` warns at once about a durable managed
+ * checkout that is ahead with no Git effect left to push it.
+ *
+ * PGLite here; Postgres through test/e2e/persistence-git-removal-push-7089-postgres.test.ts.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { publishGitEffect } from '../src/core/persistence/effect-git.ts';
+import { gitConvergenceCheck } from '../src/commands/doctor/checks/git-convergence.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { type Repo, bindSource, createGitCoalescingFixture, effectSql, git, harden, pageSlug, pass, pauseGitEffects, putPage, release } from './helpers/git-coalescing-fixture.ts';
+
+const { makeRepo, withBrain, dispose } = createGitCoalescingFixture('7089');
+afterAll(dispose);
+
+const head = (repo: Repo) => git(repo.root, 'rev-parse', 'HEAD').trim();
+const remoteHead = (repo: Repo) => git(repo.root, 'ls-remote', 'origin', 'refs/heads/main').split('\t')[0]!.trim();
+const latestGitEffect = async (engine: BrainEngine) => (await engine.executeRaw<{ id: string; state: string; error_code: string | null; outcome: Record<string, unknown> | null }>(
+ "SELECT id::text AS id, state, error_code, outcome FROM persistence_effects WHERE kind='git' ORDER BY id DESC LIMIT 1"))[0]!;
+
+async function managedRepo(engine: BrainEngine, home: string): Promise<Repo> {
+ const repo = makeRepo(home, 'content');
+ await bindSource(engine, 'default', repo);
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ harden(repo);
+ return repo;
+}
+
+/** Put page 1 and push it, then delete it with every push refused: the removal is committed locally and its effect requeued. */
+async function deleteWithRefusedPush(engine: BrainEngine, repo: Repo, ctx: OperationContext): Promise<string> {
+ await pauseGitEffects(engine, () => putPage(ctx, 1));
+ await release(engine);
+ await pass(engine);
+ expect(remoteHead(repo)).toBe(head(repo));
+ const snapshot = await engine.readPageSnapshot(pageSlug(1), { sourceId: 'default' });
+ await pauseGitEffects(engine, () => submitPageMutation(ctx, { operation: 'delete_page',
+ params: { slug: pageSlug(1), expected_revision: snapshot!.revision, request_id: randomUUID() } }));
+ expect(existsSync(join(repo.root, `${pageSlug(1)}.md`))).toBe(false);
+ repo.rejectPushes(true);
+ await release(engine);
+ await pass(engine);
+ expect(git(repo.root, 'log', '-1', '--name-status', '--format=').trim()).toBe(`D\t${pageSlug(1)}.md`);
+ expect(remoteHead(repo)).not.toBe(head(repo));
+ const removal = await latestGitEffect(engine);
+ expect(removal).toMatchObject({ state: 'queued', error_code: 'git_push_unavailable' });
+ return removal.id;
+}
+
+const localCommit = (repo: Repo) => {
+ writeFileSync(join(repo.root, 'local.md'), 'local\n');
+ git(repo.root, 'add', 'local.md'); git(repo.root, 'commit', '-q', '-m', 'Local commit');
+};
+
+for (const kind of testBackends()) describe(`#7089 removal commits are pushed on retry (${kind})`, () => {
+ if (kind === 'postgres') process.env.GBRAIN_TEST_COALESCE_PG ??= process.env.DATABASE_URL;
+
+ test('a removal whose first push failed is pushed by the next pass and records the push, never a silent skip', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const repo = await managedRepo(engine, home);
+ const id = await deleteWithRefusedPush(engine, repo, ctx('default'));
+ repo.rejectPushes(false);
+ const pushes = repo.pushes();
+ await release(engine);
+ await pass(engine);
+ expect(repo.pushes()).toBe(pushes + 1);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(await latestGitEffect(engine)).toMatchObject({ id, state: 'committed', outcome: { git: 'skipped', reason: 'target_absent', push: 'committed' } });
+ }), 300_000);
+
+ test('while the push keeps failing the removal stays queued with the push code, then pushes once the remote is back', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const repo = await managedRepo(engine, home);
+ const id = await deleteWithRefusedPush(engine, repo, ctx('default'));
+ await release(engine);
+ await pass(engine);
+ expect(await latestGitEffect(engine)).toMatchObject({ id, state: 'queued', error_code: 'git_push_unavailable' });
+ expect(remoteHead(repo)).not.toBe(head(repo));
+ repo.rejectPushes(false);
+ await release(engine);
+ await pass(engine);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(await latestGitEffect(engine)).toMatchObject({ id, state: 'committed', outcome: { push: 'committed' } });
+ }), 300_000);
+
+ test('an absent target on a root that is not ahead completes without a push attempt, even with the remote down', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const repo = await managedRepo(engine, home);
+ const id = await deleteWithRefusedPush(engine, repo, ctx('default'));
+ repo.rejectPushes(false);
+ git(repo.root, 'push', '-q');
+ expect(remoteHead(repo)).toBe(head(repo));
+ repo.rejectPushes(true);
+ const pushes = repo.pushes();
+ await release(engine);
+ await pass(engine);
+ expect(repo.pushes()).toBe(pushes);
+ expect(await latestGitEffect(engine)).toMatchObject({ id, state: 'committed', outcome: { git: 'skipped', reason: 'target_absent', push: 'skipped' } });
+ }), 300_000);
+
+ test('a Git page walk that ends while the root is ahead pushes before it completes', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const repo = await managedRepo(engine, home);
+ await pauseGitEffects(engine, () => putPage(ctx('default'), 2));
+ const walk = await latestGitEffect(engine);
+ await effectSql(engine, `UPDATE persistence_effects SET data=data||'{"source_scan":true,"after_slug":"zzzz"}'::jsonb WHERE id=$1`, [walk.id]);
+ localCommit(repo);
+ expect(remoteHead(repo)).not.toBe(head(repo));
+ await release(engine);
+ await pass(engine);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(await latestGitEffect(engine)).toMatchObject({ id: walk.id, state: 'committed', outcome: { push: 'committed' } });
+ }), 300_000);
+
+ test('doctor git_convergence warns at once about a durable managed checkout ahead with no Git effect to push it', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const repo = await managedRepo(engine, home);
+ expect((await gitConvergenceCheck(engine))?.status).toBe('ok');
+ localCommit(repo);
+ const check = await gitConvergenceCheck(engine);
+ expect(check).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', repo.root],
+ actor: 'agent', verify: { argv: expect.arrayContaining(['doctor', 'git_convergence']) } } });
+ expect(check!.message).toContain('no Git effect queued, running or parked');
+ expect((check!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: repo.root, ahead: 1, stranded: true })]);
+
+ await pauseGitEffects(engine, () => putPage(ctx('default'), 3));
+ const pending = await gitConvergenceCheck(engine);
+ expect(pending?.status).toBe('ok');
+ expect((pending!.details as { roots: Array<{ stranded?: boolean }> }).roots[0]!.stranded).toBeUndefined();
+
+ await release(engine);
+ await pass(engine);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect((await gitConvergenceCheck(engine))?.status).toBe('ok');
+ }), 300_000);
+});
+
+if (testBackends().includes('pglite')) describe('#7089 publishGitEffect on an absent target', () => {
+ test('pushes a removal an earlier attempt committed while the root is ahead, and pushes nothing when it is not', () => withBrain('pglite', async ({ home }) => {
+ const repo = makeRepo(home, 'single');
+ harden(repo);
+ writeFileSync(join(repo.root, 'gone.md'), 'gone\n');
+ git(repo.root, 'add', 'gone.md'); git(repo.root, 'commit', '-q', '-m', 'Add'); git(repo.root, 'push', '-q');
+ git(repo.root, 'rm', '-q', 'gone.md'); git(repo.root, 'commit', '-q', '-m', 'Remove');
+ const pushes = repo.pushes();
+ expect(await publishGitEffect(repo.root, 'gone.md', undefined, true)).toEqual({ git: 'skipped', reason: 'target_absent', push: 'committed' });
+ expect(repo.pushes()).toBe(pushes + 1);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(await publishGitEffect(repo.root, 'gone.md', undefined, true)).toEqual({ git: 'skipped', reason: 'target_absent', push: 'skipped' });
+ expect(repo.pushes()).toBe(pushes + 1);
+ }), 120_000);
+});