Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): settle Git effects no retry can move, on proof; retry failed current pushes

garrytanf087e9546d75
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index fcc14e8bd3..1e90340dc2 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -4,6 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The #6188 fence check and fence repair live in [fence repair](core-fence-repair.md). Managed connector ingestion, connector item holds and the no-op kernel (checkpoint validation and the fault seams: [request indexes and fault seams](core-persistence-request-indexes.md)). Also the persistence verb types and errors, database-write and manual links, write attribution and loop-fact retirement; the managed purge of deleted pages is under [memory purge](memory-purge.md).
+- `src/core/persistence/effect-settle.ts` — `gbrain sources writer settle-effects <source> (--request-id|--parked-code) [--unsettle] [--dry-run|--apply --expect <plan_hash>]` (`writer_settle_effects`, an administration extension) (#7423, #7378): records `data.settled` (and appends to `data.settlements`) on a failed Git effect no retry can move, never touching its failure, parked targets, request or bytes. It settles only on an exact-target proof re-checked under row locks at apply: each target declared `db_only` in the current binding's gbrain.yml (`sourceDbOnlyDir`), or, for an effect `guardEffectSource` refuses `source_changed` because the source moved to a new worktree (same incarnation, this host owning the active binding), a later committed and pushed Git effect of the current worktree whose `expected_hash` equals the canonical file now and a blob at the already-fetched `@{upstream}` equal to it (no fetch). Withdrawal effects, claims, open recovery records, revoked writers, replaced sources and unknown targets refuse; an effect of the current binding that is not db_only refuses `retry_instead`. The plan hash is doctor --remediate's `computePlanHash` over the brain, source, selector, owner epoch and each proof (`preview_changed` otherwise). Readers that skip settled rows: doctor `parked_effects`, `readParkedGroups`, `readGitPushHolds`, `retryParkedPushes`/`--parked-code`, `retryIndexLockParks`, `sync status`, `failedEffectHistory`; `retryParkedEffects` reports a settled effect as `action: settled`. `retryParkedPushes` also reaches a push that failed without parked targets (#7378, `failedCodes`). Tests: `test/persistence-effect-settle.test.ts` (scenarios in `test/helpers/effect-settle-scenarios.ts`) + the Postgres arm in `test/e2e/w5-persistence-postgres.test.ts`.
- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 7a8a63604f..6ec1682538 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -12,7 +12,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).
- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.
-- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.
+- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). A hold in a worktree the source is no longer bound to is `former_worktree` and its fix is the settle preview (#7378). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.
- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).
- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`): a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v259). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 8ea8292c74..d13735f37a 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -79,7 +79,7 @@ of making a duplicate.
| <a id="segmented_mirror_writer_gate"></a>`segmented_mirror_writer_gate` | effect `error_code`, then the parked target's code (`targets_parked`) | A withdrawal (`forget`, `forget_fact`, `purge_fact`) on a page stored in segments committed, but a gbrain older than the segmented writer floor that doctor `segmented_storage` still warns about wrote to the brain in the last 7 days: another host, an older `serve` or worker still running on this host, or an older write this build has not matched (doctor names the host and when the hold clears). This host's own writes from before it upgraded, once the upgraded build has made the same kind of write after them (doctor's information case), keep `pages.segmented_storage` off but do not hold the mirror. Its mirror would write a version 2 recovery record that gbrain cannot read (v0.60.290.0 wedges the worktree on it, see [`recovery_version_unsupported`](#recovery_version_unsupported)), so it wrote nothing: the canonical file keeps the withdrawn row, the withdrawal's Git effect waits, and the mirror retries and parks after five attempts like any failed target, so writes on the worktree go on. The refusal names each older host with its version, the kind of write and when it was last seen. | `fix.next` is `tell_user_to_run` `gbrain upgrade` on the named hosts (and a restart of their serve, sync or worker processes). Once those hosts are upgraded and their older writes are 7 days old, the owner retries the parked mirror by itself (checked at most once a minute); the file loses the row and the Git effect commits it. `gbrain sources writer retry-effects <source> --request-id <request>` retries it sooner; it parks again while the hold lasts. |
| `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). 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. |
+| `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 target no retry can move (declared `db_only` since, or left in a former canonical worktree) is [settled on proof](#settle-effects) instead. |
| <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. |
@@ -185,6 +185,35 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the
`gbrain config set` value to use; outstanding-request, queued-byte and
recovery-byte limits can refuse writes without that warning.
+<a id="settle-effects"></a>
+**A parked or failed Git effect no retry can ever move** (#7423, #7378): the
+target's prefix was declared `db_only` after the effect was queued, so every
+retry parks it again; or the effect belongs to a former canonical worktree (the
+source was moved with set-path or a transfer), so `retry-effects --request-id`
+refuses it `source_changed` and `--parked-pushes`, which only reaches the current
+worktree, previews nothing (it now names those effects under `former_worktree`,
+and doctor's `git_push_holds` fix for them is the settle preview). Do not claim
+or transfer the source to force the old effect through. Settle it on proof
+instead: preview with `gbrain sources writer settle-effects <source> --parked-code
+<code> --dry-run` (or `--request-id <id>`), show the user each effect's proof, and
+after they agree run the printed `apply_command` (`--apply --expect <plan_hash>`;
+a changed plan refuses `preview_changed`). An effect settles only when each
+target is declared `db_only` in the current gbrain.yml (proof `db_only`), or, for a
+former-worktree effect, a later Git effect of the current worktree committed and
+pushed the bytes the canonical file holds now and the already-fetched
+remote-tracking ref of the checkout's branch holds exactly those bytes at that
+path (proof `superseded_remote`; nothing is fetched). Each other effect is listed
+with its refusal: `retry_instead` (current binding: retry it),
+`no_covering_receipt` (write the page through gbrain first), `bytes_unpushed`,
+`remote_ref_missing` or `remote_ref_stale` (fetch in the checkout, then preview
+again), `content_changed`, `content_missing`, `unknown_target`, `withdrawal_effect`
+(never settled), `recovery_open`, `claimed`, `authority_changed`, `source_replaced` and
+`owner_unavailable`. A settlement is recorded on the effect (`data.settled`, every
+settle and unsettle appended to `data.settlements`); its failure, request, intent
+and target bytes are kept. Doctor `parked_effects`, writer status, the bulk retries
+and `sync status` skip settled effects. `--unsettle` with the same selector
+previews, and with `--apply --expect` reverses, a settlement.
+
<a id="held-files-and-content-refusals"></a>
## Held files and content refusals
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index c7191e8395..fee3fc5903 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -61,7 +61,7 @@ async function unwatchedDurableRoots(engine: BrainEngine): Promise<Map<string, s
(SELECT array_agg(b.relative_path) FROM persistence_source_bindings b WHERE b.worktree_id=h.worktree_id) AS relative_paths
FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id
WHERE h.host_id=$1::uuid AND w.owner_host_id=$1::uuid AND w.state='active' 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'))`,
+ SELECT 1 FROM persistence_effects e WHERE e.worktree_id=h.worktree_id AND e.kind='git' AND e.state IN ('queued','running','failed') AND NOT (e.data ? 'settled'))`,
[hostId]).catch(() => []);
const roots = new Map<string, string[]>();
for (const binding of bindings) {
diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.ts
index d81836eeae..71d467f779 100644
--- a/src/commands/doctor/checks/parked-effects.ts
+++ b/src/commands/doctor/checks/parked-effects.ts
@@ -42,10 +42,11 @@ const SAMPLE = 20;
* #5612: Git and withdrawal targets that failed five consecutive times are
* parked instead of retried forever. Reads the partial `persistence_effects_parked`
* index: an exact count plus a capped sample naming each page and its retry command.
+ * Settled effects (#7423, #7378: `gbrain sources writer settle-effects`) are history and not counted.
*/
export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
try {
- const scoped = sourceIds ? ' AND e.source_id=ANY($1::text[])' : '';
+ const scoped = `${sourceIds ? ' AND e.source_id=ANY($1::text[])' : ''} AND NOT (e.data ? 'settled')`;
const params = sourceIds ? [sourceIds] : [];
const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects e WHERE e.data ? 'parked'${scoped}`, params);
const rows = await engine.executeRaw<{ request: WriteRequest; source_id: string; kind: string; state: string; parked: ParkedTarget[] }>(
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 680427ff09..d538527cd8 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -22,6 +22,7 @@ export const WRITER_HELP = `Usage:
gbrain sources writer retry-effects <source> --request-id <uuid> [--admin-intent writer_retry_effects --expected-state <admin_state>] [--dry-run] [--json]
gbrain sources writer retry-effects <source> --parked-pushes [--dry-run] [--json]
gbrain sources writer retry-effects <source> --parked-code <code> [--dry-run] [--json]
+ gbrain sources writer settle-effects <source> --request-id <uuid>|--parked-code <code> [--unsettle] [--dry-run | --apply --expect <plan_hash>] [--json]
gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [administration options] [--dry-run] [--json]
gbrain sources writer claim <source> --path <directory> [administration options] [--dry-run] [--json]
gbrain sources writer activate --confirm-quiesced [--cleanup-dead-local-locks] [--shared-skills] [administration options] [--dry-run] [--json]
@@ -103,6 +104,12 @@ retry-effects <source> --parked-code <code> gives one more attempt to every Git
source's worktree with a target parked on that code; doctor parked_effects and writer status list
each parked code with its command. A target a .gitignore rule excludes parks at once as
git_target_ignored, naming the rule: change the rule first, or the retry parks it again.
+settle-effects records a settled disposition on Git effects a retry can never move, only on an
+exact-target proof: the target is now declared db_only in gbrain.yml, or the effect belongs to a
+former canonical worktree and the fetched remote branch holds the current bytes a later pushed Git
+effect wrote (nothing is fetched). The failure, request and target bytes are kept; doctor and
+retries skip settled effects. Preview first; --apply needs the preview's --expect <plan_hash>.
+--unsettle (previewed and plan-bound the same way) reverses a settlement; both stay in history.
lock sets an opt-in, brain-level writer admin lock (config key persistence.writer_admin_lock)
and unlock clears it; both are local-only, idempotent and print the resulting state.
While locked, writer claim, activate and transfer (prepare, accept and cancel) are refused with
@@ -144,7 +151,7 @@ export function adminHostConfig<T extends GBrainConfig>(config: T | null | undef
type Group = 'writer' | 'local-writer';
const GROUP_ARGV: Record<Group, string[]> = { writer: ['gbrain', 'sources', 'writer'], 'local-writer': ['gbrain', 'auth', 'local-writer'] };
-const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--confirm-relocated-root', '--cleanup-dead-local-locks', '--shared-skills', '--enable', '--disable', '--parked-pushes'];
+const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--confirm-relocated-root', '--cleanup-dead-local-locks', '--shared-skills', '--enable', '--disable', '--parked-pushes', '--apply', '--unsettle'];
/** A CLI usage refusal: the exact usage in the suggestion, the group's help as the read-only fix. */
function invalid(group: Group, message: string, suggestion: string) {
return opError('invalid_params', message, suggestion, {
@@ -162,7 +169,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
'--source-ids': 'source_ids', '--scopes': 'scopes', '--allowed-operations': 'allowed_operations',
'--slug-prefixes': 'slug_prefixes', '--limit': 'limit', '--before': 'before',
'--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id', '--pat-file': 'pat_file', '--parked-code': 'parked_code',
- '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category',
+ '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category', '--expect': 'expect',
};
const arrays = new Set(['source_ids', 'scopes', 'allowed_operations', 'slug_prefixes']);
const seen = new Set<string>();
@@ -195,6 +202,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (verb === 'status') operation = 'writer_status';
else if (verb === 'failures') operation = 'writer_failures';
else if (verb === 'retry-effects') operation = 'writer_retry_effects';
+ else if (verb === 'settle-effects') operation = 'writer_settle_effects';
else if (verb === 'git-durability') operation = 'writer_git_durability';
else if (verb === 'claim') operation = 'writer_claim';
else if (verb === 'activate') operation = 'writer_activate';
@@ -206,7 +214,7 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (phase !== 'prepare' && phase !== 'accept' && phase !== 'cancel') throw invalid(group, 'Transfer requires prepare or accept (or cancel, which ends a prepared transfer).',
'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed; gbrain sources writer transfer cancel <source> --expected-epoch <n> on the owner host ends a transfer nobody will accept.');
operation = phase === 'prepare' ? 'writer_transfer_prepare' : phase === 'accept' ? 'writer_transfer_accept' : 'writer_transfer_cancel';
- } else throw invalid(group, 'Writer administration requires status, failures, movement, retry-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
+ } else throw invalid(group, 'Writer administration requires status, failures, movement, retry-effects, settle-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
`Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);
const source = positional.shift();
if (source !== undefined) {
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index fde20210b6..b991035336 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],
'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],
- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--apply', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],
@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.ts
index f8ab4c0f8d..b26718769b 100644
--- a/src/core/persistence/admin-contract.ts
+++ b/src/core/persistence/admin-contract.ts
@@ -16,7 +16,7 @@ export const PERSISTENCE_ADMIN_OPERATIONS = [
* added there: the owner advertises it in `administration_extensions`, which older clients ignore, and a client calls
* one only when the owner lists it.
*/
-export const PERSISTENCE_ADMIN_EXTENSIONS = ['writer_failures', 'writer_transfer_cancel'] as const;
+export const PERSISTENCE_ADMIN_EXTENSIONS = ['writer_failures', 'writer_transfer_cancel', 'writer_settle_effects'] as const;
export type PersistenceAdminExtension = typeof PERSISTENCE_ADMIN_EXTENSIONS[number];
export type PersistenceAdminOperation = typeof PERSISTENCE_ADMIN_OPERATIONS[number] | PersistenceAdminExtension;
export function isPersistenceAdminOperation(value: unknown): value is PersistenceAdminOperation {
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index e980495e26..4e08c85203 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -212,6 +212,21 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (ownerHost) await requireWriterAdminIntent(engine, 'writer_retry_effects', params);
return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy, ownerHost);
}
+ if (operation === 'writer_settle_effects') {
+ keys(params, ['source_id', 'request_id', 'parked_code', 'unsettle', 'apply', 'expect', 'dry_run']);
+ bool(params, 'unsettle'); bool(params, 'apply');
+ if (params.apply === true && params.dry_run === true) throw invalid('settle-effects takes --dry-run or --apply, not both.',
+ 'Preview with --dry-run, then run the apply_command it prints (--apply --expect <plan_hash>) after the user agrees.');
+ if (params.parked_code !== undefined && (typeof params.parked_code !== 'string' || !/^[a-z][a-z0-9_]*$/.test(params.parked_code))) throw invalid('Invalid --parked-code value.',
+ 'Pass --parked-code as a snake_case code doctor parked_effects names, e.g. --parked-code git_target_unsafe.');
+ if (params.expect !== undefined && (typeof params.expect !== 'string' || !/^ph_[0-9a-f]{24}$/.test(params.expect))) throw invalid('Invalid --expect value.',
+ 'Pass --expect exactly as the plan_hash the settle-effects preview printed (ph_ followed by 24 hex digits).');
+ const sourceId = source(params.source_id);
+ const requestId = params.request_id === undefined ? undefined : uuid(params.request_id, 'A valid original write request UUID is required.',
+ 'Pass --request-id with the request id doctor parked_effects or gbrain sources writer status lists for the effect.');
+ return (await import('./effect-settle.ts')).settleEffects(engine, { sourceId, requestId, parkedCode: params.parked_code as string | undefined,
+ unsettle: params.unsettle === true, apply: params.apply === true, expect: params.expect as string | undefined });
+ }
if (operation === 'source_add' || operation === 'source_lifecycle') {
const { managedPersistenceEnabled } = await import('./ownership.ts');
if (!await managedPersistenceEnabled(engine)) throw new OperationError('writer_coordinator_required',
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 466a715543..fc10cca797 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -162,7 +162,7 @@ const EFFECT_ROWS = `SELECT e.id::text AS effect_id, e.kind, e.state, COALESCE(e
* the same vector) or an effect whose source was archived, replaced or removed.
*/
export async function failedEffectHistory(engine: BrainEngine): Promise<FailedEffectEntry[]> {
- const rows = await engine.executeRaw<EffectRow>(`${EFFECT_ROWS} WHERE e.state='failed' AND e.recovery IS NULL ORDER BY e.id LIMIT 50`);
+ const rows = await engine.executeRaw<EffectRow>(`${EFFECT_ROWS} WHERE e.state='failed' AND e.recovery IS NULL AND NOT (e.data ? 'settled') ORDER BY e.id LIMIT 50`);
return rows.map(e => {
const retry = `gbrain sources writer retry-effects ${e.source_id} --request-id ${e.request_id} --dry-run`;
const [exit, why] = !e.source_live ? [null, 'its source was archived, replaced or removed, so nothing can run it']
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 8bc79c6034..1020ec7b04 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -35,6 +35,13 @@ export function contentRepairCommit(path: string, receipt: Pick<ContentRepairRec
}
/** `rule`: for `git_target_ignored`, the .gitignore rule that excludes the file (`<file>:<line>: <pattern>`). */
export interface ParkedTarget { slug?: string; error_code: string; rule?: string }
+/** #7423 / #7378: a settled target: under a declared db_only dir (`declared`), or its current bytes proved on the fetched remote (effect-settle.ts). */
+export type SettledTarget = { slug: string; declared: string }
+ | { slug: string; path: string; remote_ref: string; remote_commit: string; blob: string; receipt_request_id: string };
+export type SettlementProof = { kind: 'db_only'; worktree_id: string; targets: SettledTarget[] }
+ | { kind: 'superseded_remote'; former_worktree_id: string; worktree_id: string; targets: SettledTarget[] };
+/** The disposition `gbrain sources writer settle-effects` records on a Git effect whose retry can never succeed. */
+export interface EffectSettlement { reason: SettlementProof['kind']; at: string; host_id: string; plan_hash: string; proof: SettlementProof }
/** `page_body_segmented`: a segmented page an older binary's mirror or Git scan passed by; this one mirrors and commits it. */
/** `preview_changed`: a `gbrain repair segmented-mirror` target whose file or render no longer has the hash its preview approved (`data.approved_file`). */
export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' | 'withdrawal_not_mirrored' | 'preview_changed' }
@@ -101,7 +108,11 @@ export interface PersistenceEffect {
/** GBRA-130 A-12: pages whose file this withdrawal mirror rewrote, recorded by its recovery with the cursor step. */
published?: string[];
/** The SHA-256 of the bytes this mirror wrote to each published page's file, at the page revision it rendered. */
- published_files?: Record<string, { hash: string; revision: string }> };
+ published_files?: Record<string, { hash: string; revision: string }>;
+ /** #7423 / #7378: present while the effect is settled; every reader of parked and held effects skips it. */
+ settled?: EffectSettlement;
+ /** Every settle and unsettle of this effect, oldest first; never trimmed. */
+ settlements?: Array<Record<string, unknown> & { action: 'settled' | 'unsettled'; at: string; host_id: string; plan_hash: string }> };
state: 'queued' | 'running' | 'committed' | 'failed';
execution_token: string | null;
claim_expires_at: string | Date | null;
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index 0bcabcce66..88b3df1d28 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -65,7 +65,7 @@ export function refusalEnvelope(error: OperationError): { code: string; message:
}
/** #6697: the stored authority's refusal, or null while the original writer may still act. */
-async function storedAuthorityRefusal(tx: BrainEngine, request: WriteRequest, sourceId: string): Promise<OperationError | null> {
+export async function storedAuthorityRefusal(tx: BrainEngine, request: WriteRequest, sourceId: string): Promise<OperationError | null> {
try {
await authorizeStoredRequest(tx, request, true);
const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,
@@ -113,15 +113,16 @@ async function ownerRevokedError(tx: BrainEngine, sourceId: string, request: Wri
* Git and withdrawal effects (the credential-change retry).
*/
export async function retryParkedEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean,
- options: { internalId?: string; ownerHost?: boolean; parkedOnly?: boolean } = {}): Promise<Record<string, unknown> | null> {
+ options: { internalId?: string; ownerHost?: boolean; parkedOnly?: boolean; failedCodes?: readonly string[] } = {}): Promise<Record<string, unknown> | null> {
const [request, ambiguous] = options.internalId
? await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND id=$2::uuid', [sourceId, options.internalId])
: await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid LIMIT 2', [sourceId, requestId]);
if (!request || ambiguous) return null;
const tracked = await engine.executeRaw<PersistenceEffect>(`SELECT * FROM persistence_effects WHERE request_id=$1::uuid
AND ((kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried'))
- OR (NOT $2::boolean AND (state='failed' AND (kind<>'embedding' OR error_code='source_changed') OR kind='embedding' AND data ? 'parked'))) ORDER BY kind`,
- [request.id, options.parkedOnly === true]);
+ OR (NOT $2::boolean AND (state='failed' AND (kind<>'embedding' OR error_code='source_changed') OR kind='embedding' AND data ? 'parked'))
+ OR (kind='git' AND state='failed' AND error_code=ANY($3::text[]))) ORDER BY kind`,
+ [request.id, options.parkedOnly === true, [...options.failedCodes ?? []]]);
if (!tracked.length) return null;
const hostId = existingLocalHostId();
if (!hostId) throw unregisteredHost(sourceId, requestId);
@@ -136,7 +137,8 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
const parked = effect.data.parked ?? [];
const summary = { kind: effect.kind, error_code: effect.error_code, parked_targets: parked.length, targets: parked.slice(0, 20), retried: effect.data.retried ?? 0 };
const parkedState = effect.error_code === 'targets_parked' ? 'parked' : 'failed';
- if (effect.state !== 'failed' || (parkedState === 'failed' && options.parkedOnly)) {
+ if (effect.state === 'failed' && effect.data.settled) { effects.push({ ...summary, state: parkedState, terminal: true, action: 'settled', settled: effect.data.settled }); continue; }
+ if (effect.state !== 'failed' || (parkedState === 'failed' && options.parkedOnly && !options.failedCodes?.includes(effect.error_code ?? ''))) {
effects.push({ ...summary, state: effect.state, terminal: effect.state === 'committed', action: 'unchanged' });
continue;
}
@@ -168,14 +170,16 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
effects.push({ ...summary, state: 'queued', terminal: false, action: 'retry_queued', ...retriedUnder });
}
const queued = effects.some(effect => effect.action === 'retry_queued');
+ const settled = effects.some(effect => effect.action === 'settled') && !effects.some(effect => effect.action === 'retry_queued' || effect.action === 'would_retry');
const revoked = denied !== null && effects.some(effect => effect.action === 'owner_revoked');
return { request_id: request.request_id, source_id: sourceId, dry_run: dryRun, effects,
...(denied ? { authority: { ok: false, code: refusal!.code, message: refusal!.message } } : {}),
...(revoked ? { action: 'owner_revoked', refusal: refusalEnvelope(denied!), fix: denied!.fix } : {}),
next_action: revoked && !queued ? denied!.suggestion
- : dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target or failed effect.'
- : queued ? 'The resident owner makes one more attempt per parked target or failed effect. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'
- : 'No parked target remains for this request.' };
+ : settled ? `This request's parked effects are settled; gbrain sources writer settle-effects ${sourceId} --request-id ${request.request_id} --unsettle --dry-run previews reversing it.`
+ : dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target or failed effect.'
+ : queued ? 'The resident owner makes one more attempt per parked target or failed effect. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'
+ : 'No parked target remains for this request.' };
});
}
@@ -193,7 +197,7 @@ export async function retryIndexLockParks(engine: BrainEngine, worktreeId: strin
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'
+ 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 (e.data ? 'settled')
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]);
diff --git a/src/core/persistence/effect-settle.ts b/src/core/persistence/effect-settle.ts
new file mode 100644
index 0000000000..67fa958a12
--- /dev/null
+++ b/src/core/persistence/effect-settle.ts
@@ -0,0 +1,198 @@
+/**
+ * #7423 / #7378: `gbrain sources writer settle-effects <source> (--request-id <id> | --parked-code <code>) [--unsettle]
+ * [--dry-run | --apply --expect <plan_hash>]`, the operator exit for a parked or failed Git effect whose retry can never
+ * succeed. A settlement is a disposition recorded on the effect row (`data.settled`, with every settle and unsettle
+ * appended to `data.settlements`); the failure, its parked targets, the request, its intent and the target bytes are
+ * never changed or deleted. Every reader of parked and held effects skips a settled row, and `--unsettle` (bound to its
+ * own plan) restores it.
+ *
+ * An effect settles only on an exact-target proof, re-checked under row locks when the plan is applied:
+ * - `db_only`: each target's slug falls under a `storage.db_only` directory of the current binding's gbrain.yml (not a
+ * push code: a commit that failed to push still owes its push);
+ * - `superseded_remote`: the binding guard refuses the effect as `source_changed` because the source moved to a new
+ * worktree (same incarnation, this host owns the current binding), and for each target a later Git effect of the
+ * current worktree committed and pushed the bytes the canonical file holds now, and the already-fetched remote-tracking
+ * ref of the checkout's branch holds exactly those bytes at that path. Nothing is fetched: a missing ref, or a ref
+ * that lacks bytes a push reported, refuses.
+ * Unknown targets, a withdrawal or other non-Git effect, a claimed effect, an open recovery record, a revoked original
+ * writer, a replaced source and a binding this host does not own are refused. An effect of the current binding that is
+ * not db_only is refused as `retry_instead`: `retry-effects` can still run it.
+ * The plan hash (doctor --remediate's `computePlanHash`) binds the brain, source, selector, mode, the binding's owner epoch
+ * and each effect's proof; an apply under another hash refuses `preview_changed` and changes nothing.
+ */
+import { existsSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { computePlanHash } from '../consent.ts';
+import { execFileBounded } from '../bounded-child-exec.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { digest } from './digest.ts';
+import { existingLocalHostId } from './identity.ts';
+import { guardEffectSource } from './effect-recovery.ts';
+import { storedAuthorityRefusal } from './effect-retry.ts';
+import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
+import { persistenceFileHash } from './coordinator.ts';
+import { sourceDbOnlyDir } from './source-storage.ts';
+import { declarePersistenceProtocol } from './protocol.ts';
+import { GIT_PUSH_CODES } from './git-push-holds.ts';
+import type { EffectSettlement, ParkedTarget, PersistenceEffect, SettlementProof, SettledTarget } from './effect-model.ts';
+import type { WriteRequest } from './model.ts';
+
+export interface SettleEffectsInput { sourceId: string; requestId?: string; parkedCode?: string; unsettle?: boolean; apply?: boolean; expect?: string }
+type Refusal = { code: string; message: string };
+type Row = PersistenceEffect & { request: WriteRequest };
+interface Entry {
+ effect_id: string; request_id: string; kind: string; error_code: string | null; worktree_id: string | null; targets: ParkedTarget[];
+ action: 'would_settle' | 'settled' | 'would_unsettle' | 'unsettled' | 'refused'; proof?: SettlementProof; settled?: EffectSettlement; refusal?: Refusal;
+}
+
+const statusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its retrying and parked effects, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+const GIT_ENV = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' };
+const PUSH_CODES: readonly string[] = GIT_PUSH_CODES;
+
+async function gitRead(root: string, args: string[]): Promise<string | null> {
+ const { error, stdout } = await execFileBounded('git', ['-C', root, ...args], { timeout: 20_000, maxBuffer: 1024 * 1024, env: gitChildEnv(GIT_ENV) });
+ return error ? null : stdout.trim() || null;
+}
+
+/** The targets an effect owes: its parked targets, or (a push that failed without parking) its own page. */
+function effectTargets(effect: PersistenceEffect): ParkedTarget[] {
+ return effect.data.parked ?? [{ ...(effect.data.slug ? { slug: effect.data.slug } : {}), error_code: effect.error_code ?? 'unknown' }];
+}
+
+/** The proof that a later, pushed Git effect of the current worktree holds this target's current canonical bytes on the fetched remote. */
+async function remoteProof(tx: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding & { local_path: string }, slug: string): Promise<SettledTarget | Refusal> {
+ const [receipt] = await tx.executeRaw<{ request_id: string; state: string; data: PersistenceEffect['data']; outcome: Record<string, unknown> | null }>(
+ `SELECT r.request_id::text AS request_id,e.state,e.data,e.outcome FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE e.kind='git' AND e.source_id=$1 AND e.worktree_id=$2::uuid AND e.id>$3 AND e.data->>'slug'=$4 AND e.data ? 'relative_path'
+ ORDER BY e.id DESC LIMIT 1`, [effect.source_id, binding.worktree_id, effect.id, slug]);
+ if (!receipt) return { code: 'no_covering_receipt', message: `No later Git effect of source ${effect.source_id}'s current worktree committed page ${slug}, so nothing shows its current bytes were backed up. Write the page through gbrain (its Git effect commits and pushes it), then preview again.` };
+ const path = receipt.data.relative_path!;
+ if (effect.data.relative_path !== undefined && !effect.data.source_scan && effect.data.relative_path !== path) {
+ return { code: 'unknown_target', message: `Page ${slug} is now filed at ${path}, not at ${effect.data.relative_path}, the path this effect owes; no exact target links them.` };
+ }
+ const file = join(binding.local_path, path);
+ const page = await tx.readPageSnapshot(slug, { sourceId: effect.source_id });
+ if (!page || !existsSync(file) || !statSync(file).isFile()) return { code: 'content_missing', message: `Page ${slug} or its canonical file ${path} is gone, so there are no current bytes to prove.` };
+ if (persistenceFileHash(file) !== receipt.data.expected_hash) return { code: 'content_changed', message: `The canonical file ${path} no longer holds the bytes the latest Git effect of page ${slug} (request ${receipt.request_id}) wrote; inspect the checkout before preview again.` };
+ if (receipt.state !== 'committed' || receipt.outcome?.push !== 'committed') return { code: 'bytes_unpushed', message: `The latest Git effect of page ${slug} (request ${receipt.request_id}) has not pushed (state ${receipt.state}), so its bytes are on this host only. Let it push (gbrain sources writer status shows it), then preview again.` };
+ const ref = await gitRead(binding.local_path, ['rev-parse', '--symbolic-full-name', '@{upstream}']);
+ const commit = ref ? await gitRead(binding.local_path, ['rev-parse', '--verify', '-q', `${ref}^{commit}`]) : null;
+ if (!ref || !commit) return { code: 'remote_ref_missing', message: `The checkout of source ${effect.source_id} has no fetched remote-tracking ref for its branch, so the remote cannot be read without fetching. Fetch in the checkout, then preview again.` };
+ const [remoteBlob, fileBlob] = await Promise.all([gitRead(binding.local_path, ['rev-parse', '--verify', '-q', `${commit}:./${path}`]), gitRead(binding.local_path, ['hash-object', '--', path])]);
+ if (!fileBlob || remoteBlob !== fileBlob) return { code: 'remote_ref_stale', message: `The fetched ${ref} (${commit}) does not hold the bytes of ${path} that request ${receipt.request_id} pushed: the ref is older than that push, or the remote moved past it. Fetch in the checkout, then preview again.` };
+ return { slug, path, remote_ref: ref, remote_commit: commit, blob: fileBlob, receipt_request_id: receipt.request_id };
+}
+
+/** The exact-target proof for one effect, or why it cannot settle. */
+async function settleProof(tx: BrainEngine, row: Row, hostId: string, binding: WorktreeBinding | null): Promise<SettlementProof | Refusal> {
+ const { request, ...effect } = row;
+ if (effect.kind === 'withdrawal-mirror') return { code: 'withdrawal_effect', message: 'A withdrawal effect is never settled: its file may still hold the withdrawn text.' };
+ if (effect.kind !== 'git') return { code: 'not_git_effect', message: `Only Git effects settle; this ${effect.kind} effect keeps its own retry.` };
+ if (effect.execution_token !== null) return { code: 'claimed', message: 'A worker holds this effect; preview again once it is released.' };
+ if (effect.recovery || request.recovery) return { code: 'recovery_open', message: 'The effect or its request holds an open recovery record; it must be recovered first.' };
+ if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { code: 'owner_unavailable',
+ message: `This host does not own source ${effect.source_id}'s active canonical binding; settle runs on the owner host.` };
+ let former = false;
+ try { await guardEffectSource(tx, effect, hostId); }
+ catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ if (error.code !== 'source_changed') return { code: error.code, message: error.message };
+ const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [effect.source_id]);
+ if (!source || source.archived || source.incarnation !== effect.source_incarnation || binding.source_incarnation !== effect.source_incarnation || binding.worktree_id === effect.worktree_id) {
+ return { code: 'source_replaced', message: `Source ${effect.source_id} was archived, removed or re-created after this effect was recorded, so it owes nothing to the current source.` };
+ }
+ former = true;
+ }
+ const denied = await storedAuthorityRefusal(tx, request, effect.source_id);
+ if (denied) return { code: 'authority_changed', message: `The original writer is no longer authorized (${denied.message}).` };
+ const sourceRoot = join(binding.local_path, binding.relative_path);
+ const targets: SettledTarget[] = [];
+ for (const target of effectTargets(effect)) {
+ if (!target.slug) return { code: 'unknown_target', message: 'A parked entry names no page, so its exact target is unknown.' };
+ let declared: string | null;
+ try { declared = PUSH_CODES.includes(target.error_code) ? null : sourceDbOnlyDir(sourceRoot, target.slug); }
+ catch (error) { if (error instanceof OperationError) return { code: error.code, message: error.message }; throw error; }
+ if (declared) { targets.push({ slug: target.slug, declared }); continue; }
+ if (!former) return { code: 'retry_instead', message: `Page ${target.slug} is not declared db_only and the effect belongs to the current binding, so retry-effects can still run it.` };
+ const proved = await remoteProof(tx, effect, binding as WorktreeBinding & { local_path: string }, target.slug);
+ if ('code' in proved) return proved;
+ targets.push(proved);
+ }
+ return targets.every(target => 'declared' in target)
+ ? { kind: 'db_only', worktree_id: binding.worktree_id, targets }
+ : { kind: 'superseded_remote', former_worktree_id: effect.worktree_id!, worktree_id: binding.worktree_id, targets };
+}
+
+export async function settleEffects(engine: BrainEngine, input: SettleEffectsInput): Promise<Record<string, unknown> & { plan_hash: string; effects: Entry[] }> {
+ const { sourceId, requestId, parkedCode, unsettle = false, apply = false } = input;
+ if ((requestId === undefined) === (parkedCode === undefined)) throw opError('invalid_params', 'settle-effects selects with exactly one of --request-id or --parked-code.',
+ `Preview with gbrain sources writer settle-effects ${sourceId} and one parked code doctor parked_effects names (--parked-code), or name one request with --request-id.`, { fix: statusFix(sourceId) });
+ if (apply && !input.expect) throw opError('invalid_params', 'settle-effects --apply needs --expect <plan_hash> from its preview.',
+ 'Run the preview (--dry-run), show the user the plan, and run the apply_command it prints after they agree.', { fix: statusFix(sourceId) });
+ const hostId = existingLocalHostId();
+ if (!hostId) throw opError('permission_denied', 'Settling effects requires the registered local CLI host.',
+ `This machine has no registered gbrain host identity, so it cannot settle effects of source ${sourceId}; nothing changed. Run it on the brain host that owns ${sourceId}.`, { fix: statusFix(sourceId) });
+ const selector = requestId !== undefined ? ['--request-id', requestId] : ['--parked-code', parkedCode!];
+ const mode = unsettle ? 'unsettle' : 'settle';
+ return engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");
+ const binding = await getWorktreeBinding(tx, sourceId, hostId);
+ const rows = await tx.executeRaw<Row>(`SELECT e.*,r.request_id::text AS public_request_id,to_jsonb(r) AS request FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE e.source_id=$1 AND ($2::uuid IS NULL OR r.request_id=$2::uuid)
+ AND ($3::text IS NULL OR e.error_code=$3 OR EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) p WHERE p->>'error_code'=$3))
+ AND (CASE WHEN $4::boolean THEN e.data ? 'settled'
+ ELSE e.state='failed' AND NOT (e.data ? 'settled') AND (e.data ? 'parked' OR e.kind='git' AND e.error_code=ANY($5::text[])) END)
+ ORDER BY e.id LIMIT 200 ${apply ? 'FOR UPDATE OF e' : ''}`, [sourceId, requestId ?? null, parkedCode ?? null, unsettle, PUSH_CODES]);
+ const effects: Entry[] = [];
+ for (const row of rows) {
+ const entry = { effect_id: String(row.id), request_id: (row as Row & { public_request_id: string }).public_request_id, kind: row.kind, error_code: row.error_code,
+ worktree_id: row.worktree_id, targets: effectTargets(row) };
+ if (unsettle) { effects.push({ ...entry, action: 'would_unsettle', settled: row.data.settled }); continue; }
+ const proof = await settleProof(tx, row, hostId, binding);
+ effects.push('code' in proof ? { ...entry, action: 'refused', refusal: proof } : { ...entry, action: 'would_settle', proof });
+ }
+ const actionable = effects.filter(effect => effect.action !== 'refused');
+ const [brain] = await tx.executeRaw<{ brain_id: string }>('SELECT brain_id::text AS brain_id FROM persistence_brain WHERE singleton=1');
+ const planHash = computePlanHash({ brain: brain?.brain_id ?? 'unknown', source: sourceId, operation: `writer_${mode}_effects`,
+ records: actionable.map(effect => ({ id: effect.effect_id, revision: digest(effect.proof ?? effect.settled ?? null) })),
+ parameters: { request_id: requestId ?? null, parked_code: parkedCode ?? null, owner_epoch: binding?.owner_epoch ?? null, worktree_id: binding?.worktree_id ?? null }, effects: [] });
+ if (apply) {
+ if (input.expect !== planHash) throw opError('preview_changed', `The settle plan changed since its preview (--expect ${input.expect}, current plan ${planHash}); nothing was changed.`,
+ 'Preview again, show the user the new plan, and run its apply_command only if they approve it.',
+ { fix: readFix('Shows the current settle plan and its plan_hash, read-only.', { argv: ['gbrain', 'sources', 'writer', 'settle-effects', sourceId, ...selector, ...(unsettle ? ['--unsettle'] : []), '--dry-run', '--json'] }) });
+ const at = new Date().toISOString();
+ for (const effect of actionable) {
+ if (unsettle) {
+ await tx.executeRaw(`UPDATE persistence_effects SET data=(data-'settled')||jsonb_build_object('settlements',COALESCE(data->'settlements','[]'::jsonb)||jsonb_build_array($2::text::jsonb)),
+ updated_at=now() WHERE id=$1 AND data ? 'settled'`, [effect.effect_id, JSON.stringify({ action: 'unsettled', at, host_id: hostId, plan_hash: planHash, settled: effect.settled })]);
+ effect.action = 'unsettled';
+ continue;
+ }
+ const settled: EffectSettlement = { reason: effect.proof!.kind, at, host_id: hostId, plan_hash: planHash, proof: effect.proof! };
+ await tx.executeRaw(`UPDATE persistence_effects SET data=data||jsonb_build_object('settled',$2::text::jsonb,'settlements',COALESCE(data->'settlements','[]'::jsonb)||jsonb_build_array($3::text::jsonb)),
+ updated_at=now() WHERE id=$1 AND state='failed' AND execution_token IS NULL AND recovery IS NULL AND NOT (data ? 'settled')`,
+ [effect.effect_id, JSON.stringify(settled), JSON.stringify({ action: 'settled', ...settled })]);
+ effect.action = 'settled';
+ }
+ }
+ const applyCommand = ['gbrain', 'sources', 'writer', 'settle-effects', sourceId, ...selector, ...(unsettle ? ['--unsettle'] : []), '--apply', '--expect', planHash];
+ const preview = !apply && actionable.length > 0;
+ return { action: 'writer_settle_effects', source_id: sourceId, mode, dry_run: !apply, plan_hash: planHash, settleable: actionable.length,
+ refused: effects.length - actionable.length, effects,
+ ...(preview ? { apply_command: applyCommand, fix: { ask_user: true, argv: applyCommand, consent: [], actor: 'agent', requires_exclusive: false,
+ why: unsettle ? 'Removes the settled disposition so the effects are held and reported again; the settlement stays in their history.'
+ : 'Records a settled disposition on each listed effect (its failure, request and target bytes are kept), so doctor and retries stop reporting it.',
+ user_message: unsettle ? `Un-settle ${actionable.length} effect(s) of source ${sourceId}, so doctor reports them again?`
+ : `Settle ${actionable.length} Git effect(s) of source ${sourceId} whose retry can never succeed? Each has the proof shown; their failures stay in history and --unsettle reverses it.`,
+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] } } satisfies Action } : {}),
+ next: preview ? 'Show the user each proof; run apply_command (bound to this plan_hash) only after they agree.'
+ : apply ? `${actionable.length} effect(s) ${unsettle ? 'un-settled' : 'settled'}; doctor parked_effects and writer status reflect it now.`
+ : effects.length ? 'No listed effect can settle; each refusal names its cause.' : `No ${unsettle ? 'settled' : 'unsettled parked or failed'} effect matches this selector.` };
+ });
+}
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index 1da55f0811..081083a554 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -172,6 +172,27 @@ export async function wireDurabilityCredential(root: string, remote: string | nu
return { status: 'fixed', detail: `wired a repo-scoped credential for ${host} (store 0600; replaces an earlier token for that host)` };
}
+/** A failed Git effect held on one of $2's codes: a parked target with it, or (#7378) a push that failed without parking. */
+const HELD_ON_CODES = `e.error_code=ANY($2::text[]) OR e.error_code='targets_parked'
+ AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) p WHERE p->>'error_code'=ANY($2::text[]))`;
+
+/**
+ * #7378: unsettled Git effects of the source held on these codes but bound to another (former) worktree. A retry of the
+ * current worktree never reaches them (the binding guard refuses their stale binding), so an empty retry is not their
+ * resolution: they are named with the settle preview that can account for them.
+ */
+async function formerWorktreeHolds(engine: BrainEngine, sourceId: string, worktreeId: string, codes: readonly string[]) {
+ const [row] = await engine.executeRaw<{ effects: number; code: string | null }>(`SELECT count(*)::int AS effects,
+ min(CASE WHEN e.error_code=ANY($2::text[]) THEN e.error_code ELSE (SELECT min(p->>'error_code') FROM jsonb_array_elements(e.data->'parked') p
+ WHERE p->>'error_code'=ANY($2::text[])) END) AS code
+ FROM persistence_effects e WHERE e.source_id=$1 AND e.worktree_id IS DISTINCT FROM $3::uuid AND e.kind='git' AND e.state='failed'
+ AND NOT (e.data ? 'settled') AND (${HELD_ON_CODES})`, [sourceId, [...codes], worktreeId]);
+ if (!row?.effects || !row.code) return {};
+ const command = ['gbrain', 'sources', 'writer', 'settle-effects', sourceId, '--parked-code', row.code, '--dry-run'];
+ return { former_worktree: { effects: Number(row.effects), command,
+ why: `${row.effects} held Git effect(s) of source ${sourceId} belong to a former canonical worktree: retry cannot run them (their binding changed) and this preview does not resolve them. Preview settling them on proof: ${command.join(' ')}` } };
+}
+
export type ParkedPushRefusal = { source_id: string; request_id: string; code: string; message: string; suggestion?: string; fix?: Action };
export type ParkedPushRetry = { status: 'ok' | 'partial'; requests: number; queued: number; unchanged: number; refused: ParkedPushRefusal[] };
const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_claim_lost']);
@@ -192,8 +213,7 @@ export async function retryParkedPushes(engine: BrainEngine, worktreeId: string,
const rows = await engine.executeRaw<{ source_id: string; id: string; request_id: string }>(`
SELECT DISTINCT e.source_id,r.id::text AS id,r.request_id::text AS request_id FROM persistence_effects e
JOIN persistence_requests r ON r.id=e.request_id
- WHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND e.recovery IS NULL
- AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) p WHERE p->>'error_code'=ANY($2::text[]))
+ WHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.recovery IS NULL AND NOT (e.data ? 'settled') AND (${HELD_ON_CODES})
ORDER BY e.source_id,request_id,id`, [worktreeId, [...codes]]);
let queued = 0, unchanged = 0;
const refused: ParkedPushRefusal[] = [];
@@ -201,7 +221,7 @@ export async function retryParkedPushes(engine: BrainEngine, worktreeId: string,
const target = { source_id: row.source_id, request_id: row.request_id };
let result: Record<string, unknown> | null;
try {
- result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id, parkedOnly: true });
+ result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id, parkedOnly: true, failedCodes: codes });
} catch (error) {
if (!(error instanceof OperationError) || !REQUEST_REFUSALS.has(error.code)) throw error;
refused.push({ ...target, ...refusalEnvelope(error) });
@@ -222,7 +242,7 @@ export async function retryParkedPushes(engine: BrainEngine, worktreeId: string,
export async function retrySourceParkedPushes(engine: BrainEngine, sourceId: string, dryRun: boolean): Promise<Record<string, unknown>> {
const binding = await ownedBinding(engine, sourceId);
return { action: 'writer_retry_parked_pushes', source_id: sourceId, worktree_id: binding.worktree_id, dry_run: dryRun,
- ...await retryParkedPushes(engine, binding.worktree_id, dryRun) };
+ ...await retryParkedPushes(engine, binding.worktree_id, dryRun), ...await formerWorktreeHolds(engine, sourceId, binding.worktree_id, GIT_PUSH_CODES) };
}
/**
@@ -233,7 +253,7 @@ export async function retrySourceParkedPushes(engine: BrainEngine, sourceId: str
export async function retrySourceParkedCode(engine: BrainEngine, sourceId: string, code: string, dryRun: boolean): Promise<Record<string, unknown>> {
const binding = await ownedBinding(engine, sourceId);
return { action: 'writer_retry_parked_code', source_id: sourceId, worktree_id: binding.worktree_id, code, dry_run: dryRun,
- ...await retryParkedPushes(engine, binding.worktree_id, dryRun, [code]) };
+ ...await retryParkedPushes(engine, binding.worktree_id, dryRun, [code]), ...await formerWorktreeHolds(engine, sourceId, binding.worktree_id, [code]) };
}
async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<WorktreeBinding & { local_path: string }> {
diff --git a/src/core/persistence/git-push-holds.ts b/src/core/persistence/git-push-holds.ts
index 53449f5796..b93b21c01a 100644
--- a/src/core/persistence/git-push-holds.ts
+++ b/src/core/persistence/git-push-holds.ts
@@ -28,19 +28,22 @@ export interface GitPushHold {
oldest_at: string;
/** The unresolved conflict the last publish recorded for the checkout (both sides changed these paths). */
conflict: IntegrateConflictState | null;
+ /** #7378: the effects belong to a worktree the source is no longer bound to; no retry reaches them, settle-effects accounts for them. */
+ former_worktree: boolean;
fix: Action;
}
export async function readGitPushHolds(engine: BrainEngine, sourceIds?: string[]): Promise<GitPushHold[]> {
- const rows = await engine.executeRaw<{ source_id: string; root: string | null; retrying: number; parked: number; codes: string[]; oldest_at: string | Date }>(
+ const rows = await engine.executeRaw<{ source_id: string; root: string | null; former_worktree: boolean; retrying: number; parked: number; codes: string[]; oldest_at: string | Date }>(
`WITH held AS (
SELECT e.source_id, e.worktree_id, e.state, r.created_at,
CASE WHEN e.error_code='targets_parked' THEN (SELECT p->>'error_code' FROM jsonb_array_elements(COALESCE(e.data->'parked','[]'::jsonb)) p
WHERE p->>'error_code'=ANY($1::text[]) LIMIT 1) ELSE e.error_code END AS code
FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
- WHERE e.kind='git' AND e.state IN ('queued','running','failed') AND e.recovery IS NULL
+ WHERE e.kind='git' AND e.state IN ('queued','running','failed') AND e.recovery IS NULL AND NOT (e.data ? 'settled')
AND ($2::text[] IS NULL OR e.source_id=ANY($2::text[])))
SELECT h.source_id, (SELECT b.local_path FROM persistence_host_bindings b WHERE b.worktree_id=h.worktree_id ORDER BY b.local_path LIMIT 1) AS root,
+ NOT EXISTS (SELECT 1 FROM persistence_source_bindings s WHERE s.source_id=h.source_id AND s.worktree_id=h.worktree_id) AS former_worktree,
count(*) FILTER (WHERE h.state<>'failed')::int AS retrying, count(*) FILTER (WHERE h.state='failed')::int AS parked,
array_agg(DISTINCT h.code ORDER BY h.code) AS codes, min(h.created_at) AS oldest_at
FROM held h WHERE h.code=ANY($1::text[])
@@ -48,7 +51,7 @@ export async function readGitPushHolds(engine: BrainEngine, sourceIds?: string[]
return rows.map(row => {
const conflict = row.root ? readIntegrateConflict(row.root) : null;
const hold = { source_id: row.source_id, root: row.root, retrying: Number(row.retrying), parked: Number(row.parked), codes: row.codes,
- oldest_at: new Date(row.oldest_at).toISOString(), conflict };
+ oldest_at: new Date(row.oldest_at).toISOString(), conflict, former_worktree: row.former_worktree === true };
return { ...hold, fix: gitPushFix(hold) };
});
}
@@ -65,6 +68,11 @@ function gitPushFix(hold: Omit<GitPushHold, 'fix'>): Action {
user_message: `This machine and the remote both changed ${hold.conflict.paths.join(', ')} in ${hold.root}, so ${held} Git backup(s) of page writes in source ${hold.source_id} are held (nothing is lost; the database has every write). Which version should win: this machine's (ours) or the remote's (theirs)? Afterwards run gbrain sources writer retry-effects ${hold.source_id} --parked-pushes, then gbrain sources refresh ${hold.source_id}.`,
verify: statusVerify(hold.source_id), docs: 'docs/guides/shared-checkout-git.md#conflicts',
};
+ if (hold.parked && hold.former_worktree) return {
+ argv: ['gbrain', 'sources', 'writer', 'settle-effects', hold.source_id, '--parked-code', hold.codes[0]!, '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `${hold.parked} Git effect(s) of source ${hold.source_id} failed on a push (${hold.codes.join(', ')}) in a worktree the source is no longer bound to, so no retry reaches them. This previews settling each one whose current bytes the fetched remote already holds; it changes nothing.`,
+ verify: statusVerify(hold.source_id),
+ };
if (hold.parked) return {
argv: ['gbrain', 'sources', 'writer', 'retry-effects', hold.source_id, '--parked-pushes'], consent: [], actor: 'agent', requires_exclusive: false,
why: `${hold.parked} Git effect(s) of source ${hold.source_id} parked after repeated push failures (${hold.codes.join(', ')}); this authorizes one more push attempt for each. A push the remote rejected because it moved is merged in memory and pushed without moving the checkout. Preview with --dry-run.`,
diff --git a/src/core/persistence/parked-groups.ts b/src/core/persistence/parked-groups.ts
index 841319527b..9552bc646b 100644
--- a/src/core/persistence/parked-groups.ts
+++ b/src/core/persistence/parked-groups.ts
@@ -7,21 +7,23 @@ export interface ParkedGroup { source_id: string; code: string; effects: number;
/**
* Parked Git targets per source and error code (doctor `parked_effects`, `sources writer status`). Each group names its
* bulk retry (`--parked-pushes` for push codes, `--parked-code <code>` otherwise) as a preview. A `git_target_ignored`
- * group names the .gitignore rule and says the rule has to change first: a retry while it stands parks again.
+ * group names the .gitignore rule and says the rule has to change first: a retry while it stands parks again. Other groups
+ * also name the settle preview (#7423, #7378) for targets a retry can never move; settled effects are not counted.
*/
export async function readParkedGroups(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<ParkedGroup[]> {
const rows = await engine.executeRaw<{ source_id: string; code: string; effects: number; targets: number; rule: string | null }>(
`SELECT e.source_id, p->>'error_code' AS code, count(DISTINCT e.id)::int AS effects, count(*)::int AS targets, min(p->>'rule') AS rule
FROM persistence_effects e CROSS JOIN LATERAL jsonb_array_elements(e.data->'parked') p
- WHERE e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND jsonb_typeof(e.data->'parked')='array'
+ WHERE e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND jsonb_typeof(e.data->'parked')='array' AND NOT (e.data ? 'settled')
AND ($1::text[] IS NULL OR e.source_id=ANY($1::text[]))
GROUP BY 1, 2 ORDER BY 1, 2`, [sourceIds ?? null]);
return rows.map(({ rule, ...row }) => {
const push = (GIT_PUSH_CODES as readonly string[]).includes(row.code);
const command = ['gbrain', 'sources', 'writer', 'retry-effects', row.source_id, ...(push ? ['--parked-pushes'] : ['--parked-code', row.code]), '--dry-run'];
+ const settle = `gbrain sources writer settle-effects ${row.source_id} --parked-code ${row.code} --dry-run`;
const next = row.code === 'git_target_ignored'
? `Git ignores these files${rule ? ` (${rule})` : ''}, so a retry parks them again while the rule stands. Change the rule and commit it, then preview ${command.join(' ')} and rerun it without --dry-run; or keep the files out of Git and leave them parked (their pages are committed in the database).`
- : `Fix the cause, then preview ${command.join(' ')} and rerun it without --dry-run to authorize one more attempt per target.`;
+ : `Fix the cause, then preview ${command.join(' ')} and rerun it without --dry-run to authorize one more attempt per target. A target that can never succeed (now declared db_only, or left in a former canonical worktree) settles on proof instead: preview ${settle}.`;
return { ...row, ...(rule ? { rule } : {}), command, next };
});
}
diff --git a/src/core/persistence/source-storage.ts b/src/core/persistence/source-storage.ts
index 1471ed4a53..c9fc87571c 100644
--- a/src/core/persistence/source-storage.ts
+++ b/src/core/persistence/source-storage.ts
@@ -46,6 +46,12 @@ function load(root: string): StorageConfig | null {
* logged once per version; `refuse` then throws `storage_error`, while
* `not_db_only` answers false so the caller keeps its non-db_only behavior.
*/
+/** #7423: the declared `storage.db_only` dir this page slug falls under at this source root, or null; an invalid gbrain.yml refuses (`storage_error`). */
+export function sourceDbOnlyDir(root: string, slug: string): string | null {
+ const config = load(root);
+ return config?.db_only.find(dir => isDeclaredDbOnlySlug(slug, { ...config, db_only: [dir] })) ?? null;
+}
+
export function isSourceDbOnlySlug(root: string, slug: string, onInvalid: 'refuse' | 'not_db_only'): boolean {
try {
return isDeclaredDbOnlySlug(slug, load(root));
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 2ac5790239..c51d09b097 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -335,7 +335,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const header = selected?.header ?? null;
// #7010: the push-hold probe rides this statement, so a source with no held Git effect costs no extra round trip (GBRA-161 PR 2: so does the fence-hold probe).
const [committed] = await engine.executeRaw<{ n: number | string; git_push_held: boolean; fence_held: boolean; last_committed_at: Date | string | null }>(`SELECT count(*) AS n, EXISTS (SELECT 1 FROM persistence_effects e
- WHERE e.source_id=$1 AND e.kind='git' AND e.state IN ('queued','running','failed') AND e.error_code IN ('targets_parked', ${GIT_PUSH_CODES.map(code => `'${code}'`).join(',')})) AS git_push_held,
+ WHERE e.source_id=$1 AND e.kind='git' AND e.state IN ('queued','running','failed') AND e.error_code IN ('targets_parked', ${GIT_PUSH_CODES.map(code => `'${code}'`).join(',')})
+ AND NOT (e.data ? 'settled')) AS git_push_held,
EXISTS (SELECT 1 FROM derived_generations g WHERE g.source_id=$1 AND g.kind IN ('fact_fence','take_fence') AND g.state='held') AS fence_held,
(SELECT max(r.completed_at) FROM persistence_source_bindings b JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
WHERE b.source_id=$1 AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS last_committed_at
diff --git a/test/e2e/w5-persistence-postgres.test.ts b/test/e2e/w5-persistence-postgres.test.ts
index f00dbffeb7..a7ba68fd80 100644
--- a/test/e2e/w5-persistence-postgres.test.ts
+++ b/test/e2e/w5-persistence-postgres.test.ts
@@ -8,6 +8,7 @@ import {
capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts, failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark, ignoredTargetParksAtOnce,
managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, managedStaleSweepManyPages, scanParksOneTargetAndContinues, singleTargetParksAndRetries, staleExtractionWithheldWhenItCannotRun,
} from '../helpers/w5-scenarios.ts';
+import { dbOnlyTargetSettles, failedCurrentPushRetries, formerWorktreeEffectsSettle, withdrawalEffectRefuses } from '../helpers/effect-settle-scenarios.ts';
const url = process.env.DATABASE_URL;
describe.skipIf(!url)('Postgres managed capacity, parking and stale extraction', () => {
@@ -16,6 +17,10 @@ describe.skipIf(!url)('Postgres managed capacity, parking and stale extraction',
test('a Git scan parks one target and continues', () => scanParksOneTargetAndContinues(url), 180_000);
test('failures do not carry to another target', () => failuresDoNotCarryToAnotherTarget(url), 180_000);
test('a healthy scan and contention never park', () => healthyScanAndContentionNeverPark(url), 180_000);
+ test('#7423 a target declared db_only after parking settles on proof and unsettles', () => dbOnlyTargetSettles(url), 240_000);
+ test('#7378 former-worktree Git effects settle only on the fetched remote bytes', () => formerWorktreeEffectsSettle(url), 300_000);
+ test('#7378 a withdrawal effect never settles', () => withdrawalEffectRefuses(url), 180_000);
+ test('#7378 a failed current push without parked targets retries', () => failedCurrentPushRetries(url), 180_000);
test('configured retention compacts past unfinished receipts', () => compactionSkipsUnfinishedReceipts(url), 240_000);
test('capacity warning and refusal hint', () => capacityWarnsAndRefusalNamesTheKey(url), 180_000);
test('managed extract --stale is coordinated', () => managedStaleSweep(url), 180_000);
diff --git a/test/helpers/effect-settle-scenarios.ts b/test/helpers/effect-settle-scenarios.ts
new file mode 100644
index 0000000000..7a6bfcd057
--- /dev/null
+++ b/test/helpers/effect-settle-scenarios.ts
@@ -0,0 +1,291 @@
+/**
+ * #7423 / #7378: a parked or failed Git effect whose retry can never succeed is settled by an explicit, preview-first,
+ * plan-hash-bound operator step (`gbrain sources writer settle-effects`), only on an exact-target proof: its target now
+ * resolves db_only under the current gbrain.yml, or it belongs to a former canonical worktree and the already-fetched
+ * remote branch holds the current canonical bytes a later committed and pushed Git effect wrote. The original failure,
+ * request and target stay as they were; every reader skips the settled row, and `--unsettle` (plan-bound too) restores it.
+ * A failed push of the current binding (#7378, no `data.parked`) is retried by `--parked-pushes`, never settled.
+ * PGLite runs these from test/persistence-effect-settle.test.ts; test/e2e/w5-persistence-postgres.test.ts runs them on Postgres.
+ */
+import { expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { basename, dirname, join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+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 { retryParkedEffects } from '../../src/core/persistence/effect-retry.ts';
+import { retrySourceParkedCode, retrySourceParkedPushes } from '../../src/core/persistence/git-durability-administration.ts';
+import { settleEffects } from '../../src/core/persistence/effect-settle.ts';
+import { readParkedGroups } from '../../src/core/persistence/parked-groups.ts';
+import { readGitPushHolds } from '../../src/core/persistence/git-push-holds.ts';
+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-root.ts';
+import { checkParkedEffects } from '../../src/commands/doctor/checks/parked-effects.ts';
+import { managedBrain } from './managed-brain.ts';
+import { durableGitRepo, git } from './git-publication.ts';
+import { withEnv } from './with-env.ts';
+
+const put = async (ctx: OperationContext, slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',
+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${body}\n`,
+ ...await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }).then(page => page ? { expected_revision: page.revision } : {}) } });
+type Effect = { id: number; request_id: string; internal_id: string; kind: string; state: string; error_code: string | null; worktree_id: string;
+ source_incarnation: string; recovery: unknown; data: Record<string, unknown>; outcome: Record<string, unknown> | null };
+const effects = async (engine: BrainEngine, slug: string) => engine.executeRaw<Effect>(`SELECT e.id,r.request_id::text AS request_id,r.id::text AS internal_id,
+ e.kind,e.state,e.error_code,e.worktree_id::text AS worktree_id,e.source_incarnation::text AS source_incarnation,e.recovery,e.data,e.outcome
+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind IN ('git','withdrawal-mirror') AND r.slug=$1 ORDER BY e.id`, [slug]);
+const effectById = async (engine: BrainEngine, id: number) => (await engine.executeRaw<Effect>(`SELECT e.id,e.kind,e.state,e.error_code,e.worktree_id::text AS worktree_id,
+ e.source_incarnation::text AS source_incarnation,e.recovery,e.data,e.outcome FROM persistence_effects e WHERE e.id=$1`, [id]))[0]!;
+async function sql(engine: BrainEngine, statement: string, params: unknown[]) {
+ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(statement, params); });
+}
+/** Puts one effect back to a fresh queued state with the given data (the resident consumer stopped). */
+async function resetEffect(engine: BrainEngine, id: number, data: Record<string, unknown>) {
+ await disposePersistenceConsumer(engine);
+ await sql(engine, `UPDATE persistence_effects SET data=$2::text::jsonb,state='queued',attempts=0,execution_token=NULL,
+ claim_expires_at=NULL,error_code=NULL,outcome=NULL WHERE id=$1`, [id, JSON.stringify(data)]);
+}
+/** Runs one effect attempt at a time with every other effect deferred. */
+async function runOnly(engine: BrainEngine, ctx: OperationContext, id: number, times = 1) {
+ await disposePersistenceConsumer(engine);
+ for (let i = 0; i < times; i++) {
+ await sql(engine, "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 });
+ }
+}
+const target = (effect: Effect) => ({ slug: effect.data.slug, page_id: effect.data.page_id, relative_path: effect.data.relative_path, expected_hash: effect.data.expected_hash });
+/** The rows a settlement must never change: the failure, its targets and the request. */
+const history = async (engine: BrainEngine, id: number) => {
+ const effect = await effectById(engine, id);
+ const [request] = await engine.executeRaw<Record<string, unknown>>(`SELECT r.state,r.intent,r.authority,r.slug FROM persistence_requests r
+ JOIN persistence_effects e ON e.request_id=r.id WHERE e.id=$1`, [id]);
+ return { state: effect.state, error_code: effect.error_code, parked: effect.data.parked ?? null, relative_path: effect.data.relative_path,
+ expected_hash: effect.data.expected_hash, worktree_id: effect.worktree_id, request };
+};
+
+const dbOnly = (root: string, prefix: string) => writeFileSync(join(root, 'gbrain.yml'), `storage:\n db_only:\n - ${prefix}\n`);
+const gitRepo = (root: string) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+
+/** #7423: a target parked on git_target_unsafe whose prefix is declared db_only afterwards re-parks on every retry; settle is its exit. */
+export async function dbOnlyTargetSettles(databaseUrl?: string) {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ await put(ctx, 'aa/page', 'Becomes database-only.');
+ const file = join(root, 'aa/page.md');
+ const bytes = readFileSync(file);
+ rmSync(file); mkdirSync(file);
+ const [effect] = await effects(engine, 'aa/page');
+ await resetEffect(engine, effect!.id, target(effect!));
+ await runOnly(engine, ctx, effect!.id, 5);
+ expect(await effectById(engine, effect!.id)).toMatchObject({ state: 'failed', error_code: 'targets_parked',
+ data: { parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });
+ dbOnly(root, 'aa/');
+ expect(await retrySourceParkedCode(engine, 'default', 'git_target_unsafe', false)).toMatchObject({ requests: 1, queued: 1 });
+ await runOnly(engine, ctx, effect!.id, 5);
+ expect(await effectById(engine, effect!.id)).toMatchObject({ state: 'failed', error_code: 'targets_parked',
+ data: { parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });
+ const before = await history(engine, effect!.id);
+ expect((await checkParkedEffects(engine)).message).toContain('gbrain sources writer settle-effects default --parked-code git_target_unsafe --dry-run');
+
+ const preview = await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe' });
+ expect(preview).toMatchObject({ action: 'writer_settle_effects', mode: 'settle', dry_run: true, settleable: 1, refused: 0,
+ effects: [{ request_id: effect!.request_id, action: 'would_settle', proof: { kind: 'db_only', targets: [{ slug: 'aa/page', declared: 'aa/' }] } }] });
+ expect(preview.plan_hash).toMatch(/^ph_/);
+ expect(preview.apply_command).toEqual(['gbrain', 'sources', 'writer', 'settle-effects', 'default', '--parked-code', 'git_target_unsafe', '--apply', '--expect', preview.plan_hash]);
+ expect(await history(engine, effect!.id)).toEqual(before);
+
+ await expect(settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe', apply: true, expect: 'ph_000000000000000000000000' }))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ await expect(settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe', apply: true }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ expect((await effectById(engine, effect!.id)).data.settled).toBeUndefined();
+
+ const applied = await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe', apply: true, expect: preview.plan_hash });
+ expect(applied).toMatchObject({ dry_run: false, plan_hash: preview.plan_hash, settleable: 1, effects: [{ action: 'settled' }] });
+ expect(await history(engine, effect!.id)).toEqual(before);
+ expect((await effectById(engine, effect!.id)).data).toMatchObject({ settled: { reason: 'db_only', plan_hash: preview.plan_hash, host_id: localHostId(),
+ proof: { kind: 'db_only' } }, settlements: [{ action: 'settled', plan_hash: preview.plan_hash }] });
+ expect(await checkParkedEffects(engine)).toMatchObject({ status: 'ok', details: { parked_effects: 0, parked_groups: [] } });
+ expect(await readParkedGroups(engine)).toEqual([]);
+ expect(await retrySourceParkedCode(engine, 'default', 'git_target_unsafe', true)).toMatchObject({ requests: 0, queued: 0 });
+ expect(await retryParkedEffects(engine, 'default', effect!.request_id, true)).toMatchObject({ effects: [{ kind: 'git', action: 'settled' }] });
+ expect(await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe' })).toMatchObject({ settleable: 0, effects: [] });
+
+ const undo = await settleEffects(engine, { sourceId: 'default', requestId: effect!.request_id, unsettle: true });
+ expect(undo).toMatchObject({ mode: 'unsettle', dry_run: true, settleable: 1, effects: [{ action: 'would_unsettle', settled: { reason: 'db_only' } }] });
+ await expect(settleEffects(engine, { sourceId: 'default', requestId: effect!.request_id, unsettle: true, apply: true, expect: preview.plan_hash }))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ expect(await settleEffects(engine, { sourceId: 'default', requestId: effect!.request_id, unsettle: true, apply: true, expect: undo.plan_hash }))
+ .toMatchObject({ effects: [{ action: 'unsettled' }] });
+ expect(await history(engine, effect!.id)).toEqual(before);
+ const restored = await effectById(engine, effect!.id);
+ expect(restored.data.settled).toBeUndefined();
+ expect(restored.data.settlements).toMatchObject([{ action: 'settled', plan_hash: preview.plan_hash }, { action: 'unsettled', plan_hash: undo.plan_hash, settled: { reason: 'db_only' } }]);
+ expect(await checkParkedEffects(engine)).toMatchObject({ status: 'warn', details: { parked_effects: 1 } });
+
+ rmSync(join(root, 'gbrain.yml'));
+ expect(await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe' })).toMatchObject({ settleable: 0, refused: 1,
+ effects: [{ action: 'refused', refusal: { code: 'retry_instead' } }] });
+ rmSync(file, { recursive: true }); writeFileSync(file, bytes);
+ }, { databaseUrl, setup: ({ root }) => gitRepo(root) });
+}
+
+/** A managed checkout with a tracking remote (a bare repository next to it) and the durability hook. */
+function remoteRepo(root: string): void {
+ const remote = join(dirname(root), 'remote.git');
+ git(dirname(root), 'init', '-q', '--bare', '-b', 'main', remote);
+ writeFileSync(join(root, '.gitignore'), '\n');
+ git(root, 'init', '-q', '-b', 'main');
+ durableGitRepo(root, ['.gitignore']);
+ git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');
+}
+const brokenRemote = (root: string) => git(root, 'remote', 'set-url', 'origin', join(dirname(root), 'missing.git'));
+
+/**
+ * #7378: Git effects bound to a former canonical worktree (one parked on a push, one failed on a push without parked
+ * targets) are refused by the binding guard. After the source moves to a new worktree through a rebind and genuine
+ * updates commit and push the current bytes, settle proves each exact path against the fetched remote branch.
+ */
+export async function formerWorktreeEffectsSettle(databaseUrl?: string) {
+ await withEnv({ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, () => managedBrain(async ({ engine, ctx, root }) => {
+ const remote = join(dirname(root), 'remote.git');
+ brokenRemote(root);
+ await put(ctx, 'aa/page', 'First version.');
+ await put(ctx, 'bb/page', 'First version.');
+ const [parked] = await effects(engine, 'aa/page');
+ await resetEffect(engine, parked!.id, target(parked!));
+ await runOnly(engine, ctx, parked!.id, 5);
+ expect(await effectById(engine, parked!.id)).toMatchObject({ state: 'failed', error_code: 'targets_parked',
+ data: { parked: [{ slug: 'aa/page', error_code: 'git_push_unavailable' }] } });
+ const [failed] = await effects(engine, 'bb/page');
+ await sql(engine, `UPDATE persistence_effects SET state='failed',error_code='git_push_unavailable',execution_token=NULL,claim_expires_at=NULL,
+ data=$2::text::jsonb WHERE id=$1`, [failed!.id, JSON.stringify(target(failed!))]);
+ const old = (await getWorktreeBinding(engine, 'default'))!;
+
+ const moved = join(dirname(root), 'moved');
+ cpSync(root, moved, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) });
+ await disposePersistenceConsumer(engine);
+ await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'default', path: moved });
+ const current = (await getWorktreeBinding(engine, 'default'))!;
+ expect(current.worktree_id).not.toBe(old.worktree_id);
+ expect(current.source_incarnation).toBe(old.source_incarnation);
+ for (const effect of [parked!, failed!]) {
+ await expect(retryParkedEffects(engine, 'default', effect.request_id, true)).rejects.toMatchObject({ code: 'source_changed' });
+ }
+ const settleArgv = ['gbrain', 'sources', 'writer', 'settle-effects', 'default', '--parked-code', 'git_push_unavailable', '--dry-run'];
+ expect(await readGitPushHolds(engine, ['default'])).toMatchObject([{ source_id: 'default', parked: 2, former_worktree: true, fix: { argv: settleArgv } }]);
+ const pushes = await retrySourceParkedPushes(engine, 'default', true);
+ expect(pushes).toMatchObject({ requests: 0, queued: 0, former_worktree: { effects: 2, command: settleArgv } });
+ expect(String((pushes.former_worktree as { why: string }).why)).toContain('former canonical worktree');
+
+ const refusals = async () => Object.fromEntries(((await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_push_unavailable' })).effects as Array<{
+ request_id: string; refusal?: { code: string } }>).map(entry => [entry.request_id === parked!.request_id ? 'aa' : 'bb', entry.refusal?.code ?? 'settleable']));
+ expect(await refusals()).toEqual({ aa: 'no_covering_receipt', bb: 'no_covering_receipt' });
+
+ brokenRemote(moved);
+ await put(ctx, 'aa/page', 'Second version.');
+ const [, update] = await effects(engine, 'aa/page');
+ expect(update!.worktree_id).toBe(current.worktree_id);
+ await runOnly(engine, ctx, update!.id);
+ expect((await effectById(engine, update!.id)).state).toBe('queued');
+ expect(await refusals()).toEqual({ aa: 'bytes_unpushed', bb: 'no_covering_receipt' });
+
+ git(moved, 'remote', 'set-url', 'origin', remote);
+ await runOnly(engine, ctx, update!.id);
+ expect(await effectById(engine, update!.id)).toMatchObject({ state: 'committed', outcome: { push: 'committed' } });
+ await put(ctx, 'bb/page', 'Second version.');
+ const [, other] = await effects(engine, 'bb/page');
+ await runOnly(engine, ctx, other!.id);
+ expect(await effectById(engine, other!.id)).toMatchObject({ state: 'committed', outcome: { push: 'committed' } });
+ expect(await refusals()).toEqual({ aa: 'settleable', bb: 'settleable' });
+
+ const tip = git(moved, 'rev-parse', 'refs/remotes/origin/main').trim();
+ git(moved, 'update-ref', 'refs/remotes/origin/main', `${tip}~1`);
+ expect((await refusals()).bb).toBe('remote_ref_stale');
+ git(moved, 'update-ref', '-d', 'refs/remotes/origin/main');
+ expect((await refusals()).bb).toBe('remote_ref_missing');
+ git(moved, 'update-ref', 'refs/remotes/origin/main', tip);
+ const file = join(moved, 'bb/page.md');
+ const bytes = readFileSync(file);
+ writeFileSync(file, `${bytes}Uncoordinated edit.\n`);
+ expect((await refusals()).bb).toBe('content_changed');
+ rmSync(file);
+ expect((await refusals()).bb).toBe('content_missing');
+ writeFileSync(file, bytes);
+ await sql(engine, 'UPDATE persistence_effects SET source_incarnation=$2::uuid WHERE id=$1', [failed!.id, randomUUID()]);
+ expect((await refusals()).bb).toBe('source_replaced');
+ await sql(engine, 'UPDATE persistence_effects SET source_incarnation=$2::uuid WHERE id=$1', [failed!.id, failed!.source_incarnation]);
+ await sql(engine, `UPDATE persistence_effects SET recovery='{"version":1}'::jsonb WHERE id=$1`, [failed!.id]);
+ expect((await refusals()).bb).toBe('recovery_open');
+ await sql(engine, 'UPDATE persistence_effects SET recovery=NULL WHERE id=$1', [failed!.id]);
+ await sql(engine, 'UPDATE persistence_local_writers SET revoked_at=now() WHERE id=(SELECT principal_id::uuid FROM persistence_requests WHERE id=$1::uuid)', [failed!.internal_id]);
+ expect(await refusals()).toEqual({ aa: 'authority_changed', bb: 'authority_changed' });
+ await sql(engine, 'UPDATE persistence_local_writers SET revoked_at=NULL WHERE id=(SELECT principal_id::uuid FROM persistence_requests WHERE id=$1::uuid)', [failed!.internal_id]);
+ await sql(engine, 'UPDATE persistence_effects SET execution_token=$2::uuid WHERE id=$1', [failed!.id, randomUUID()]);
+ expect((await refusals()).bb).toBe('claimed');
+ await sql(engine, 'UPDATE persistence_effects SET execution_token=NULL WHERE id=$1', [failed!.id]);
+ await sql(engine, 'UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [current.worktree_id, randomUUID()]);
+ expect(await refusals()).toEqual({ aa: 'owner_unavailable', bb: 'owner_unavailable' });
+ await sql(engine, 'UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [current.worktree_id, localHostId()]);
+ expect(await refusals()).toEqual({ aa: 'settleable', bb: 'settleable' });
+
+ const before = await Promise.all([parked!, failed!].map(effect => history(engine, effect.id)));
+ const preview = await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_push_unavailable' });
+ expect(preview).toMatchObject({ settleable: 2, refused: 0 });
+ const proof = (preview.effects as Array<{ request_id: string; proof: Record<string, unknown> }>).find(entry => entry.request_id === failed!.request_id)!.proof;
+ expect(proof).toMatchObject({ kind: 'superseded_remote', former_worktree_id: old.worktree_id, worktree_id: current.worktree_id,
+ targets: [{ slug: 'bb/page', path: 'bb/page.md', remote_ref: 'refs/remotes/origin/main', remote_commit: tip,
+ blob: git(moved, 'rev-parse', `${tip}:bb/page.md`).trim(), receipt_request_id: other!.request_id }] });
+ git(moved, 'update-ref', 'refs/remotes/origin/main', `${tip}~1`);
+ await expect(settleEffects(engine, { sourceId: 'default', parkedCode: 'git_push_unavailable', apply: true, expect: preview.plan_hash }))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ git(moved, 'update-ref', 'refs/remotes/origin/main', tip);
+ expect(await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_push_unavailable', apply: true, expect: preview.plan_hash }))
+ .toMatchObject({ settleable: 2, effects: [{ action: 'settled' }, { action: 'settled' }] });
+ expect(await Promise.all([parked!, failed!].map(effect => history(engine, effect.id)))).toEqual(before);
+ expect(await checkParkedEffects(engine)).toMatchObject({ status: 'ok', details: { parked_effects: 0, git_push_holds: [] } });
+ expect(await retrySourceParkedPushes(engine, 'default', true)).not.toHaveProperty('former_worktree');
+ for (const effect of [parked!, failed!]) await expect(retryParkedEffects(engine, 'default', effect.request_id, true)).rejects.toMatchObject({ code: 'source_changed' });
+ }, { databaseUrl, setup: ({ root }) => remoteRepo(root) }));
+}
+
+/** #7378: a withdrawal effect is never settled, whatever its target. */
+export async function withdrawalEffectRefuses(databaseUrl?: string) {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ await put(ctx, 'aa/page', 'Becomes database-only.');
+ const [effect] = await effects(engine, 'aa/page');
+ await disposePersistenceConsumer(engine);
+ await sql(engine, `UPDATE persistence_effects SET kind='withdrawal-mirror',state='failed',error_code='targets_parked',
+ data=data||'{"parked":[{"slug":"aa/page","error_code":"git_target_unsafe"}]}'::jsonb WHERE id=$1`, [effect!.id]);
+ dbOnly(root, 'aa/');
+ expect(await settleEffects(engine, { sourceId: 'default', requestId: effect!.request_id })).toMatchObject({ settleable: 0, refused: 1,
+ effects: [{ kind: 'withdrawal-mirror', action: 'refused', refusal: { code: 'withdrawal_effect' } }] });
+ expect(await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_target_unsafe' })).toMatchObject({ settleable: 0, refused: 1 });
+ }, { databaseUrl, setup: ({ root }) => gitRepo(root) });
+}
+
+/** #7378: a push of the current binding that failed without parked targets is reachable by --parked-pushes, and commits. */
+export async function failedCurrentPushRetries(databaseUrl?: string) {
+ await withEnv({ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, () => managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'aa/page', 'Pushed later.');
+ const [effect] = await effects(engine, 'aa/page');
+ await disposePersistenceConsumer(engine);
+ await sql(engine, `UPDATE persistence_effects SET state='failed',error_code='git_push_unavailable',execution_token=NULL,claim_expires_at=NULL,
+ data=$2::text::jsonb,outcome=NULL WHERE id=$1`, [effect!.id, JSON.stringify(target(effect!))]);
+ expect(await readGitPushHolds(engine, ['default'])).toMatchObject([{ parked: 1, former_worktree: false,
+ fix: { argv: ['gbrain', 'sources', 'writer', 'retry-effects', 'default', '--parked-pushes'] } }]);
+ expect(await settleEffects(engine, { sourceId: 'default', parkedCode: 'git_push_unavailable' })).toMatchObject({ settleable: 0,
+ effects: [{ action: 'refused', refusal: { code: 'retry_instead' } }] });
+ expect(await retrySourceParkedPushes(engine, 'default', true)).toMatchObject({ requests: 1, queued: 1, refused: [] });
+ expect(await effectById(engine, effect!.id)).toMatchObject({ state: 'failed', error_code: 'git_push_unavailable' });
+ expect(await retrySourceParkedPushes(engine, 'default', false)).toMatchObject({ requests: 1, queued: 1, refused: [] });
+ expect(await effectById(engine, effect!.id)).toMatchObject({ state: 'queued', data: { retried: 1 } });
+ await runOnly(engine, ctx, effect!.id);
+ expect(await effectById(engine, effect!.id)).toMatchObject({ state: 'committed', outcome: { push: 'committed' } });
+ expect(await checkParkedEffects(engine)).toMatchObject({ status: 'ok', details: { git_push_holds: [] } });
+ }, { databaseUrl, setup: ({ root }) => remoteRepo(root) }));
+}
diff --git a/test/persistence-effect-settle.test.ts b/test/persistence-effect-settle.test.ts
new file mode 100644
index 0000000000..d8f5924867
--- /dev/null
+++ b/test/persistence-effect-settle.test.ts
@@ -0,0 +1,26 @@
+/**
+ * #7423 / #7378 on PGLite: settling Git effects whose retry can never succeed, and retrying a failed push of the
+ * current binding. Scenario bodies: test/helpers/effect-settle-scenarios.ts. Postgres arm:
+ * test/e2e/w5-persistence-postgres.test.ts.
+ */
+import { expect, test } from 'bun:test';
+import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { dbOnlyTargetSettles, failedCurrentPushRetries, formerWorktreeEffectsSettle, withdrawalEffectRefuses } from './helpers/effect-settle-scenarios.ts';
+
+test('#7423 a parked target declared db_only afterwards settles on proof, stays in history, and unsettles', () => dbOnlyTargetSettles(), 180_000);
+test('#7378 former-worktree Git effects settle only when the fetched remote holds the current bytes', () => formerWorktreeEffectsSettle(), 240_000);
+test('#7378 a withdrawal effect never settles', () => withdrawalEffectRefuses(), 120_000);
+test('#7378 a failed push of the current binding without parked targets is retried by --parked-pushes', () => failedCurrentPushRetries(), 120_000);
+
+test('settle-effects parses to the writer_settle_effects extension and refuses conflicting or malformed flags before reading', async () => {
+ const hash = 'ph_0123456789abcdef01234567';
+ expect(parsePersistenceAdminArgs('writer', ['settle-effects', 'source-a', '--parked-code', 'git_target_unsafe', '--unsettle', '--apply', '--expect', hash, '--json'])).toEqual({
+ operation: 'writer_settle_effects', json: true, brain: undefined,
+ params: { source_id: 'source-a', parked_code: 'git_target_unsafe', unsettle: true, apply: true, expect: hash } });
+ const engine = {} as Parameters<typeof runPersistenceAdministration>[0];
+ for (const params of [{ source_id: 'source-a', parked_code: 'x', apply: true, dry_run: true }, { source_id: 'source-a', parked_code: 'Bad Code' },
+ { source_id: 'source-a', parked_code: 'x', apply: true, expect: 'not-a-hash' }, { source_id: 'source-a', request_id: 'nope' }, { source_id: 'source-a', force: true }]) {
+ await expect(runPersistenceAdministration(engine, 'writer_settle_effects', params)).rejects.toMatchObject({ code: 'invalid_params' });
+ }
+});
diff --git a/test/writer-failures-cli-6650.test.ts b/test/writer-failures-cli-6650.test.ts
index b208b61b1e..b94cb1eb7e 100644
--- a/test/writer-failures-cli-6650.test.ts
+++ b/test/writer-failures-cli-6650.test.ts
@@ -126,16 +126,17 @@ describe('capability handshake across releases', () => {
'company_brain_resume', 'writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',
'trust_read', 'trust_preview', 'trust_apply'];
- test('a new owner keeps the frozen list and advertises writer_failures and writer_transfer_cancel as extensions', async () => {
+ test('a new owner keeps the frozen list and advertises writer_failures, writer_transfer_cancel and writer_settle_effects as extensions', async () => {
expect([...PERSISTENCE_ADMIN_OPERATIONS as readonly string[]].sort()).toEqual([...FROZEN].sort());
const path = socketPath();
const binding = await startPersistenceIpcServer(path, { brainId: BRAIN, dispatch: async () => ({}), administer: async () => ({}) });
bindings.push(binding!);
const capability = await requestPersistenceCapabilities(path);
expect((capability.administration ?? []).every(op => FROZEN.includes(op))).toBe(true);
- expect(capability.administration_extensions).toEqual(['writer_failures', 'writer_transfer_cancel']);
+ expect(capability.administration_extensions).toEqual(['writer_failures', 'writer_transfer_cancel', 'writer_settle_effects']);
expect(ownerAdministers(capability, 'writer_failures')).toBe(true);
expect(ownerAdministers(capability, 'writer_transfer_cancel')).toBe(true);
+ expect(ownerAdministers(capability, 'writer_settle_effects')).toBe(true);
expect(ownerAdministers(capability, 'writer_status')).toBe(true);
});