Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Managed sync finishes on a large history, and a refresh left by a killed process stops blocking writes (#9646, #9649) (#9662)
Garry Tan7c97d29df843
diff --git a/behavior-changes.d/orphaned_refresh_reclaim_9649.md b/behavior-changes.d/orphaned_refresh_reclaim_9649.mdnew file mode 100644index 0000000000..c9b0471603--- /dev/null+++ b/behavior-changes.d/orphaned_refresh_reclaim_9649.md@@ -0,0 +1,4 @@+---+kind: fix+---+A gbrain sources refresh whose process is gone and whose row has stayed in syncing for a whole refresh sync budget (sources.refresh_sync_budget_ms, 5 minutes by default) is now completed by the owner on its own, the way a refresh whose budget runs out completes with members still behind. Writes to its sources stop being refused with worktree_refreshing, the row records completed_by owner_reclaim and lists the lagging sources in sync_deferred, and each of those catches up on its next sync. Before, such a row refused every write to the checkout until someone ran gbrain sources refresh. A refresh whose process is still running is never touched.diff --git a/changelog.d/managed-sync-stamp-stuck-refresh-9646-9649.md b/changelog.d/managed-sync-stamp-stuck-refresh-9646-9649.mdnew file mode 100644index 0000000000..31aca8d789--- /dev/null+++ b/changelog.d/managed-sync-stamp-stuck-refresh-9646-9649.md@@ -0,0 +1,7 @@+**A managed source on a large brain finishes its sync again, and a refresh left behind by a killed process stops blocking writes after a few minutes.**++### Fixed+- A sync pass whose source had no recorded watermark could never stamp its checkpoint on a large Postgres brain: the stamp counted fence normalizations over the whole request history inside a transaction bounded at 5 s, was cancelled every time, and so never wrote the watermark that would have ended the scan. The count is now read before the stamp, in small fixed ranges, and the stamp only reads what committed after that, so its 5 s transaction no longer reads the whole history. Raising GBRAIN_STATEMENT_TIMEOUT was never a workaround and is not needed now. Reported by @zm112211mz in #9646; first fix proposed by @Masashi-Ono0611 in #9647.+- A `gbrain sources refresh` killed while syncing its sources left its row in `syncing`, and every write to those sources was refused with `worktree_refreshing` until someone ran `gbrain sources refresh` again. The owner now completes such a refresh once its process is gone and the row has not moved for one refresh sync budget (`sources.refresh_sync_budget_ms`, 5 minutes by default), the same way a refresh whose budget runs out completes; lagging sources catch up on their next sync. A refresh whose process is still running is never touched. Reported by @zm112211mz in #9649.++<!-- behavior-change: orphaned_refresh_reclaim_9649 -->diff --git a/docs/architecture/key-files/core-persistence-git.md b/docs/architecture/key-files/core-persistence-git.mdindex 685fb893d3..f9b5820a0e 100644--- a/docs/architecture/key-files/core-persistence-git.md+++ b/docs/architecture/key-files/core-persistence-git.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.The managed Git writer (`gbrain sources refresh`), git-canonical memory (the git gap census, declared database-only classes, the door) and the checkout reads beside them.-- `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 (#8617: a `refresh_source_changed` for a moved HEAD or work that arrived after the drain check is retried once in the same run from a fresh precheck; a second refusal returns the first with the retry's cause appended), dirt rechecked, `git merge --ff-only`, HEAD verified again (a HEAD that descends from the target after a successful merge, with no member synced off it, counts as merged: a plain-git commit landed in between; a refused fast-forward whose HEAD only gained commits on the start commit aborts `refresh_source_changed`, GST-1674), then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member in one budget (`sources.refresh_sync_budget_ms`; past it a member is `deferred`) (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` / `sync_deferred` when a member blocks or is deferred. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; so does a fenced row whose merge started (`outcome.merge_started_at`, epoch ms) and whose HEAD descends from the old HEAD without the target, when the reflogs of HEAD and its branch show no move to the target since then (git refused the fast-forward, GST-1674; no readable reflog stays `recovery_required`); 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. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host) and a fix naming `--resume`. While the worktree's newest refresh is `aborted`, every run (tick, `--resume`, `--abandon`, even one its precheck refuses) ends by running the managed `--no-pull` sync of each member behind the checkout HEAD (`syncAfterUnfinishedRefresh`, listed in `synced`), so a write held for an import that refresh fenced off is decided in that run, not at a later refresh. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit or on a row recovery would abort (a HEAD moved before the merge, or a refused merge, GST-1674), and never on a `recovery_required` row once a member is past it (`membersPastStart`: a `last_commit` that is not it or an ancestor, GST-1457: the next sync would soft-delete what it synced; or a managed-sync import or delete admitted after the row's `barrier_sequence`, GST-1465: a pass stopped before its stamp), checking and aborting under every member's drain lease (`underMemberLeases`, so a pass in flight refuses `sync_drain_lease_held`), and `--resume` finishes a `recovery_required` row only at a HEAD that contains every member commit on that refresh's line (`adoptsHead`, which `--abandon` also reads to name `--resume` instead of a reset). `keepPagesWayOut` names the way out (GST-1472): a fast-forward to the newest member commit on the target's line, a merge of member commits on diverged lines (ask the user), or a fetch when git cannot place a member commit (`ancestry` tells exit 1 from a failure); the refusals also name the revert route for a deliberate rollback (GST-1477), and off the owner host writer status names no step. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured `fix` when it has one; `refresh_in_progress` carries the writer-status read); 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, and after a refused merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), `test/refresh-barrier-held-after-abort.test.ts` (the sync after an aborted refresh), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified (#8617: a `refresh_source_changed` for a moved HEAD or work that arrived after the drain check is retried once in the same run from a fresh precheck; a second refusal returns the first with the retry's cause appended), dirt rechecked, `git merge --ff-only`, HEAD verified again (a HEAD that descends from the target after a successful merge, with no member synced off it, counts as merged: a plain-git commit landed in between; a refused fast-forward whose HEAD only gained commits on the start commit aborts `refresh_source_changed`, GST-1674), then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member in one budget (`sources.refresh_sync_budget_ms`; past it a member is `deferred`) (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` / `sync_deferred` when a member blocks or is deferred. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; so does a fenced row whose merge started (`outcome.merge_started_at`, epoch ms) and whose HEAD descends from the old HEAD without the target, when the reflogs of HEAD and its branch show no move to the target since then (git refused the fast-forward, GST-1674; no readable reflog stays `recovery_required`); 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. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, or (#9649) once the row has not moved for one refresh sync budget (`sources.refresh_sync_budget_ms`) with the checkout still at the target or a descendant, recording `completed_by: owner_reclaim` and the lagging members in `sync_deferred` as a run whose budget ran out does (#8072), and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host) and a fix naming `--resume`. While the worktree's newest refresh is `aborted`, every run (tick, `--resume`, `--abandon`, even one its precheck refuses) ends by running the managed `--no-pull` sync of each member behind the checkout HEAD (`syncAfterUnfinishedRefresh`, listed in `synced`), so a write held for an import that refresh fenced off is decided in that run, not at a later refresh. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit or on a row recovery would abort (a HEAD moved before the merge, or a refused merge, GST-1674), and never on a `recovery_required` row once a member is past it (`membersPastStart`: a `last_commit` that is not it or an ancestor, GST-1457: the next sync would soft-delete what it synced; or a managed-sync import or delete admitted after the row's `barrier_sequence`, GST-1465: a pass stopped before its stamp), checking and aborting under every member's drain lease (`underMemberLeases`, so a pass in flight refuses `sync_drain_lease_held`), and `--resume` finishes a `recovery_required` row only at a HEAD that contains every member commit on that refresh's line (`adoptsHead`, which `--abandon` also reads to name `--resume` instead of a reset). `keepPagesWayOut` names the way out (GST-1472): a fast-forward to the newest member commit on the target's line, a merge of member commits on diverged lines (ask the user), or a fetch when git cannot place a member commit (`ancestry` tells exit 1 from a failure); the refusals also name the revert route for a deliberate rollback (GST-1477), and off the owner host writer status names no step. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured `fix` when it has one; `refresh_in_progress` carries the writer-status read); 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, and after a refused merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), `test/refresh-barrier-held-after-abort.test.ts` (the sync after an aborted refresh), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.- `src/core/persistence/refresh-barrier.ts` (+ deferred admission and claim in `journal.ts`, migration v292 `src/core/schema-migrations/v292-refresh-write-barrier.ts`) — the refresh write barrier (`docs/designs/REFRESH_WRITE_BARRIER.md`, `docs/guides/write-refusals.md#deferred-writes`). Off by default (`persistence.refresh_barrier`). With it on, a single page or memory write that reaches a worktree during a refresh is journaled in state `deferred` (tied to `deferred_refresh_id`) and answered pending instead of refused `worktree_refreshing`. Only a claim that declares the barrier moves a deferred row, and only after its refresh is released. `deferredReplayRefusal` re-checks the write's authority and reads the refresh's `old_head..target_head` diff with git, so a file the refresh changed ends `revision_conflict` with nothing applied. A write still waiting past `persistence.refresh_barrier_max_wait_ms` (15 minutes) ends `refresh_barrier_expired`. A write during a refresh in `recovery_required` defers too, and since GST-1582 there is no per-refresh cap (`persistence.refresh_barrier_max_deferred` is no longer read). A write whose page file holds a committed change sync has not imported yet is held with `deferred_import_from` (migration v294) instead of refused `pending_import`, and ends `pending_import_expired` past the wait limit (or four wait limits, at least four hours, after admission when it is held again and again). GST-1623: either kind of deferred write ends `revision_conflict` when a later write to its page committed first, and a refresh-deferred write is checked against its refresh before an import hold, which then clears `deferred_refresh_id`. `refresh-retry-hint.ts` derives `worktree_refreshing`'s `retry_after_ms` from the worktree's refresh history. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while any deferred write is unfinished. Tests: `test/refresh-write-barrier.test.ts`, `test/refresh-barrier-state-audit.test.ts`.- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `contentCanonical` digest (`reconcileCanonical` without the write gate's database-only markers, so a flagged page is not reported behind its own file, #9511); a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, split by content evidence in `direction_evidence`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; the census reads the `DOCTOR_GIT_GAP_NEWEST` (800) most recently changed live pages per source (`censusGitGap` option `newest`, keyed by `updated_at`; the census records `newest` and `newest_since`, the oldest `updated_at` it read) and the message states that window (`checked the <n> most recently changed of <live> live page(s), back to <time>`). The gap is informational (never a warning); a source the budget stopped or never reached (`PARTIAL, <read> of <live> live page(s) read`) or one that could not be compared makes the check the unknown convention (`warn`, `health: unknown`), never ok (GBRA-541). It lists totals only with each source's `live_pages` (counted in SQL before the scan). Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60, connector imports #7971). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsvindex 5f7aee661c..02482f3a4c 100644--- a/scripts/engine-raw-sql-baseline.tsv+++ b/scripts/engine-raw-sql-baseline.tsv@@ -920,7 +920,7 @@ src/core/persistence/sync-pass-row.ts execute_raw 4src/core/persistence/sync-pass-run.ts execute_raw 14src/core/persistence/sync-pass-status.ts execute_raw 3src/core/persistence/sync-pass.ts execute_raw 14-src/core/persistence/sync-prepare.ts execute_raw 15+src/core/persistence/sync-prepare.ts execute_raw 17 #9646: the stamp fence-trend pre-read runs outside the 5 s publication (newest sequence, open-import probe); moves with the persistence engine-sql conversionsrc/core/persistence/sync-prescreen.ts execute_raw 2src/core/persistence/sync-run.ts execute_raw 28src/core/persistence/sync-screen.ts execute_raw 1diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e37a997332..5ced9a0870 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -39,7 +39,7 @@ src/commands/hook.ts 1997 ratchet cathedral-5 heartbeat extraction offsets partsrc/core/chunkers/code.ts 1637 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1602 -> 1637, both sides' growthsrc/core/config.ts 2033 ratchet +2 GBRA-438: maintenance.auto and maintenance.embed_daily_usd KNOWN_CONFIG_KEYS rows (read in core/maintenance/run.ts); +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +2 GBRA-377 PR B: loadConfig reads a config.json of file-plane settings alone (skills.resolver) as no brain, plus its comment; +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts); re-summed at the #8797 merge (2026 measured); +1 GST-2250: the sources.auto_reconcile.source. KNOWN_CONFIG_KEY_PREFIXES row (prefix rows are data and cannot move); re-measured at the Train A merge of #8943: 2029; +1 GBRA-224 W3 #7836 (train T #8302, in Train B): dream.write_deferral.enabled / embed.restamp.enabled KNOWN_CONFIG_KEYS row (read in heal-audit.ts healEnabled), re-measured at the Train B merge of Train A fa5a61e9: 2030; re-measured at the Train C merge onto Train B (#9246 onto #9223): 2030 -> 2031, both sides' growthsrc/core/persistence/sync-run.ts 1715 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals); +10 GBRA-133: freezeEntry takes a timer turn between its synchronous Git reads and re-checks the run there (loopYield lives in sync-yield.ts; the turns sit between reads of freezeEntry locals); +4 GST-2568: the freeze drift screen accepts a page that holds its file's baseline when only derived keys differ (onlyDerivedKeysAdded lives in sync-screen.ts; the condition reads freezeEntry locals), and performManagedPass counts the holds a pass released (sourceHoldFingerprints and releasedHoldCount live in sync-holds.ts); +1 GST-2914: on PGLite each drain step starts with a setImmediate turn, so a run of held or waived pages lets timers and the SIGTERM handler run (one awaited line in the drainCursor loop; it cannot move)-src/core/persistence/worktree-refresh.ts 1541 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside it; re-measured at the Train A merge of #8930: 1541+src/core/persistence/worktree-refresh.ts 1550 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside it; re-measured at the Train A merge of #8930: 1541; +9 #9649: the owner scan lists a syncing orphan idle past the refresh sync budget and completeSyncedOrphan completes it with its lagging members deferred (shares the private transition, lastCommit, reachedTarget and readRefresh of the state machine)src/core/bootstrap/harness.ts 2632 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts); re-measured at the Train A merge of #8930: 2632src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mintsrc/core/ops/pages.ts 745 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured); +4 GBRA-449: an empty list_pages names the page types present when no visible page has the requested type (logic in ops/list-pages-pagination.ts unusedTypeNotice); +1 GST-2462: a static import of the put_page ignored-label notice (a dynamic one yielded on the first put_page, so a queued embedding ran inside it; mode-receipt.serial.test.ts); +1 GBRA-585: put_page reports where a sourceless local write landed (static import; logic in access/implicit-placement.ts)diff --git a/src/core/persistence/sync-pass-fold.ts b/src/core/persistence/sync-pass-fold.tsindex 9dc9afd4f8..4445f74fc4 100644--- a/src/core/persistence/sync-pass-fold.ts+++ b/src/core/persistence/sync-pass-fold.ts@@ -43,7 +43,7 @@ import { OPEN_AT_STAMP_CAP, readPassRow, type ManagedSyncPassValue } from './synimport { emptySyncScope } from './sync-slug-mode.ts';import { faultPoint } from './fault-points.ts';import { supersessionSql } from './terminal-classify.ts';-import { publishPassStamp, syncGitTopLevel, type SyncIntent } from './sync-prepare.ts';+import { publishPassStamp, syncGitTopLevel, type FenceTrendPrefix, type SyncIntent } from './sync-prepare.ts';/** What a folded stamp's proof needs of its round: S1's mark, page count and largest page id, and the round's imports. */export interface PassFold {@@ -64,7 +64,7 @@ export interface PassFold {* `prepared` (the round's last import) with the stamp folded into its publication: into its apply, or, for a writeback* (the import rewrites its file), into its post-effects hook, so the stamp sees and records the import's own Git effect.*/-export function foldPassCheckpoint<T extends PreparedMutation>(prepared: T, input: { row: WriteRequest; p: SyncIntent; root: string }): T {+export function foldPassCheckpoint<T extends PreparedMutation>(prepared: T, input: { row: WriteRequest; p: SyncIntent; root: string; trend?: FenceTrendPrefix }): T {if (prepared.noop) return prepared;prepared.sourceExclusive = true;if (prepared.file) {@@ -124,7 +124,7 @@ class StampSkipped extends Error { constructor(readonly reason: string) { super(* not enough on Postgres: postgres.js rethrows a failed statement when its transaction scope ends even after the caller* caught it, so a stamp's checkpoint validation timeout would fail the whole import (#5762 recovery journey).*/-async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {+async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string; trend?: FenceTrendPrefix }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {try {await tx.transaction(async stamp => {const skipped = await provenStamp(stamp, input, outcome, writeback);@@ -136,7 +136,7 @@ async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncI}}-async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {+async function provenStamp(tx: BrainEngine, { row, p, root, trend }: { row: WriteRequest; p: SyncIntent; root: string; trend?: FenceTrendPrefix }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {const stamp = p.stamp!, fold = stamp.fold!, postgres = tx.kind === 'postgres';const scope = { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation };await faultPoint('sync:pass_fold', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id });@@ -168,6 +168,6 @@ async function provenStamp(tx: BrainEngine, { row, p, root }: { row: WriteRequesconst prior = pass.value.obligations.converged?.writeback;const read = prior?.length ? await readConvergedWatermark(tx, scope, row.request_id, OPEN_AT_STAMP_CAP, { own: writeback, prior }) : watermark;await publishPassStamp(tx, row, p, root, async () => {}, fold.obligations ? { value: { ...pass.value, obligations: fold.obligations } } : pass,- { changed: stamp.changed + (outcome.noop === true ? 0 : fold.batch ?? 1), watermark: read, ...(emptyScope === undefined ? {} : { emptyScope }) });+ { changed: stamp.changed + (outcome.noop === true ? 0 : fold.batch ?? 1), watermark: read, ...(emptyScope === undefined ? {} : { emptyScope }), ...(trend ? { trend } : {}) });return null;}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 75c36efad9..6bf0256dec 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -26,7 +26,7 @@ import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';import { abortStop, recordedStop, replaysUnchangedRefusal, resumableRowStop } from './sync-stop-class.ts';import { adoptLegacyPage, incomingId, partialCloneTreeRefusal, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';-import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';+import { readFenceTrendPrefix, recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, transientEnding, writePassRow, type ManagedSyncPassValue, type PassEpisode,type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';@@ -605,13 +605,14 @@ async function stampUnchangedPass(engine: BrainEngine, input: SyncPassInput, rouconst { sourceId, incarnation } = context;const { value, level, head, kind, converged, parserFp, pack, selectionFp, passId, startedAt, started, counts, applied } = round;const at = new Date().toISOString();+ const trend = await readFenceTrendPrefix(engine, { worktreeId: context.binding.worktree_id, sourceId, incarnation });await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {assertActive();await assertDrainLease(tx, sourceId);await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);// Holds on paths that left the level go with it here too, as a stamp releases them.for (const path of [...level.releasableHolds, ...await settledDeletionHolds(tx, sourceId, level.deletionCandidates)]) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });- await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null });+ await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null, prefix: trend });const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP, { prior: converged?.writeback });value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex f7023ce5c2..1dcec45ede 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -536,7 +536,7 @@ export const PASS_LEASE_LOST_MESSAGE = 'The sync pass that admitted this checkpo* obligation, hold release, the retry compare-and-delete, and the pass row's converged state (`request_hwm`,* `open_at_stamp`, fingerprints), written under the lease token. The cursor checkpoint (`applyManagedSyncCheckpoint`) is unchanged.*/-async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {+async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>, trend?: FenceTrendPrefix): Promise<Record<string, unknown>> {const stamp = p.stamp!;const lease = await fenceLockRow(tx, syncLockId(row.source_id), stamp.leaseToken);const pass = lease.length ? await readPassRow(tx, row.source_id, stamp.incarnation) : null;@@ -547,7 +547,7 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn`Sync request ${open} of ${row.source_id} is still open or needs recovery, so checkpoint request ${row.request_id} did not commit. Let it finish; do not resubmit it. `+ `Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,{ fix: syncInspectFix(row, open, false) });- return publishPassStamp(tx, row, p, root, releaseHold, pass, { changed: stamp.changed });+ return publishPassStamp(tx, row, p, root, releaseHold, pass, { changed: stamp.changed, trend });}/**@@ -556,7 +556,7 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn* and the watermark and source scope it already read.*/export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>,- pass: { value: ManagedSyncPassValue }, read: { changed: number; watermark?: Awaited<ReturnType<typeof readConvergedWatermark>>; emptyScope?: boolean }): Promise<Record<string, unknown>> {+ pass: { value: ManagedSyncPassValue }, read: { changed: number; watermark?: Awaited<ReturnType<typeof readConvergedWatermark>>; emptyScope?: boolean; trend?: FenceTrendPrefix }): Promise<Record<string, unknown>> {const stamp = p.stamp!;if (stamp.configured) {const emptyScope = read.emptyScope ?? emptySyncScope(root, syncGitTopLevel(root, p.passId!));@@ -574,7 +574,7 @@ export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: Syif (stamp.stampChunker) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);}await recordPassTail(tx, row.source_id, p.passId!, { changed: read.changed, extract: stamp.extract, ...(stamp.since ? { since: stamp.since } : {}) });- await recordPassFenceTrend(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, passId: p.passId!, since: pass.value.obligations.converged?.request_hwm ?? null });+ await recordPassFenceTrend(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, passId: p.passId!, since: pass.value.obligations.converged?.request_hwm ?? null, prefix: read.trend });for (const path of [...stamp.releasedHolds, ...await settledDeletionHolds(tx, row.source_id, stamp.deletionCandidates)]) await releaseHold(tx, path);if (stamp.retryTaken.length) await clearGitHoldRetryPaths(tx, row.source_id, stamp.incarnation, stamp.retryTaken);const watermark = read.watermark ?? await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP,@@ -599,16 +599,62 @@ export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: Sy* the sync imports committed since the previous stamp's watermark. A pass that stopped before its stamp is counted by the* next stamp, once, so a completed pass always has its trend row and a normalization is never counted twice.*/-export async function recordPassFenceTrend(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; passId: string; since: string | null }): Promise<void> {- const rows = await tx.executeRaw<{ path: string | null; fences: Array<{ class: string }> }>(`SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences- FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed'- AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence`,- [scope.worktreeId, scope.sourceId, scope.since ?? '0']);- let tally: FencesTally | undefined;+export async function recordPassFenceTrend(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; passId: string; since: string | null; prefix?: FenceTrendPrefix }): Promise<void> {+ // #9646: the requests up to the prefix were tallied before the publication; a prefix read from another watermark is not used.+ const prefix = scope.prefix && scope.prefix.since === scope.since ? scope.prefix : undefined;+ const rows = await fenceTrendRows(tx, scope, prefix?.through ?? scope.since ?? '0', null, prefix?.open);+ let tally = prefix?.tally;for (const row of rows) if (row.path && row.fences.length) tally = addFencesNormalized(tally, row.path, row.fences);if (tally) await recordSyncRunTrend(tx, { sourceId: scope.sourceId, runId: scope.passId, day: new Date().toISOString().slice(0, 10), count: tally.count, byClass: tally.by_class, writers: tally.dirs });}+/** Request sequences one prefix statement reads: a range of the unique sequence index, so a statement's cost never grows with the history. */+export const FENCE_TREND_PAGE = 5_000;++/** The trend tally of a stamp's range up to `through`, read before its publication (`readFenceTrendPrefix`). */+export interface FenceTrendPrefix { since: string | null; through: string; open?: string[]; tally?: FencesTally }++/**+ * The publication's read has no upper bound (`upTo` null) and also reads, by sequence, the imports the prefix left open; the+ * prefix reads one range of the sequence index per statement.+ */+function fenceTrendRows(engine: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string }, after: string, upTo: string | null, open: string[] = []) {+ const range = upTo !== null ? 'sequence > $3::bigint AND sequence <= $4::bigint'+ : open.length ? '(sequence > $3::bigint OR sequence = ANY($4::text::bigint[]))' : 'sequence > $3::bigint';+ return engine.executeRaw<{ path: string | null; fences: Array<{ class: string }>; sequence?: string }>(`SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences${upTo === null ? '' : ', sequence::text AS sequence'}+ FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND ${range} AND state='committed'+ AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence`,+ upTo !== null ? [scope.worktreeId, scope.sourceId, after, upTo] : open.length ? [scope.worktreeId, scope.sourceId, after, `{${open.join(',')}}`] : [scope.worktreeId, scope.sourceId, after]);+}++/**+ * #9646: a stamp's publication runs under a 5 s statement bound, and its trend range starts at the previous watermark, or at 0+ * for a source that never recorded one, which on a large brain is the whole request table. Read before the publication, outside+ * it, in statements of FENCE_TREND_PAGE sequences each, this tallies the range up to the newest request now, leaving out the+ * imports still open in it, whose sequences it records; the publication then reads only what is newer plus those sequences+ * (`recordPassFenceTrend`), so every import is counted once, the stamp lands in bounded time and records its trend row in the+ * same transaction, as before.+ */+export async function readFenceTrendPrefix(engine: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; incarnation: string }): Promise<FenceTrendPrefix> {+ const since = (await readPassRow(engine, scope.sourceId, scope.incarnation))?.value.obligations.converged?.request_hwm ?? null;+ const [newest] = await engine.executeRaw<{ through: string | null }>('SELECT max(sequence)::text AS through FROM persistence_requests');+ const floor = BigInt(since ?? '0'), through = BigInt(newest?.through ?? '0');+ // Read before the tally: an import open now that commits during it is skipped here and read by the publication, once.+ // The worktree's open requests are few, and persistence_requests_open indexes exactly them by sequence.+ const open = through > floor ? (await engine.executeRaw<{ sequence: string }>(`SELECT sequence::text AS sequence FROM persistence_requests+ WHERE worktree_id=$1::uuid AND sequence > $2::bigint AND sequence <= $3::bigint AND state IN ('queued','deferred','running','recovering')+ AND source_id=$4 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [scope.worktreeId, String(floor), String(through), scope.sourceId])).map(row => row.sequence) : [];+ const skip = new Set(open);+ let tally: FencesTally | undefined;+ for (let low = floor; low < through; low += BigInt(FENCE_TREND_PAGE)) {+ const high = low + BigInt(FENCE_TREND_PAGE) < through ? low + BigInt(FENCE_TREND_PAGE) : through;+ for (const row of await fenceTrendRows(engine, scope, String(low), String(high))) {+ if (row.path && row.fences.length && !skip.has(row.sequence!)) tally = addFencesNormalized(tally, row.path, row.fences);+ }+ }+ return { since, through: String(through > floor ? through : floor), ...(open.length ? { open } : {}), ...(tally ? { tally } : {}) };+}+/** The checkpoint request's publication: the whole run committed, so `last_commit` (and the slug-root pin) advance under the guard. */async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(@@ -678,10 +724,14 @@ export type SyncPreparedMutation = PreparedMutation & { importProvenance?: SyncI*/export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, config: GBrainConfig, clock?: ClaimPhaseClock,screening?: { unsaved: true }): Promise<SyncPreparedMutation> {- const at: { root?: string } = {};- const prepared = await prepareSyncMutation(unbounded, row, config, clock, screening, at);const p = row.intent as SyncIntent | null;- return p?.kind === 'managed_sync_import' && p.stamp?.fold && at.root && !screening ? foldPassCheckpoint(prepared, { row, p, root: at.root }) : prepared;+ const at: { root?: string; trend?: FenceTrendPrefix } = {};+ // #9646: a stamp's trend range is tallied here, outside its publication (readFenceTrendPrefix).+ if (p?.passId && row.worktree_id && !screening && (p.kind === 'managed_sync_checkpoint' || (p.kind === 'managed_sync_import' && p.stamp?.fold))) {+ at.trend = await readFenceTrendPrefix(unbounded, { worktreeId: row.worktree_id, sourceId: row.source_id, incarnation: row.source_incarnation });+ }+ const prepared = await prepareSyncMutation(unbounded, row, config, clock, screening, at);+ return p?.kind === 'managed_sync_import' && p.stamp?.fold && at.root && !screening ? foldPassCheckpoint(prepared, { row, p, root: at.root, trend: at.trend }) : prepared;}/** #6722 and #7106: what a committed sync write left the page's embedding and search index in, for its receipt. */@@ -701,7 +751,7 @@ function keepDbOnlyLabels(root: string, slug: string, base: Snapshot | undefined/** #8729: a screen (`screening`) publishes nothing, so the segmented staging its import opened is aborted (unbounded: past the screen's deadline too) as soon as the import hands it over, never left live beside the admitted write's. */async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock: ClaimPhaseClock | undefined,- screening: { unsaved: true } | undefined, at: { root?: string }): Promise<SyncPreparedMutation> {+ screening: { unsaved: true } | undefined, at: { root?: string; trend?: FenceTrendPrefix }): Promise<SyncPreparedMutation> {const engine = boundedReads(unbounded, clock, { engineReads: true });const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,@@ -796,7 +846,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c}};if (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate,- apply: tx => p.passId ? applyPassCheckpoint(tx, row, p, root, releaseHold) : applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };+ apply: tx => p.passId ? applyPassCheckpoint(tx, row, p, root, releaseHold, at.trend) : applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };const source = { sourceId: row.source_id };enterClaimStep(clock, 'page_snapshot', undefined, 'db');const read = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex c9034d3ee7..45c289635c 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -1219,10 +1219,12 @@ export const _refreshScanCacheSizeForTests = () => laggingSyncing.size + unreada*/export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostId?: string } = {}): Promise<number> {const host = opts.hostId ?? hostIdFor(engine);- const rows = await engine.executeRaw<WorktreeRefreshRow>(`SELECT f.* FROM persistence_worktree_refreshes f- JOIN persistence_worktrees w ON w.id=f.worktree_id WHERE w.owner_host_id=$1::uuid AND f.state IN ('draining','fenced','merged','syncing')- AND (f.state<>'syncing' OR NOT EXISTS (SELECT 1 FROM sources s WHERE s.id=ANY(f.source_ids) AND (s.last_commit IS NULL OR s.last_commit=f.old_head)))- ORDER BY f.state='syncing', f.created_at LIMIT 16`, [host]);+ const budgetMs = await configuredMs(engine, undefined, 'GBRAIN_REFRESH_SYNC_BUDGET_MS', 'sources.refresh_sync_budget_ms', SYNC_BUDGET_MS).catch(() => SYNC_BUDGET_MS);+ // #9649: a syncing row that has not moved for a whole sync budget is listed even while its members lag (completeSyncedOrphan).+ const rows = await engine.executeRaw<WorktreeRefreshRow & { stale: boolean }>(`SELECT f.*,f.updated_at<now()-($2::double precision*interval '1 millisecond') AS stale FROM persistence_worktree_refreshes f+ JOIN persistence_worktrees w ON w.id=f.worktree_id WHERE w.owner_host_id=$1::uuid AND f.state IN ('draining','fenced','merged','syncing') AND (f.state<>'syncing'+ OR f.updated_at<now()-($2::double precision*interval '1 millisecond') OR NOT EXISTS (SELECT 1 FROM sources s WHERE s.id=ANY(f.source_ids) AND (s.last_commit IS NULL OR s.last_commit=f.old_head)))+ ORDER BY f.state='syncing', f.created_at LIMIT 16`, [host, budgetMs]);const listed = new Set(rows.map(row => row.id));for (const cache of [laggingSyncing, unreadableHeadLogged]) for (const id of cache.keys()) if (!listed.has(id)) cache.delete(id);let moved = 0;@@ -1231,17 +1233,17 @@ export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostIif (!root) continue;const commits = row.state === 'syncing' ? (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [row.source_ids])).map(source => source.last_commit ?? '').join(',') : null;- const lagging = commits === null ? undefined : laggingSyncing.get(row.id);+ const lagging = commits === null || row.stale ? undefined : laggingSyncing.get(row.id);if (lagging?.commits === commits && Date.now() - lagging.at < LAGGING_RECHECK_MS) continue;try {await withGit(async git => {- if (commits !== null && !await membersAtTarget(engine, git, row, root)) { laggingSyncing.set(row.id, { commits, at: Date.now() }); return; }+ if (commits !== null && !row.stale && !await membersAtTarget(engine, git, row, root)) { laggingSyncing.set(row.id, { commits, at: Date.now() }); return; }const lock = await tryAcquireNativeLock(refreshLockPath(row.worktree_id));if (!lock) return;try {const after = await withTopologyLocks(engine, row.source_ids[0], async () => {const current = await readRefresh(engine, row.id);- return current.state === 'syncing' ? completeSyncedOrphan(engine, git, current, root) : recoverOne(engine, git, current, root, true);+ return current.state === 'syncing' ? completeSyncedOrphan(engine, git, current, root, row.stale ? budgetMs : null) : recoverOne(engine, git, current, root, true);}, undefined, 0);if (after.state !== row.state) moved++;else if (commits !== null) laggingSyncing.set(row.id, { commits, at: Date.now() });@@ -1271,12 +1273,19 @@ export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostI* checkout HEAD is still the target or a descendant of it; otherwise it is left as it is (an unrelated or unreadable HEAD* waits for an attended --resume, which names both ways out).*/-async function completeSyncedOrphan(engine: BrainEngine, git: Git, row: WorktreeRefreshRow, root: string): Promise<WorktreeRefreshRow> {+async function completeSyncedOrphan(engine: BrainEngine, git: Git, row: WorktreeRefreshRow, root: string, staleAfterMs: number | null = null): Promise<WorktreeRefreshRow> {const synced = await membersAtTarget(engine, git, row, root);- if (!synced) return row;+ if (!synced && staleAfterMs === null) return row;const head = await headOf(git, root);if (head === null || (head !== row.target_head && !await isAncestor(git, root, row.target_head, head))) return row;- await engine.transaction(tx => transition(tx, row, ['syncing'], 'completed', { synced, completed_by: 'owner_recovery' }));+ // #9649: its process is gone (the caller holds its lock) and the row has not moved for a whole sync budget, so it completes as a run whose+ // budget ran out with members behind does (#8072): the checkout is at the target and each lagging member's next sync imports it.+ const members = synced ?? await Promise.all(row.source_ids.map(async source_id => {+ const last_commit = await lastCommit(engine, source_id);+ return { source_id, last_commit, status: await reachedTarget(git, root, row, last_commit) ? 'up_to_date' : 'deferred' };+ }));+ await engine.transaction(tx => transition(tx, row, ['syncing'], 'completed', synced ? { synced, completed_by: 'owner_recovery' } : { synced: members,+ sync_deferred: members.filter(member => member.status === 'deferred').map(member => member.source_id), completed_by: 'owner_reclaim', reclaimed: { idle_limit_ms: staleAfterMs } }));return readRefresh(engine, row.id);}diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.jsonindex 72a3b20932..c100f7f7f5 100644--- a/test/fixtures/fold-hook-noop-6712.json+++ b/test/fixtures/fold-hook-noop-6712.json@@ -121,7 +121,7 @@"SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])","UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",- "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",+ "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND (sequence > $3::bigint OR sequence = ANY($4::text::bigint[])) AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE ($4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5) RETURNING 1","RELEASE SAVEPOINT gbrain_nested_1","SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true),set_config('gbrain.git_protocol',$7,true)",@@ -254,7 +254,7 @@"SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])","UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::bo","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",- "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",+ "SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND (sequence > $3::bigint OR sequence = ANY($4::text::bigint[])) AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE ($4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5) RETURNING 1","SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true),set_config('gbrain.git_protocol',$7,true)","SELECT value FROM config WHERE key = $1",diff --git a/test/fold-hook-noop-6712.test.ts b/test/fold-hook-noop-6712.test.tsindex 8a509921ed..524082e522 100644--- a/test/fold-hook-noop-6712.test.ts+++ b/test/fold-hook-noop-6712.test.ts@@ -4,7 +4,8 @@** Protects: the publication transaction of a `put_page` and of a canonical one-file import whose stamp folds into its* apply runs the same SQL statements, in the same order, as the golden sequence recorded on the commit before the hook- * (c64799845, the pre-hook side of the merge with master v0.60.300.0; test/fixtures/fold-hook-noop-6712.json). Statements are the publication's own round trips (begin to+ * (c64799845, the pre-hook side of the merge with master v0.60.300.0; test/fixtures/fold-hook-noop-6712.json; since #9646 the fold's+ * fence-trend read also takes the imports its pre-read found open, by sequence). Statements are the publication's own round trips (begin to* commit), captured through the statement seam (PGLite: `countPgliteStatements`; Postgres: the `GBRAIN_SQL_TRACE` wire* trace), with whitespace collapsed and the per-call statement timeout masked. A hook that adds, drops or reorders a* statement for any other write fails here.diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex fcc1f066b1..588455f284 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -487,3 +487,37 @@ test('E33: a completed sync run always has its trend row; a failed trend write fexpect(recorded).toHaveLength(1);expect(recorded[0]!.record).toMatchObject({ count: 2, by_class: { kind_map: 2, holder_alias: 2 } });}), 180_000);++test('#9646: a pass stamp on a source with no recorded watermark reads only requests newer than its publication\'s preparation inside the publication', () => each(async engine => {+ const s = await source(engine, { 'notes/fix-a.md': fixable('A') });+ expect(await s.sync()).toMatchObject({ fences_normalized: { count: 1 } });+ // A source whose converged watermark was never recorded: the stamp's trend range starts at 0, the whole request history.+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,obligations,converged}',(completed_keys->0->'obligations'->'converged')-'request_hwm')+ WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1`, [s.id]);+ const [{ newest }] = await engine.executeRaw<{ newest: string }>('SELECT max(sequence)::text AS newest FROM persistence_requests');+ const trendRows = () => engine.executeRaw<{ fingerprint: string; count: number }>(`SELECT fingerprint, (completed_keys->0->>'count')::int AS count FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'=$2`,+ [FENCE_TREND_OP, s.id]);+ const before = new Set((await trendRows()).map(row => row.fingerprint));+ s.write('notes/fix-b.md', fixable('B'));+ commit(s.root, 'another fixable file');+ const original = engine.executeRaw;+ const inPublication: string[] = [];+ (engine as unknown as { executeRaw: typeof original }).executeRaw = function (this: typeof engine, sql: string, params?: unknown[]) {+ if (sql.includes('AS fences') && (this as unknown as { _pageTransaction?: boolean })._pageTransaction === true) inPublication.push(String(params?.[2]));+ return original.call(this, sql, params) as never;+ } as typeof original;+ let result: SyncResult;+ try { result = await s.sync(); } finally { (engine as unknown as { executeRaw: typeof original }).executeRaw = original; }+ expect(result).toMatchObject({ status: 'synced', fences_normalized: { count: 1 } });+ // The stamp landed and its trend scan inside the 5 s publication started past everything committed before this sync.+ expect(inPublication.length).toBeGreaterThan(0);+ for (const after of inPublication) expect(BigInt(after)).toBeGreaterThanOrEqual(BigInt(newest));+ const [pass] = await engine.executeRaw<{ hwm: string | null }>(`SELECT completed_keys->0->'obligations'->'converged'->>'request_hwm' AS hwm FROM op_checkpoints+ WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1`, [s.id]);+ expect(pass!.hwm).not.toBeNull();+ // The stamp recorded this pass's trend row in its own transaction, as before; its count was tallied mostly outside the publication.+ const added = (await trendRows()).filter(row => !before.has(row.fingerprint));+ expect(added).toHaveLength(1);+ expect(added[0]!.count).toBeGreaterThanOrEqual(1);+}), 180_000);+diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex ce1babfe9f..4448810d44 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -717,6 +717,7 @@ test/sync-drain-write-capacity.test.tstest/sync-drift-rescreen-progress-gst2515.test.tstest/sync-dry-run-drain-7167.test.tstest/sync-exits-l4-6712.test.ts+test/sync-fence-trend-open-9646.test.tstest/sync-fenced-slices-gbra133.test.tstest/sync-file-drift-agrees-7931.test.tstest/sync-filter-owned-9024.test.tsdiff --git a/test/sync-fence-trend-open-9646.test.ts b/test/sync-fence-trend-open-9646.test.tsnew file mode 100644index 0000000000..ecc60e2ac8--- /dev/null+++ b/test/sync-fence-trend-open-9646.test.ts@@ -0,0 +1,86 @@+/**+ * #9646: the stamp's fence trend is pre-read outside its 5 s publication. An import still open at the pre-read is recorded by+ * sequence and read by the publication, so it is counted exactly once whenever it commits, and an old import that never commits+ * leaves the publication's read starting past the newest request instead of reopening the whole history.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { readFenceTrendPrefix, recordPassFenceTrend } from '../src/core/persistence/sync-prepare.ts';+import { FENCE_TREND_OP } from '../src/core/fence-repair/census-store.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) await engine.disconnect();+ await closePostgres?.();+});++const FENCES = JSON.stringify({ fences_normalized: [{ class: 'kind_map' }] });++async function history(engine: BrainEngine) {+ const sourceId = `source-a-${randomUUID().slice(0, 8)}`, incarnation = randomUUID();+ const [{ id: worktreeId }] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees DEFAULT VALUES RETURNING id::text AS id');+ const add = async (path: string, state: 'queued' | 'committed') => (await engine.executeRaw<{ sequence: string }>(`INSERT INTO persistence_requests+ (principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,intent,authority,state,outcome,intent_bytes,terminal_reservation)+ VALUES('local_cli','test',$1::uuid,'put_page',$2,$3::uuid,$4,$5::uuid,'digest',$6::text::jsonb,'{}'::jsonb,$7,$8::text::jsonb,0,0) RETURNING sequence::text AS sequence`,+ [randomUUID(), sourceId, incarnation, path.replace(/\.md$/, ''), worktreeId, JSON.stringify({ kind: 'managed_sync_import', passId: 'pass-0', path }), state, state === 'committed' ? FENCES : null]))[0]!.sequence;+ const commit = (sequence: string) => engine.executeRaw(`UPDATE persistence_requests SET state='committed', outcome=$2::text::jsonb WHERE sequence=$1::bigint`, [sequence, FENCES]);+ const trend = async (passId: string) => (await engine.executeRaw<{ count: number }>(`SELECT (completed_keys->0->>'count')::int AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,+ [FENCE_TREND_OP, `${sourceId}:run:${passId}`]))[0]?.count;+ return { scope: { worktreeId, sourceId, incarnation }, add, commit, trend };+}++function recording(engine: BrainEngine) {+ const statements: Array<{ sql: string; params: unknown[] }> = [];+ const executeRaw = (sql: string, params: unknown[] = []) => { statements.push({ sql, params }); return engine.executeRaw(sql, params); };+ return { engine: { executeRaw } as unknown as BrainEngine, statements };+}++test('#9646: an import open at the pre-read that commits before the stamp is counted once, and a stuck old import keeps the publication past the newest request', async () => {+ for (const engine of engines) {+ const h = await history(engine);+ const stuck = await h.add('notes/stuck.md', 'queued');+ await h.add('notes/a.md', 'committed');+ const late = await h.add('notes/late.md', 'queued');+ const newest = await h.add('notes/c.md', 'committed');+ const prefix = await readFenceTrendPrefix(engine, h.scope);+ await h.commit(late);+ await h.add('notes/d.md', 'committed');+ const publication = recording(engine);+ await recordPassFenceTrend(publication.engine, { ...h.scope, passId: 'pass-1', since: null, prefix });+ // a, c, late and d, each once; the stuck import is still open and never read as committed.+ expect(await h.trend('pass-1')).toBe(4);+ const reads = publication.statements.filter(statement => statement.sql.includes('AS fences'));+ expect(reads).toHaveLength(1);+ expect(BigInt(reads[0]!.params[2] as string)).toBe(BigInt(newest));+ expect(prefix).toMatchObject({ since: null, through: newest, open: [stuck, late], tally: { count: 2 } });+ }+}, 120_000);++test('#9646: the open-import probe reads the open-request index, not the request history', async () => {+ for (const engine of engines) {+ const h = await history(engine);+ for (let i = 0; i < 3; i++) await h.add(`notes/p-${i}.md`, 'committed');+ const pre = recording(engine);+ expect((await readFenceTrendPrefix(pre.engine, h.scope)).open).toBeUndefined();+ const probe = pre.statements.find(statement => statement.sql.includes("state IN ('queued','deferred','running','recovering')"));+ expect(probe).toBeDefined();+ const plan = await engine.transaction(async tx => {+ await tx.executeRaw('SET LOCAL enable_seqscan = off');+ await tx.executeRaw('SET LOCAL enable_bitmapscan = off');+ return tx.executeRaw<Record<string, string>>(`EXPLAIN ${probe!.sql}`, probe!.params);+ });+ expect(plan.map(row => Object.values(row)[0]).join('\n')).toContain('persistence_requests_open');+ }+}, 120_000);diff --git a/test/sync-fence-trend-prefix-9646.test.ts b/test/sync-fence-trend-prefix-9646.test.tsnew file mode 100644index 0000000000..55f5331a56--- /dev/null+++ b/test/sync-fence-trend-prefix-9646.test.ts@@ -0,0 +1,62 @@+/**+ * #9646: the fence trend of a pass stamp is tallied before its publication in statements over at most FENCE_TREND_PAGE request+ * sequences each, so no statement's cost grows with the request history and the stamp's publication reads only what is newer.+ */+import { expect, test } from 'bun:test';+import { FENCE_TREND_PAGE, readFenceTrendPrefix, recordPassFenceTrend } from '../src/core/persistence/sync-prepare.ts';++const NEWEST = FENCE_TREND_PAGE * 3 + 345;+const fenced = (sequence: number) => sequence % 1000 === 0;+function history(open: string[] = []) {+ const ranges: Array<[bigint, bigint | null]> = [];+ const trend: unknown[][] = [];+ const executeRaw = async (sql: string, params: unknown[] = []): Promise<any[]> => {+ if (sql.includes('FROM op_checkpoints WHERE op=$1 AND fingerprint=$2')) return [];+ if (sql.includes('max(sequence)')) return [{ through: String(NEWEST) }];+ if (sql.includes("state IN ('queued','deferred','running','recovering')")) return open.map(sequence => ({ sequence }));+ if (sql.includes('INSERT INTO op_checkpoints')) { trend.push(params); return []; }+ if (!sql.includes('AS fences')) throw new Error(`unexpected statement: ${sql}`);+ const after = BigInt(params[2] as string), upTo = sql.includes('sequence <= $4') ? BigInt(params[3] as string) : null;+ ranges.push([after, upTo]);+ const rows = [];+ // Every fenced request reads as committed, an open one included: it committed during the prefix.+ for (let s = Number(after) + 1; s <= Number(upTo ?? BigInt(NEWEST + 10)); s++) if (fenced(s)) rows.push({ path: `notes/p-${s}.md`, fences: [{ class: 'kind_map' }], sequence: String(s) });+ if (upTo === null && typeof params[3] === 'string') for (const s of params[3].slice(1, -1).split(',')) if (fenced(Number(s))) rows.push({ path: `notes/p-${s}.md`, fences: [{ class: 'kind_map' }], sequence: s });+ return rows;+ };+ return { engine: { executeRaw } as never, ranges, trend };+}++test('#9646: with no watermark the prefix reads the whole history in bounded ranges and the publication reads only past it', async () => {+ const h = history();+ const scope = { worktreeId: '00000000-0000-0000-0000-000000000001', sourceId: 'source-a', incarnation: '00000000-0000-0000-0000-000000000002' };+ const prefix = await readFenceTrendPrefix(h.engine, scope);+ expect(prefix).toMatchObject({ since: null, through: String(NEWEST), tally: { count: Math.floor(NEWEST / 1000) } });+ expect(h.ranges.length).toBe(Math.ceil(NEWEST / FENCE_TREND_PAGE));+ for (const [after, upTo] of h.ranges) { expect(upTo).not.toBeNull(); expect(upTo! - after).toBeLessThanOrEqual(BigInt(FENCE_TREND_PAGE)); }+ // Contiguous and non-overlapping: every request is read exactly once.+ h.ranges.forEach(([after], i) => expect(after).toBe(i === 0 ? 0n : h.ranges[i - 1]![1]!));+ h.ranges.length = 0;+ await recordPassFenceTrend(h.engine, { ...scope, passId: 'pass-1', since: null, prefix });+ expect(h.ranges).toEqual([[BigInt(NEWEST), null]]);+ expect(JSON.parse(h.trend[0]![2] as string)[0]).toMatchObject({ count: Math.floor(NEWEST / 1000) });+});++test('#9646: a prefix read from another watermark is not used: the publication tallies from its own watermark', async () => {+ const h = history();+ const scope = { worktreeId: '00000000-0000-0000-0000-000000000001', sourceId: 'source-a' };+ await recordPassFenceTrend(h.engine, { ...scope, passId: 'pass-2', since: String(NEWEST - 500), prefix: { since: null, through: String(NEWEST), tally: { count: 99, by_class: {}, sample_paths: [], dirs: {} } } });+ expect(h.ranges).toEqual([[BigInt(NEWEST - 500), null]]);+ expect(JSON.parse(h.trend[0]![2] as string)[0]).toMatchObject({ count: 1 });+});++test('#9646: an import still open when the prefix is read is left to the publication by sequence, so it is counted once and the publication still starts past the newest request', async () => {+ const h = history(['7000']);+ const scope = { worktreeId: '00000000-0000-0000-0000-000000000001', sourceId: 'source-a', incarnation: '00000000-0000-0000-0000-000000000002' };+ const prefix = await readFenceTrendPrefix(h.engine, scope);+ expect(prefix).toMatchObject({ since: null, through: String(NEWEST), open: ['7000'], tally: { count: Math.floor(NEWEST / 1000) - 1 } });+ h.ranges.length = 0;+ await recordPassFenceTrend(h.engine, { ...scope, passId: 'pass-3', since: null, prefix });+ expect(h.ranges).toEqual([[BigInt(NEWEST), null]]);+ expect(JSON.parse(h.trend[0]![2] as string)[0]).toMatchObject({ count: Math.floor(NEWEST / 1000) });+});diff --git a/test/worktree-refresh-orphan-7679.test.ts b/test/worktree-refresh-orphan-7679.test.tsindex b7fec8d412..36ca50f34e 100644--- a/test/worktree-refresh-orphan-7679.test.ts+++ b/test/worktree-refresh-orphan-7679.test.ts@@ -196,6 +196,9 @@ test('#7679: a live refresh is never stolen: owner recovery, a plain refresh andfor (const id of [f.alpha, f.beta]) await performManagedSync(f.engine, { sourceId: id, noPull: true, noEmbed: true });expect(await f.lastCommit(f.alpha)).toBe(target);expect(await resumeWorktreeRefreshes(f.engine)).toBe(0);+ // #9649: a row older than the sync budget is still its live holder's: the reclaim takes only a refresh whose lock is free.+ await f.engine.executeRaw(`UPDATE persistence_worktree_refreshes SET updated_at=now()-interval '1 hour' WHERE id=$1::uuid`, [held.id]);+ expect(await resumeWorktreeRefreshes(f.engine)).toBe(0);const refused = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_in_progress');expect(refused.message).toContain(`pid ${process.pid}`);await refusedWith(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_in_progress');@@ -286,3 +289,24 @@ test('#7679: a plain refresh that cannot read the checkout HEAD leaves an orphanexpect(await f.lastCommit(f.alpha)).toBe(target);});}, 300_000);++test('#9649: owner recovery reclaims an orphaned syncing refresh that made no progress for the refresh sync budget, so writes to its sources are admitted again', async () => {+ for (const item of cases) await withKilledRefresh(item, async ({ f, target, old, orphan }) => {+ // A fresh orphan whose members lag is still left to the next refresh (the #7679 contract above), and a write names it with its age.+ expect(await resumeWorktreeRefreshes(f.engine)).toBe(0);+ const refused = await refusedWith(f.put(f.beta, 'notes/while-stuck', page('While stuck', 'refused')), 'worktree_refreshing');+ expect(refused.message).toContain(`refresh ${orphan.id}`);+ expect(refused.message).toMatch(/syncing, running \d+ s/);+ // No progress on the row for longer than the refresh sync budget, set on the database clock: no wall-clock wait.+ await f.engine.executeRaw(`UPDATE persistence_worktree_refreshes SET updated_at=now()-interval '1 hour' WHERE id=$1::uuid`, [orphan.id]);+ expect(await resumeWorktreeRefreshes(f.engine)).toBe(1);+ const [row] = await f.refreshRows() as Row[];+ expect(row).toMatchObject({ id: orphan.id, state: 'completed', outcome: { completed_by: 'owner_reclaim', sync_deferred: [f.alpha, f.beta] } });+ // The checkout stays at the target and the members stay where they were: their next sync imports it, as after a deferred member (#8072).+ expect(f.head()).toBe(target);+ expect(await f.lastCommit(f.alpha)).toBe(old);+ expect((await f.put(f.beta, 'notes/after-reclaim', page('After reclaim', 'admitted'))).state ?? 'committed').toBe('committed');+ expect(await writerRefreshes(f, f.beta)).toEqual([]);+ });+}, 300_000);+