Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(w3): lane Postgres arms, PGLite setup in beforeAll, read-only verify, split W3 key-files cluster, keep runManagedSync under 300 lines

garrytanfec48515a15b
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index f5c045abdc..3c80b423a1 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -45,6 +45,7 @@ boundary and add its link here rather than raising the cap.
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, database-write, attribution, purge-deleted and loop-fact retirement |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding |
+| [Managed sync and persistence stalls (key files cluster)](key-files/persistence-stalls.md) | `claim-phase.ts`, `pre-activation-release.ts`, `sync-concurrent-write.ts`, `worktree-manifest.ts`, `src/core/hardened-git.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, plus the relational arm and multi-hop chain modules (`relational-recall.ts`, `relational-rerank-pin.ts`, `relational-chain.ts`, `relational-plan.ts`, `hub-dampening.ts`) |
| [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` |
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 76f454b8c2..16e03cc015 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -11,8 +11,6 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. 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 transaction lock. Dry-run reports candidates without deletion. Registration 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 require canonical 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`).
- `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, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--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`. #6122: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`.
-- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`).
-- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
- `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. 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`.
@@ -32,7 +30,6 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`. #6176: every renewal of a single or group claim also stores `claim-phase.ts`'s stamp in the request's `claim_phase` column (v216: phase `preparing` or `publishing`, claim start, phase start and the execution token; group members get their own token), so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor `persistence_write_stall` can name a stuck phase without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`.
-- `src/core/persistence/claim-phase.ts` — #6176: the phase a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim clock in the consumer (single and group routes); `claimPhaseStamp` is the jsonb each claim renewal stores in `persistence_requests.claim_phase` (v216), keyed to the execution token so a later claim never reads an earlier claim's ages. `claimStateOf` reads a row back as `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `resumes_on_its_own` and a `why`. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Tests: `test/persistence-write-stall.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
@@ -62,6 +59,6 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
-- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: the manifest lives in `worktree-manifest.ts` (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v217 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`). Tests: `test/persistence-manifest-git-scope.test.ts`.
+- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
- `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 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`.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
new file mode 100644
index 0000000000..5e20424e7d
--- /dev/null
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -0,0 +1,15 @@
+# Managed sync and persistence stalls (key files cluster)
+
+[Subsystem index](../KEY_FILES.md).
+
+Fix wave 11's managed-sync and persistence modules: claim phases and the
+`persistence_write_stall` doctor check (#6176), releasing a source claimed
+before activation (#6122), the `concurrent_write` sync hold (#6194) and
+Git-scoped writer manifests (#6099). The modules they extend (consumer,
+sync-run, sync-holds, deactivation, source lifecycle) are in
+[core persistence](core-persistence.md).
+
+- `src/core/persistence/claim-phase.ts` — #6176: the phase a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim clock in the consumer (single and group routes); `claimPhaseStamp` is the jsonb each claim renewal stores in `persistence_requests.claim_phase` (v216), keyed to the execution token so a later claim never reads an earlier claim's ages. `claimStateOf` reads a row back as `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `resumes_on_its_own` and a `why`. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Tests: `test/persistence-write-stall.test.ts`.
+- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`).
+- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
+- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v217 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`). Tests: `test/persistence-manifest-git-scope.test.ts`.
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index 1ca53dced4..6d3cfa76ae 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -68,7 +68,7 @@ async function preActivationClaimRefusal(engine: BrainEngine, sourceId: string):
preview_argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'], consent: ['destructive'], actor: 'agent', requires_exclusive: false,
why: 'Releases every source claimed before activation (bindings removed, worktrees retired, a topology change recorded); the brain stays classic and the next gbrain sync runs in classic mode.',
user_message: `Source ${sourceId} was claimed for managed writes, but managed persistence was never turned on, so sync is blocked. Release the claim and go back to classic sync, or turn managed persistence on?`,
- verify: { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] }, docs: 'docs/architecture/topologies.md#deactivate-runbook' } });
+ verify: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }, docs: 'docs/architecture/topologies.md#deactivate-runbook' } });
}
export async function assertManagedSyncActive(engine: BrainEngine, lock = false): Promise<void> {
const [brain] = await engine.executeRaw<{ enabled: boolean }>(`SELECT enabled FROM persistence_brain WHERE singleton=1${lock ? ' FOR SHARE' : ''}`);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index bd5d8c4268..614afaf786 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -698,6 +698,19 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
return { cursor: saved };
}
+/**
+ * A single-path admission that lost its cursor resolves to null (the caller re-reads the cursor): ENG-A7's
+ * CursorMoved, or #6075's idempotency_conflict when a bulk pass admitted the head first with its grouped intent.
+ */
+async function cursorMovedAdmission(engine: BrainEngine, key: string, admitting: Cursor, pending: Pending, error: unknown): Promise<null> {
+ if (error instanceof CursorMoved) return null;
+ if (error instanceof OperationError && error.code === 'idempotency_conflict') {
+ const current = await readCursor(engine, key, admitting);
+ if (current?.pending?.requestId === pending.requestId && digest(current.pending.intent) !== digest(pending.intent)) return null;
+ }
+ throw error;
+}
+
/** A finished cursor is deleted (compare-and-swap) before the next run discovers; returns whichever cursor replaced it. */
async function retireCompletedCursor(engine: BrainEngine, key: string, completed: Cursor, assertActive: () => void): Promise<Cursor | null> {
await engine.transaction(async tx => {
@@ -969,15 +982,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();
assertActive();
return accepted;
- })).catch(async error => {
- if (error instanceof CursorMoved) return null;
- // #6075: the group admitted this request first with its grouped intent; re-read the cursor instead of failing the pass.
- if (error instanceof OperationError && error.code === 'idempotency_conflict') {
- const current = await readCursor(engine, key, admitting);
- if (current?.pending?.requestId === pending.requestId && digest(current.pending.intent) !== digest(pending.intent)) return null;
- }
- throw error;
- });
+ })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));
if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
await validateSyncAuthority(engine, cursor.authority, pending.slug);
assertSyncDispatchActive();
diff --git a/test/persistence-write-stall.test.ts b/test/persistence-write-stall.test.ts
index 772a1b3b4b..b831c9e8b4 100644
--- a/test/persistence-write-stall.test.ts
+++ b/test/persistence-write-stall.test.ts
@@ -4,7 +4,7 @@
* (claim-phase.ts), `gbrain sources writer status` names it, and doctor's `persistence_write_stall` warns once
* a claim is older than `persistence.max_claim_ms`. PGLite always; Postgres when DATABASE_URL is set.
*/
-import { afterAll, describe, expect, setSystemTime, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, setSystemTime, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -99,19 +99,19 @@ function harness(kind: 'pglite' | 'postgres'): HarnessConfig {
sourceIds: ['write-stall', 'write-stall-other'], principalIds: [randomUUID()] };
}
-test('PGLite: a hung publication is named by writer status and doctor persistence_write_stall', async () => {
- const config = harness('pglite');
- await withEnv({ GBRAIN_HOME: config.root, GBRAIN_PERSISTENCE_FIXTURE_HOME: config.root }, async () => {
- const engine = new PGLiteEngine();
- await engine.connect({});
- try {
- await engine.initSchema();
+describe('PGLite', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+ afterAll(async () => { await engine.disconnect(); });
+ test('a hung publication is named by writer status and doctor persistence_write_stall', async () => {
+ const config = harness('pglite');
+ await withEnv({ GBRAIN_HOME: config.root, GBRAIN_PERSISTENCE_FIXTURE_HOME: config.root }, async () => {
selectFixtureHost(config.hostId);
await initializeFixtures(engine, config);
await scenario(engine, config);
- } finally { await engine.disconnect(); }
- });
-}, 120_000);
+ });
+ }, 120_000);
+});
describe.skipIf(!process.env.DATABASE_URL)('Postgres', () => {
test('a hung publication is named by writer status and doctor persistence_write_stall', async () => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3595e8dde7..d72e2fb8c6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -47,6 +47,7 @@ test/managed-sweep-refused-window-retry.test.ts
test/managed-sweep-timeline.test.ts
test/managed-sync-bulk.test.ts
test/managed-sync-chunker-version.test.ts
+test/managed-sync-concurrent-write-hold.test.ts
test/managed-sync-drain.test.ts
test/managed-sync-group-completion.test.ts
test/managed-sync-images-5493.test.ts
@@ -65,14 +66,18 @@ test/persistence-history-fixture.test.ts
test/persistence-image-import.serial.test.ts
test/persistence-managed-lifecycle.test.ts
test/persistence-managed-sync.test.ts
+test/persistence-manifest-git-scope.test.ts
test/persistence-memory-mutations.test.ts
test/persistence-page-authority.test.ts
test/persistence-physical-root-device.test.ts
+test/persistence-preactivation-claim.test.ts
+test/persistence-reconcile-git-dirty-6138.test.ts
test/persistence-skill-bundles.serial.test.ts
test/persistence-skill-crash.slow.test.ts
test/persistence-sync-cursor-options.test.ts
test/persistence-sync-fence-holds.test.ts
test/persistence-sync-holds.test.ts
+test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
test/repair-embedding-effects.test.ts
test/repair-frontmatter.test.ts