Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/capy/fix-wave-11 (bd881b54d: W1, W2, W4, W5) into capy/fix-wave-11-w3; renumber W3 migrations to v217 (claim_phase) and v218 (manifest purge)

garrytan7ede892de49d
diff --cc docs/architecture/key-files/core-persistence.md
index 16e03cc015,52da96c0b5..14e1603722
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@@ -29,7 -29,7 +29,7 @@@ Connector ingestion, item holds and che
- `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/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`.
++- `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 (v217: 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/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`.
diff --cc docs/architecture/key-files/persistence-stalls.md
index 5e20424e7d,0000000000..7f68d57b0e
mode 100644,000000..100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@@ -1,15 -1,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/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` (v217), 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`.
++- `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 v218 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 --cc docs/architecture/topologies.md
index 606d81ebb9,e94f8ccc51..e813dedb8d
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@@ -454,26 -454,6 +454,26 @@@ intent and state checks. Explicit nonin
procedure and preconditions. A transfer still requires the prepared epoch and an
exact successor manifest; stale heartbeats never authorize takeover.
+<a id="transfer-manifest-scope"></a>**What the manifest covers.** In a Git checkout, the transfer, `sources
+set-path` (rebind), clone and reclone manifest covers the files Git tracks
+(`git ls-files --cached`), hashed from their bytes in the working tree; a
+tracked file missing on disk counts as deleted (#6099). Files Git ignores (such
+as `.env.local` or `node_modules`) are never opened, hashed or stored, and never
+need copying: a clean `git clone` of the same commit verifies. Untracked files
+that Git does not ignore are not covered; `transfer prepare` reports how many as
+`untracked_files` with a warning to commit or ignore them. Git runs with the
+checkout's own hooks, fsmonitor and submodule recursion disabled. Symlinks and
+submodules refuse with `writer_manifest_unsafe`. A directory that is not the top
+of its own Git work tree keeps the exact-copy manifest over every file. A
+mismatch names the first differing paths for a local rebind (tracked paths only
+in a Git checkout). A transfer an older release prepared covers every file,
+ignored ones included; if the successor is a Git checkout and does not match,
+accept refuses `writer_manifest_rescope_required`: prepare the transfer again
+on the owner host instead of copying ignored files. Upgrading removes the
+per-file path and hash maps releases before v0.60.69 stored with prepared
- transfers and clone recovery records (migration v217); only digests and counts
++transfers and clone recovery records (migration v218); only digests and counts
+remain.
+
Live, young or foreign legacy locks block activation regardless of expiry. For
exact dead same-host holders only, preview with
`--cleanup-dead-local-locks --dry-run` and explicitly opt in on the reviewed
diff --cc src/core/cli-flag-registry.generated.ts
index 4408a97793,47cf995d3f..8cf78540f0
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -72,10 -72,10 +72,10 @@@ export const CLI_FLAG_REGISTRY: Record<
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--path', '--pglite', '--plan', '--prefer-postgres', '--preview', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],
++ 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
diff --cc src/core/persistence/claim-phase.ts
index 76edfea5e6,0000000000..76b3dabe67
mode 100644,000000..100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@@ -1,103 -1,0 +1,103 @@@
+/**
+ * #6176: which phase a running write request's claim is in, and how long it
+ * has been there, so a stall names its phase instead of `cause_unknown`.
+ *
+ * The consumer keeps a `ClaimPhaseClock` per claim and every claim renewal
+ * (claim-lease.ts cadence, 10 s) stores `claimPhaseStamp` in the request's
- * `claim_phase` column (v216): the phase, the claim start, the phase start and
++ * `claim_phase` column (v217): the phase, the claim start, the phase start and
+ * the execution token, so a later claim of the same request never reads an
+ * earlier claim's ages. Recording rides the renewal: no extra statement per write.
+ *
+ * `claimStateOf` reads a request row back. A claim whose renewal cannot reach
+ * its row (it lapsed while still `running`) is inside a transaction that holds
+ * the row, or its owner is gone; `publication_started` means files were being
+ * published and the recovery path finishes the request.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export type ClaimPhaseName = 'preparing' | 'publishing';
+export interface ClaimPhaseClock { phase: ClaimPhaseName; claimedAt: number; since: number }
+
+export function startClaimPhase(now = Date.now()): ClaimPhaseClock {
+ return { phase: 'preparing', claimedAt: now, since: now };
+}
+export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, now = Date.now()): void {
+ if (clock.phase === phase) return;
+ clock.phase = phase;
+ clock.since = now;
+}
+/** The `claim_phase` jsonb a renewal stores for the claim holding `token`. */
+export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null): string {
+ return JSON.stringify({ phase: clock.phase, claimed_at: new Date(clock.claimedAt).toISOString(), since: new Date(clock.since).toISOString(), token });
+}
+
+/** `persistence.max_claim_ms`: how long a write may hold its claim before doctor reports it as stalled. */
+export const MAX_CLAIM_CONFIG_KEY = 'persistence.max_claim_ms';
+export const MAX_CLAIM_DEFAULT_MS = 600_000;
+const MAX_CLAIM_MIN_MS = 60_000;
+const MAX_CLAIM_MAX_MS = 86_400_000;
+
+export function parseMaxClaimMs(raw: string | null | undefined): number | null {
+ const text = raw?.trim() ?? '';
+ if (!/^\d+$/.test(text)) return null;
+ const n = Number(text);
+ return n >= MAX_CLAIM_MIN_MS && n <= MAX_CLAIM_MAX_MS ? n : null;
+}
+/** `config set` validation; the refusal text, or null when the value is valid (or the key is another one). */
+export function validateMaxClaimConfigValue(key: string, value: string): string | null {
+ if (key !== MAX_CLAIM_CONFIG_KEY || parseMaxClaimMs(value) !== null) return null;
+ return `invalid_params: ${MAX_CLAIM_CONFIG_KEY} must be a whole number of milliseconds from ${MAX_CLAIM_MIN_MS} to ${MAX_CLAIM_MAX_MS} `
+ + `(default ${MAX_CLAIM_DEFAULT_MS}, 10 minutes; for example gbrain config set ${MAX_CLAIM_CONFIG_KEY} 900000) (got '${value}'). Nothing was written.`;
+}
+export async function readMaxClaimMs(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {
+ return parseMaxClaimMs(await engine.getConfig(MAX_CLAIM_CONFIG_KEY).catch(() => null)) ?? MAX_CLAIM_DEFAULT_MS;
+}
+
+/**
+ * Where a running claim is: `preparing` or `publishing` (recorded by a live
+ * renewal), `publication_transaction` (the claim lapsed while running and
+ * nothing was published yet), `file_publication` (files were being published)
- * or `unrecorded` (no stamp of this claim yet, or an owner that predates v216).
++ * or `unrecorded` (no stamp of this claim yet, or an owner that predates v217).
+ */
+export type ClaimStatePhase = ClaimPhaseName | 'publication_transaction' | 'file_publication' | 'unrecorded';
+export interface ClaimState {
+ phase: ClaimStatePhase;
+ claim_age_ms: number | null;
+ phase_age_ms: number | null;
+ /** Whether the same request continues without anyone acting (after its lease lapses or its transaction ends). */
+ resumes_on_its_own: boolean;
+ why: string;
+}
+export interface ClaimRow {
+ state: string;
+ claim_phase?: unknown;
+ execution_token?: string | null;
+ /** `claim_expires_at < now()`, read on the database clock. */
+ claim_lapsed?: boolean | null;
+ publication_started?: boolean | null;
+}
+
+const age = (at: unknown, now: number): number | null => {
+ const ms = typeof at === 'string' || at instanceof Date ? new Date(at).getTime() : NaN;
+ return Number.isFinite(ms) ? Math.max(0, Math.floor(now - ms)) : null;
+};
+
+export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null {
+ if (row.state !== 'running') return null;
+ const raw = typeof row.claim_phase === 'string' ? safeJson(row.claim_phase) : row.claim_phase;
+ const stamp = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
+ const own = !!stamp && !!row.execution_token && stamp.token === row.execution_token;
+ const claimAge = own ? age(stamp!.claimed_at, now) : null;
+ if (row.publication_started) return { phase: 'file_publication', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: false,
+ why: 'Its files were being published; the publication recovery path restores or finishes them when the owning process scans its roots again (after a restart if it hung).' };
+ if (row.claim_lapsed) return { phase: 'publication_transaction', claim_age_ms: claimAge, phase_age_ms: null, resumes_on_its_own: true,
+ why: 'Its claim lapsed while it was still running and nothing was published: a transaction holds the request row (renewals cannot reach it) or its owner is gone. It is requeued once that transaction ends or the owner process exits.' };
+ if (!own) return { phase: 'unrecorded', claim_age_ms: null, phase_age_ms: null, resumes_on_its_own: false,
+ why: 'The owner has not recorded this claim\'s phase (a claim younger than one renewal, or an owner that predates phase recording).' };
+ const phase = stamp!.phase === 'publishing' ? 'publishing' : 'preparing';
+ return { phase, claim_age_ms: claimAge, phase_age_ms: age(stamp!.since, now), resumes_on_its_own: false,
+ why: `Its owner is still renewing the claim while it is ${phase === 'preparing' ? 'preparing the write' : 'publishing the write'}, so the lease never lapses and nothing else on its root runs until that work settles or the owner restarts.` };
+}
+function safeJson(text: string): unknown {
+ try { return JSON.parse(text); } catch { return null; }
+}
diff --cc src/core/schema-migrations/registry.generated.ts
index 515410417d,8307655707..cfca332ad7
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -216,8 -216,7 +216,9 @@@ import { v212 } from './v212-decide-rev
import { v213 } from './v213-core-edit-notices.ts';
import { v214 } from './v214-wanted-links.ts';
import { v215 } from './v215-facts-attributed-to.ts';
- import { v216 } from './v216-persistence-request-claim-phase.ts';
- import { v217 } from './v217-purge-legacy-worktree-manifest-files.ts';
+ import { v216 } from './v216-chronicle-campaign-stamps.ts';
++import { v217 } from './v217-persistence-request-claim-phase.ts';
++import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -433,5 -432,4 +434,6 @@@ export const MIGRATIONS: Migration[] =
v214,
v215,
v216,
+ v217,
++ v218,
];
diff --cc src/core/schema-migrations/v217-persistence-request-claim-phase.ts
index 375424ccb9,0000000000..c4d73ac846
mode 100644,000000..100644
--- a/src/core/schema-migrations/v217-persistence-request-claim-phase.ts
+++ b/src/core/schema-migrations/v217-persistence-request-claim-phase.ts
@@@ -1,19 -1,0 +1,19 @@@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6176: a running write request records which phase its claim is in
+// (persistence/claim-phase.ts): the consumer's claim renewal stamps the phase,
+// the claim start and the phase start, keyed to the execution token, so
+// `gbrain sources writer status` and the `persistence_write_stall` doctor check
+// can name a stuck phase and its age. Column-only and nullable, no backfill;
+// like v178 and v198 it is migration-created on PGLite and no index references it.
- export const v216: Migration = {
- version: 216,
++export const v217: Migration = {
++ version: 217,
+ name: 'persistence_request_claim_phase',
+ idempotent: true,
+ sql: `
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS claim_phase jsonb;
+ `,
+};
diff --cc src/core/schema-migrations/v218-purge-legacy-worktree-manifest-files.ts
index f11fc45720,0000000000..4054db091c
mode 100644,000000..100644
--- a/src/core/schema-migrations/v218-purge-legacy-worktree-manifest-files.ts
+++ b/src/core/schema-migrations/v218-purge-legacy-worktree-manifest-files.ts
@@@ -1,30 -1,0 +1,30 @@@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6099 (privacy): releases before v0.60.69 stored a writer manifest's full
+// per-file map (`files`: relative path -> unsalted sha256 of the file bytes) in
+// persistence_worktrees.manifest and in clone recovery records
+// (persistence_topology_changes.recovery.manifest). Those maps can name and
+// fingerprint files Git ignores, such as `.env.local`. Nothing reads them: only
+// the digest and file count are compared (persistence/worktree-manifest.ts
+// `compactStoredManifest` keeps exactly those). This drops every remaining map,
+// keeping `file_count` (counted from the map when it was not stored). Data-only
+// and idempotent: a second run matches no row.
- export const v217: Migration = {
- version: 217,
++export const v218: Migration = {
++ version: 218,
+ name: 'purge_legacy_worktree_manifest_files',
+ idempotent: true,
+ sql: `
+ UPDATE persistence_worktrees
+ SET manifest = (manifest - 'files') || jsonb_build_object('file_count',
+ COALESCE(manifest->'file_count', to_jsonb((SELECT count(*) FROM jsonb_object_keys(manifest->'files')))))
+ WHERE jsonb_typeof(manifest) = 'object' AND jsonb_typeof(manifest->'files') = 'object';
+ UPDATE persistence_topology_changes
+ SET recovery = jsonb_set(recovery, '{manifest}', ((recovery->'manifest') - 'files') || jsonb_build_object('file_count',
+ COALESCE(recovery->'manifest'->'file_count', to_jsonb((SELECT count(*) FROM jsonb_object_keys(recovery->'manifest'->'files'))))))
+ WHERE jsonb_typeof(recovery) = 'object' AND jsonb_typeof(recovery->'manifest') = 'object'
+ AND jsonb_typeof(recovery->'manifest'->'files') = 'object';
+ `,
+};
diff --cc test/fixtures/goldens/migrations/records.json
index 6bf4ee0d4c,f0978e676d..7b772fbcf5
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@@ -1,6 -1,6 +1,6 @@@
{
"golden": {
- "count": 212,
- "count": 210,
++ "count": 213,
"gaps": [
17,
18,
@@@ -35,7 -35,7 +35,7 @@@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 217,
- "latest": 215,
++ "latest": 218,
"records": [
{
"handler": {
@@@ -3191,32 -3191,6 +3191,45 @@@
"transaction": "absent",
"verify": "absent",
"version": 215
+ },
++ {
++ "handler": "absent",
++ "idempotent": true,
++ "name": "chronicle_campaign_stamps",
++ "sql": {
++ "length": 559,
++ "sha256": "a8eccca165c3a93ce31f7f1f77cd28f4a0968b0498ba962d07c199bc680942a8"
++ },
++ "sqlFor": "absent",
++ "transaction": "absent",
++ "verify": "absent",
++ "version": 216
++ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "persistence_request_claim_phase",
+ "sql": {
+ "length": 84,
+ "sha256": "830bd460b2c241fe7d09818ad43f630956bc53a9f3e2d66bca5d62750c6d55dd"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 216
++ "version": 217
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "purge_legacy_worktree_manifest_files",
+ "sql": {
+ "length": 798,
+ "sha256": "60e812f52a977b94f1c0a3fa3657a3ec9394f09ff48dbef04550eb2b89f7d084"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 217
++ "version": 218
}
],
"versions": [
@@@ -3429,9 -3403,7 +3442,10 @@@
212,
213,
214,
- 215
+ 215,
+ 216,
- 217
++ 217,
++ 218
]
},
"normalizer": "migrations-record-v1"
diff --cc test/persistence-manifest-git-scope.test.ts
index 0959a8c91a,0000000000..0ad408938f
mode 100644,000000..100644
--- a/test/persistence-manifest-git-scope.test.ts
+++ b/test/persistence-manifest-git-scope.test.ts
@@@ -1,179 -1,0 +1,179 @@@
+/**
+ * #6099 (privacy): a Git checkout's writer manifest covers the files Git tracks, hashed from the working tree.
+ * Gitignored files (secrets, build output) are never opened or hashed, so rebinding to a clean clone works
+ * without copying them; a modified, missing or extra tracked file still refuses; a directory that is not a Git
+ * checkout keeps the exact-copy manifest; a transfer an older release prepared in tree scope refuses with a
- * re-prepare fix instead of asking for ignored files; and migration v217 drops the legacy per-file maps.
++ * re-prepare fix instead of asking for ignored files; and migration v218 drops the legacy per-file maps.
+ * PGLite always; Postgres too when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { isPhysicalRootMetadata } from '../src/core/persistence/physical-root.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { acceptWriterTransfer, getWorktreeBinding, prepareWriterTransfer, successorManifestMismatch, worktreeManifest } from '../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
- import { v217 } from '../src/core/schema-migrations/v217-purge-legacy-worktree-manifest-files.ts';
++import { v218 } from '../src/core/schema-migrations/v218-purge-legacy-worktree-manifest-files.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+function gitCheckout(root: string): void {
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ mkdirSync(join(root, 'node_modules', 'pkg'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, '.gitignore'), '.env.local\nnode_modules/\n');
+ writeFileSync(join(root, 'notes', 'alice-example.md'), '---\ntitle: Alice Example\n---\nWorks at acme-example.\n');
+ writeFileSync(join(root, 'notes', 'acme-example.md'), '---\ntitle: Acme Example\n---\nA company.\n');
+ writeFileSync(join(root, '.env.local'), 'API_TOKEN=not-a-real-token\n');
+ writeFileSync(join(root, 'node_modules', 'pkg', 'index.js'), 'module.exports = 1;\n');
+ git(root, 'add', '.');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+}
+
+test('git scope hashes tracked files only and never opens an ignored one', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-scope-'));
+ try {
+ const root = join(home, 'brain'); gitCheckout(root);
+ // An unreadable ignored file would throw if it were opened.
+ chmodSync(join(root, '.env.local'), 0o000);
+ writeFileSync(join(root, 'notes', 'draft.md'), 'untracked, not ignored\n');
+ const manifest = worktreeManifest(root);
+ expect(manifest).toMatchObject({ scope: 'git', file_count: 3, untracked_count: 1 });
+ const clone = join(home, 'clone'); execFileSync('git', ['clone', '-q', root, clone]);
+ expect(worktreeManifest(clone).digest).toBe(manifest.digest);
+ writeFileSync(join(clone, 'notes', 'alice-example.md'), 'changed\n');
+ expect(worktreeManifest(clone).digest).not.toBe(manifest.digest);
+ git(clone, 'checkout', '-q', '--', 'notes/alice-example.md');
+ rmSync(join(clone, 'notes', 'acme-example.md'));
+ expect(worktreeManifest(clone).digest).not.toBe(manifest.digest);
+ // A plain directory nested inside an unrelated repository keeps the exact-copy tree scope.
+ const nested = join(root, 'notes');
+ expect(worktreeManifest(nested).scope).toBeUndefined();
+ } finally { rmSync(home, { recursive: true, force: true }); }
+});
+
+test('a tracked submodule or symlink refuses writer_manifest_unsafe', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-unsafe-'));
+ try {
+ const root = join(home, 'brain'); gitCheckout(root);
+ execFileSync('ln', ['-s', 'alice-example.md', join(root, 'notes', 'link.md')]);
+ git(root, 'add', 'notes/link.md');
+ expect(() => worktreeManifest(root)).toThrow(expect.objectContaining({ code: 'writer_manifest_unsafe' }));
+ } finally { rmSync(home, { recursive: true, force: true }); }
+});
+
+test('a tree-scope transfer an older release prepared refuses with a re-prepare fix on a Git successor', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-rescope-'));
+ try {
+ const root = join(home, 'clone'); gitCheckout(root);
+ const legacy = { digest: 'a'.repeat(64), file_count: 5 };
+ const error = successorManifestMismatch('notes-example', root, legacy.digest, legacy, worktreeManifest(root, { scope: 'tree' }));
+ expect(error).toMatchObject({ code: 'writer_manifest_rescope_required' });
+ expect((error as { fix?: { argv: string[] } }).fix?.argv.slice(0, 6)).toEqual(['gbrain', 'sources', 'writer', 'transfer', 'prepare', 'notes-example']);
+ expect(error.suggestion).toContain('Do not copy ignored files');
+ const current = successorManifestMismatch('notes-example', root, 'b'.repeat(64), { ...legacy, scope: 'git' }, worktreeManifest(root));
+ expect(current).toMatchObject({ code: 'writer_manifest_mismatch' });
+ expect(current.suggestion).toContain('git clone');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+});
+
+for (const backend of testBackends()) describe(`#6099 git-scoped manifests (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
+
+ async function fixture(run: (home: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-git-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ if (backend === 'pglite') await resetPgliteState(engine as PGLiteEngine);
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try { await run(home); } finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }
+ const sourceId = (name: string) => `${name}-${backend}`;
+
+ test('set-path to a clean clone commits without the ignored files; a changed tracked file names its path', () => fixture(async home => {
+ const id = sourceId('git-rebind');
+ const root = join(home, 'brain'); gitCheckout(root);
+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root })).toMatchObject({ state: 'committed' });
+ const [stored] = await engine.executeRaw<{ manifest: Record<string, unknown> }>(
+ 'SELECT w.manifest FROM persistence_worktrees w JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1', [id]);
+ expect(stored?.manifest).toMatchObject({ scope: 'git', file_count: 3 });
+ expect(JSON.stringify(stored?.manifest)).not.toContain('.env.local');
+
+ const dirty = join(home, 'dirty'); execFileSync('git', ['clone', '-q', root, dirty]);
+ writeFileSync(join(dirty, 'notes', 'acme-example.md'), 'edited\n');
+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: dirty }))
+ .rejects.toMatchObject({ code: 'writer_manifest_mismatch', suggestion: expect.stringContaining('notes/acme-example.md') });
+
+ const clone = join(home, 'clone'); execFileSync('git', ['clone', '-q', root, clone]);
+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: clone })).toMatchObject({ state: 'committed' });
+ expect((await getWorktreeBinding(engine, id))?.local_path).toBe(clone);
+ }), 120_000);
+
+ test('a directory that is not a Git checkout keeps exact-copy semantics', () => fixture(async home => {
+ const id = sourceId('tree-rebind');
+ const root = join(home, 'plain'); mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, 'notes', 'alice-example.md'), 'one\n');
+ writeFileSync(join(root, '.env.local'), 'API_TOKEN=not-a-real-token\n');
+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root })).toMatchObject({ state: 'committed' });
+ const partial = join(home, 'partial');
+ cpSync(root, partial, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) && basename(path) !== '.env.local' });
+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: partial })).rejects.toMatchObject({ code: 'writer_manifest_mismatch' });
+ writeFileSync(join(partial, '.env.local'), 'API_TOKEN=not-a-real-token\n');
+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: partial })).toMatchObject({ state: 'committed' });
+ }), 120_000);
+
+ test('an in-flight transfer prepared in tree scope before the upgrade refuses with a re-prepare fix; re-prepared, a clean clone accepts', () => fixture(async home => {
+ const id = sourceId('legacy-transfer');
+ const root = join(home, 'owner'); gitCheckout(root);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root });
+ const prepared = await prepareWriterTransfer(engine, id);
+ // What an older release stored: the tree-scope digest over every file, ignored ones included, without a scope.
+ const legacy = worktreeManifest(root, { scope: 'tree' });
+ expect(legacy.scope).toBeUndefined();
+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [prepared.worktree_id, JSON.stringify(legacy)]);
+ const clone = join(home, 'successor'); execFileSync('git', ['clone', '-q', root, clone]);
+ await expect(acceptWriterTransfer(engine, id, clone, prepared.owner_epoch, legacy.digest)).rejects.toMatchObject({ code: 'writer_manifest_rescope_required' });
+ const again = await prepareWriterTransfer(engine, id);
+ expect(again.manifest).toMatchObject({ scope: 'git', file_count: 3 });
+ await acceptWriterTransfer(engine, id, clone, again.owner_epoch, again.manifest.digest);
+ expect((await getWorktreeBinding(engine, id))?.local_path).toBe(clone);
+ }), 120_000);
+
- test('migration v217 drops legacy per-file manifest maps and keeps the count; a rerun changes nothing', () => fixture(async home => {
++ test('migration v218 drops legacy per-file manifest maps and keeps the count; a rerun changes nothing', () => fixture(async home => {
+ const id = sourceId('legacy-map');
+ const root = join(home, 'legacy'); gitCheckout(root);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root });
+ const [binding] = await engine.executeRaw<{ worktree_id: string }>('SELECT worktree_id::text FROM persistence_source_bindings WHERE source_id=$1', [id]);
+ const legacy = { digest: 'c'.repeat(64), files: { '.env.local': 'd'.repeat(64), 'notes/a.md': 'e'.repeat(64) }, canonical_stamp: 'stamp' };
+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding!.worktree_id, JSON.stringify(legacy)]);
+ await engine.executeRaw(`INSERT INTO persistence_topology_changes(principal_id,request_id,digest,operation,source_id,state,recovery)
+ VALUES(gen_random_uuid(),gen_random_uuid(),'legacy','reclone',$1,'recovering',$2::text::jsonb)`,
+ [id, JSON.stringify({ kind: 'clone', manifest: { digest: 'f'.repeat(64), files: { '.env.local': 'd'.repeat(64) } } })]);
- await engine.transaction(tx => tx.runMigration(v217.version, v217.sql));
++ await engine.transaction(tx => tx.runMigration(v218.version, v218.sql));
+ const [after] = await engine.executeRaw<{ manifest: Record<string, unknown> }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding!.worktree_id]);
+ expect(after?.manifest).toEqual({ digest: 'c'.repeat(64), file_count: 2, canonical_stamp: 'stamp' });
+ const [record] = await engine.executeRaw<{ manifest: Record<string, unknown> }>(`SELECT recovery->'manifest' AS manifest FROM persistence_topology_changes WHERE source_id=$1 AND digest='legacy'`, [id]);
+ expect(record?.manifest).toEqual({ digest: 'f'.repeat(64), file_count: 1 });
+ await engine.executeRaw(`DELETE FROM persistence_topology_changes WHERE source_id=$1 AND digest='legacy'`, [id]);
- await engine.transaction(tx => tx.runMigration(v217.version, v217.sql));
++ await engine.transaction(tx => tx.runMigration(v218.version, v218.sql));
+ const [again] = await engine.executeRaw<{ manifest: Record<string, unknown> }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding!.worktree_id]);
+ expect(again?.manifest).toEqual(after!.manifest);
+ }), 120_000);
+});