Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(persistence): cut the fixed cost of files import and sync skip (GBRA-75 wave 7)
time-attack5bf4f8161df0
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex a196c20937..3217a345fb 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -35,7 +35,8 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through Gmail profile, Calendar primary calendar or People `me` (first enabled service that answers; none refuses), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.-- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.+- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. The page's current `knowledge_revision`, read with the projection flags, must still equal the snapshot's revision (a write after the screen's snapshot admits as `revision_moved`). Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.+- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. Tests: `test/sync-waiver-budget.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 24b0f83610..7f55083aaa 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex edb4e94865..7af662925f 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -26,6 +26,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`).- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.+- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.serial.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce and the pid-namespace inode from `/proc/self/ns/pid` where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows lapsed over 60 s in the same CTE, and a failed write is logged once and never stops the consumer. `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. Live is 30 s, lapsed 60 s. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. Registered in `DOCTOR_CHECK_REGISTRY` before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`.diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.mdindex a406fe8715..ed4cf18042 100644--- a/docs/architecture/key-files/shared-skills.md+++ b/docs/architecture/key-files/shared-skills.md@@ -1,7 +1,7 @@# Shared brain skills- `src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts` defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned. `skillMetadata` refuses an empty or whitespace-only SKILL.md (A-NEW-5) and records `tools_declared` (#5150): a canonical skill published without `tools` inherits the caller's `sharedSkillToolAccess` as `usable_tools` in v2 list/detail and the v1 compatibility projection (which now reuses the catalog's computed lists), `tools: []` permits none, and revisions published before the flag re-read their SKILL.md on detail (`skillToolsDeclared`) while the list fails closed. `SHARED_SKILL_LIMITS.packFiles` (128, equal to the persistence `BUNDLE_FILE_LIMITS.files`) bounds one canonical publication; `files` (64) bounds one skill (#5476).-- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths. A relative or host-only `file://` alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with `invalid_source_uri` (not `skill_bundle_required`).+- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths; inside a screening batch (`persistence/screening-paths.ts`) it canonicalizes each pack root and resolves each source root's Git scope once. A relative or host-only `file://` alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with `invalid_source_uri` (not `skill_bundle_required`).- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server `membership_inactive` (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (`remote_membership_reason: superseded`), so harness rotation converges; `gbrain bootstrap harness --refresh-skills` re-runs `join` to adopt the current epoch.- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.@@ -9,7 +9,7 @@- `src/core/shared-skills/{setup-source-policy,content-freshness}.ts` excludes external, connector, company and opted-out (`config.shared_skills=false`) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. `src/commands/doctor/checks/canonical-content.ts` reports pending publication and recovery separately; it never invents an upstream sync timestamp.- `src/core/shared-skills/{source-opt-out,inventory-limits}.ts` and `src/commands/sources-shared-skills.ts` implement `gbrain sources shared-skills <id> on|off|status`: `off` writes `config.shared_skills=false`, `on` deletes it and releases a parked inventory, and every form reports the configured value and the effective policy mode with its reason. Trusted local only; a remote attempt gets `trusted_local_only` with a `host_admin` fix and a read-only verify. `inventorySkillpack` reads its file-count, total-byte, per-file and entry bounds from the capped `shared_skills.inventory.*` keys; confinement checks are fixed. An overflow (`payload_too_large`) parks the source in its per-source migration record, so the 0.53.0 orchestrator completes and later runs skip it until the bounds change, it opts out, or it is released. `src/commands/doctor/checks/shared-skills.ts` (`shared_skills_sources`) lists opted-out and parked sources. Operator recipe: `docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills`.- `src/core/shared-skills/optimizer.ts` stages opt-in optimization outside canonical roots with the original grants, immutable approved closure and protected metadata. Publication rechecks authority and the original revision through the coordinator; provider evaluation cannot write canonical skill files directly.-- `src/core/persistence/{import-mutations,import-prepare}.ts` routes managed Markdown, code and image import through prepared canonical publication. Source, input, target, owner and revision checks run before apply; derived content retains the source-scoped skill-path guard. `importManagedFiles` takes a batch (at most `IMPORT_BATCH_MAX_PAGES` files and `IMPORT_BATCH_MAX_BYTES`, cut by `nextImportBatch`): each file keeps its own durable intent (`op_checkpoints` `managed-file-import`, written and cleared in one statement per batch), request id, receipt and result; the new requests are admitted in one transaction (`page-batch.ts` `admitBatch`, with its connection-loss re-run and `write_outcome_unknown`) and carry one `intent.import_batch`, so the owner publishes them as independent groups. A file refused before admission settles only that file; a slug the batch already holds ends the batch there, and that file and the rest import after it, as they would one by one. The preparer imports with `coordinated: true`: publication proves the base revision under its page guard, and the apply reads the page once after its write for the read-back check, the projection target, the text seal and the receipt's postimage. Pinned by `test/persistence-import-batch.test.ts` (row-by-row state against one-by-one imports on PGLite and Postgres, resume, lost commit acknowledgment).+- `src/core/persistence/{import-mutations,import-prepare}.ts` routes managed Markdown, code and image import through prepared canonical publication. Source, input, target, owner and revision checks run before apply; derived content retains the source-scoped skill-path guard. `importManagedFiles` takes a batch (at most `IMPORT_BATCH_MAX_PAGES` files and `IMPORT_BATCH_MAX_BYTES`, cut by `nextImportBatch`): each file keeps its own durable intent (`op_checkpoints` `managed-file-import`, written and cleared in one statement per batch), request id, receipt and result; the new requests are admitted in one transaction (`page-batch.ts` `admitBatch`, with its connection-loss re-run and `write_outcome_unknown`) and carry one `intent.import_batch`, so the owner publishes them as independent groups. A file refused before admission settles only that file; a slug the batch already holds ends the batch there, and that file and the rest import after it, as they would one by one. GBRA-75 wave 7: the no-op screen (`unchangedManagedImport`) calls `prepareManagedImportMutation` with `screen: { snapshot }`, the snapshot it just read: the preparer then skips its first path check, the input re-normalization and the snapshot re-read, because the screen just made them, `validate` re-runs every path and byte check last and the no-op kernel re-checks the page revision; a skipped file reads its snapshot once. A canonical input reuses its input hash as the target hash. The plan and screen loops run inside `withScreeningPaths` (`screening-paths.ts`). The preparer imports with `coordinated: true`: publication proves the base revision under its page guard, and the apply reads the page once after its write for the read-back check, the projection target, the text seal and the receipt's postimage. Pinned by `test/persistence-import-batch.test.ts` (row-by-row state against one-by-one imports on PGLite and Postgres, resume, lost commit acknowledgment).- `src/mcp/skill-resources.ts` binds `gbrain://skills` catalog, exact-revision manifests, bodies and approved assets to the equivalent authorized tool dispatch. It does not claim conformance with an unnegotiated draft Skills-over-MCP extension. `src/core/ops/brain-membership.ts` supplies the public self-member operations.- `src/core/shared-skills/retention.ts` preserves active heads, tombstones, recent history, delivery/pin leases and pending publication references. Publication quota checks use exact scalar source/brain counts instead of operator diagnostics; pending references are materialized once and lease lookups use the complete revision identity index. Pruning and capacity checks stay inside the guarded publication transaction.diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex 54a7d70e4b..953ff39f8c 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -19,6 +19,10 @@ export async function overlayCanonicalBodies(query: ReadQuery, body: string, tim/*** One MVCC statement binds content, tags, identity and withdrawals to one revision.+ * The normalized body and timeline fingerprints feed only the withdrawal overlay,+ * so the statement computes them only for a page with withdrawals (as the batch+ * reader in page-snapshot-batch.ts does): per-line regexp over the whole body+ * was most of the cost of every snapshot read.** An alias-resolving read first runs the exact-slug statement: an exact match* outranks every alias match, so a hit is the row the alias statement would@@ -61,15 +65,16 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Page) SELECT p.*,(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags,- COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)+ wd.snapshot_withdrawals,+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)+ FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body,+ CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)+ FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline+ FROM chosen p+ CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_atFROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)- ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals,- (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)- FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body,- (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)- FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline- FROM chosen p`, params);+ ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals) wd`, params);if (!rows.length) return null;const row = rows[0];if (opts?.requireUnambiguous && Number(row.snapshot_matches) > 1) throw new PageSnapshotAmbiguousError();diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex 279e4987af..d758a40ae2 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -1,6 +1,6 @@import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';import { AsyncLocalStorage } from 'node:async_hooks';-import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync, fsyncSync, linkSync, unlinkSync, renameSync } from 'node:fs';+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, writeFileSync, fsyncSync, linkSync, unlinkSync, renameSync } from 'node:fs';import { join } from 'node:path';import { hostname } from 'node:os';import type { BrainEngine } from '../engine.ts';@@ -74,10 +74,30 @@ export function readMachineId(): string | null {function mintedUnderNow(): HostIdentityMintedUnder {return { home: process.env.HOME ?? null, gbrain_home: process.env.GBRAIN_HOME ?? null, hostname: hostname(), machine_id: readMachineId() };}+/**+ * The file identity `readHostIdentity` caches a validated document under: path, device, inode, mtime, ctime and+ * size, so an in-place edit, a rename over the path or another home all miss. Null when the file is absent;+ * undefined for any other stat error, which reads uncached so an unreadable file still fails as before.+ * File timestamps tick coarsely (a few ms on Linux), so a same-size rewrite inside one tick keeps every field:+ * a file modified less than HOST_IDENTITY_RACY_MS ago (or in the future) is read but not cached, as git treats+ * racily clean index entries.+ */+const HOST_IDENTITY_RACY_MS = 2000n;+function hostIdentityKey(path: string): { key: string; settled: boolean } | null | undefined {+ try {+ const stat = statSync(path, { bigint: true });+ const age = BigInt(Date.now()) - stat.mtimeNs / 1_000_000n;+ return { key: [path, stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs, stat.size].join('\0'), settled: age >= HOST_IDENTITY_RACY_MS };+ } catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT' ? null : undefined; }+}+let cachedHostIdentity: { key: string; value: HostIdentityFile } | undefined;function readHostIdentity(path: string, create: boolean): HostIdentityFile | null {- if (!create && !existsSync(path)) return null;+ const key = hostIdentityKey(path);+ if (key?.settled && cachedHostIdentity?.key === key.key) return cachedHostIdentity.value;+ if (!create && (key === null || key === undefined && !existsSync(path))) return null;const value = privateJson<HostIdentityFile>(path, () => ({ version: 1, id: randomUUID(), minted_under: mintedUnderNow() }));if (value.version !== 1 || typeof value.id !== 'string') throw invalidIdentityFile('The local writer identity is invalid.', path, 'host identity');+ if (key?.settled) cachedHostIdentity = { key: key.key, value };return value;}export function localHostId(): string {diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex cc9e58a48e..dd0c6b322f 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -18,6 +18,7 @@ import { digest, sha256 } from './digest.ts';import { assertImportPaths, managedImportContent, prepareManagedImportMutation, readImportBytes, type ImportPack, type ManagedImportIntent } from './import-prepare.ts';import { submissionAuthority } from './authority.ts';import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';+import { withScreeningPaths } from './screening-paths.ts';import type { WorktreeBinding } from './ownership.ts';import type { PageSnapshot } from '../page-state/types.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';@@ -97,7 +98,7 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Maconst planned: Array<{ i: number; slug: string; content: string; sourcePath: string; path: string; inputPath: string; inputHash: string; target: string }> = [];const slugs = new Set<string>();let rest = files.length;- for (let i = 0; i < files.length; i++) {+ await withScreeningPaths(async () => { for (let i = 0; i < files.length; i++) {let { filePath, sourcePath } = files[i]!;try {if (isImageFilePath(sourcePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {@@ -119,7 +120,7 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Maslugs.add(slug);planned.push({ i, slug, content, sourcePath, path, inputPath, inputHash: sha256(bytes), target });} catch (error) { fail(i, error); }- }+ } });if (planned.length) await importPlanned(ctx, binding!, planned, opts, fail, (i, value) => { settled[i] = { status: 'fulfilled', value }; });if (rest < files.length) settled.splice(rest, files.length - rest, ...await importManagedFiles(engine, files.slice(rest), opts));return settled;@@ -150,13 +151,15 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,try {const pending = await readPending(members.map(member => member.key));const fresh: typeof members = [];- for (const member of members) {+ await withScreeningPaths(async () => { for (const member of members) {member.params = pending.get(member.key);if (member.params) continue;try {const snapshot = await engine.readPageSnapshot(member.slug, { sourceId, includeDeleted: true });+ // The input is the canonical file itself (the common case): its hash was taken from the bytes just read.+ const targetHash = member.target === member.inputPath ? member.inputHash : existsSync(member.target) ? sha256(readImportBytes(member.target)) : null;const intent: ManagedImportIntent = { kind: 'managed_file_import', slug: member.slug, content: member.content, sourcePath: member.sourcePath, path: member.path,- inputPath: member.inputPath, inputHash: member.inputHash, targetHash: existsSync(member.target) ? sha256(readImportBytes(member.target)) : null,+ inputPath: member.inputPath, inputHash: member.inputHash, targetHash,ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };// #5470: an import whose publication would change nothing takes no admission.@@ -164,7 +167,7 @@ async function importPlanned(ctx: OperationContext, binding: WorktreeBinding,member.params = { ...intent, ...(members.length > 1 ? { import_batch: batch } : {}), request_id: randomUUID(), source_id: sourceId };fresh.push(member);} catch (error) { refuse(member, error); }- }+ } });if (fresh.length) {await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)SELECT $1,k,c::jsonb FROM unnest($2::text[],$3::text[]) AS u(k,c) ON CONFLICT DO NOTHING`,@@ -255,7 +258,7 @@ async function unchangedManagedImport(ctx: OperationContext, binding: WorktreeBiconst authority = await submissionAuthority(ctx, 'put_page', binding.source_id, binding.source_incarnation, intent.slug);const row = screeningRequest({ source_id: binding.source_id, source_incarnation: binding.source_incarnation, slug: intent.slug,page_id: snapshot.page.id, worktree_id: binding.worktree_id, authority, intent, operation: 'put_page' });- const prepared = await prepareManagedImportMutation(ctx.engine, row, ctx.config);+ const prepared = await prepareManagedImportMutation(ctx.engine, row, ctx.config, { snapshot });if ((await inspectUnchanged(ctx.engine, { prepared, snapshot, sourcePath: intent.sourcePath, databaseOnly: false })).admitReason) return false;await prepared.validate?.(ctx.engine);return true;diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex e65518b775..0ce55aa09d 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -19,11 +19,13 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guimport { getWorktreeBinding } from './ownership.ts';import { localHostId } from './identity.ts';import { sha256 } from './digest.ts';+import { screeningPath } from './screening-paths.ts';import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';@@ -110,7 +112,7 @@ export async function assertImportPaths(engine: BrainEngine, sourceId: string, rconst roots = [source.local_path, source.worktree_path && source.relative_path !== null ? join(source.worktree_path, source.relative_path) : null];for (const candidate of roots) {if (!candidate) continue;- const other = existsSync(candidate) ? realpathSync(candidate) : resolve(candidate);+ const other = screeningPath(`source-root\0${candidate}`, () => existsSync(candidate) ? realpathSync(candidate) : resolve(candidate));for (const path of [input, target]) {const rel = relative(other, path);if (rel === '' || !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)) {@@ -124,7 +126,15 @@ export async function assertImportPaths(engine: BrainEngine, sourceId: string, r}}-export async function prepareManagedImportMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {+/**+ * `screen`: the no-op screen of an unadmitted request (import-mutations.ts), whose caller just checked the+ * paths and read the input bytes and page snapshot it passes. The preparer then skips its own first path check,+ * the input re-normalization and the snapshot re-read: `validate` re-runs every path and byte check last, and the+ * no-op kernel re-checks the page revision, so a skip still rests on all of them; anything else is admitted+ * and prepared again in full by its publication.+ */+export async function prepareManagedImportMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,+ screen?: { snapshot: PageSnapshot | null }): Promise<PreparedMutation> {const p = row.intent as ManagedImportIntent | null;if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('Filesystem import requires a trusted local CLI writer.');if (!p || p.kind !== 'managed_file_import' || typeof p.content !== 'string' || typeof p.inputPath !== 'string' || typeof p.sourcePath !== 'string') {@@ -158,13 +168,13 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri`The canonical copy of ${p.sourcePath} in source ${row.source_id} changed after import request ${row.request_id} was accepted, so it was not overwritten. Review that file, then import again if the import should still replace it.`,{ fix: reimportFix(p.inputPath, row.source_id) });};- await checkPaths(engine);- const normalized = managedImportContent(p.sourcePath, readImportBytes(p.inputPath), p.activePack);+ if (!screen) await checkPaths(engine);+ const normalized = screen ? { slug: row.slug, content: p.content } : managedImportContent(p.sourcePath, readImportBytes(p.inputPath), p.activePack);if (normalized.slug !== row.slug || normalized.content !== p.content) throw opError('source_changed', 'The frozen file identity no longer matches the import.',`${p.sourcePath} now normalizes to different content or slug than import request ${row.request_id} accepted for ${row.slug}, so it published nothing. Import it again to publish the current file.`,{ fix: reimportFix(p.inputPath, row.source_id) });const source = { sourceId: row.source_id };- const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ const snapshot = screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });assertPageRevision(snapshot, p.expected_revision ? { expectedRevision: p.expected_revision } : {});if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.tsindex 7424bc425b..1ff346a70f 100644--- a/src/core/persistence/noop-kernel.ts+++ b/src/core/persistence/noop-kernel.ts@@ -7,7 +7,8 @@* (the preparers read only the database and the local canonical root, so this* runs on the connector or import host), then asks the kernel. An item is* skipped only when:- * - the prepared mutation is a no-op and observed the snapshot revision,+ * - the prepared mutation is a no-op and observed the snapshot revision, and the+ * page still holds that revision when the kernel reads it,* - no projection work is pending (safe-chunk re-seal, text projection behind* the knowledge revision, an embedded page with no contextual mode, or* unembedded chunks when the publication would queue embedding),@@ -76,6 +77,8 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL) AS unembeddedFROM pages p WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);if (!page) return result('page_missing');+ // The page's current revision, read after the preparer ran: a write that landed since the snapshot was read is admitted.+ if (page.knowledge_revision != null && page.knowledge_revision !== snapshot.revision) return result('revision_moved');const waived: NoopKernelWaiver[] = [];const modePending = page.mode_pending === true;if (modePending && input.waive?.includes('contextual_mode')) waived.push('contextual_mode');diff --git a/src/core/persistence/screening-paths.ts b/src/core/persistence/screening-paths.tsnew file mode 100644index 0000000000..e66e4d5985--- /dev/null+++ b/src/core/persistence/screening-paths.ts@@ -0,0 +1,36 @@+import { AsyncLocalStorage } from 'node:async_hooks';++/**+ * One screening batch's memo of root-level filesystem facts (GBRA-75 wave 7).+ *+ * A managed import or sync screens each file of a batch through the same path+ * guards, and those guards resolve the same registered roots for every file:+ * the realpath of each other source's root, the canonical path of each shared+ * skillpack root, the Git scope of the source root. Inside `withScreeningPaths`+ * the guards resolve each such root once; per-file paths (the input, the target,+ * the page's own candidate files) are never memoized, so a file that moves or+ * turns into a symlink is still caught on its own check.+ *+ * The memo only lives while `run` is pending: work that outlives it (a consumer+ * loop started from inside, a later publication) computes everything fresh,+ * and a compute that throws is never memoized.+ */+interface ScreeningPaths { memo: Map<string, unknown>; open: boolean }+const scope = new AsyncLocalStorage<ScreeningPaths>();++/** A nested call joins the open batch it runs in. */+export async function withScreeningPaths<T>(run: () => Promise<T>): Promise<T> {+ if (scope.getStore()?.open) return run();+ const current: ScreeningPaths = { memo: new Map(), open: true };+ try { return await scope.run(current, run); } finally { current.open = false; current.memo.clear(); }+}++/** `compute()` once per open screening batch for `key`; outside a batch, every call computes. */+export function screeningPath<T>(key: string, compute: () => T): T {+ const current = scope.getStore();+ if (!current?.open) return compute();+ if (current.memo.has(key)) return current.memo.get(key) as T;+ const value = compute();+ current.memo.set(key, value);+ return value;+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex e880ebe975..fd618efbc4 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -51,6 +51,7 @@ import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';+import { withScreeningPaths } from './screening-paths.ts';export interface ManagedSyncWriteDiagnostic {source_id: string;@@ -806,6 +807,29 @@ const WAIVER_RUN_MAX = 64;*/async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | null> {+ // The run's screens share one memo of root-level path facts (screening-paths.ts); waiveNoopRun re-validates each entry.+ const run = await withScreeningPaths(() => screenWaiverRun(engine, cursor, head, key, config, assertActive, frozenRun, limit));+ if (!run) return null;+ assertActive();+ const observedAt = frozenRun.observedAt ?? new Date().toISOString();+ const done = await waiveNoopRun(engine, cursor, run, key, async (tx, prefix) => {+ let next: Cursor = cursor;+ for (const { waived } of prefix) next = waivedCursor(next, waived);+ const paths = prefix.map(({ pending }) => pending.intent.path).filter((path): path is string => typeof path === 'string');+ return writeCursor(tx, key, cursor, { ...next, progress: stampProgress(cursor.progress, cursor.index, cursor.index + prefix.length, drainStartedAt) }, async inner => {+ for (const path of await heldGitPaths(inner, cursor.sourceId, cursor.incarnation, paths)) await holdClear(cursor, path, observedAt)!(inner);+ });+ }, tx => currentCursor(tx, key, cursor));+ if (!done) return null;+ for (let index = cursor.index + 1; index <= cursor.index + done.waived; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length, waived: true });+ assertActive();+ return done.next && done.cursor.index === cursor.index + done.waived+ ? saveCursor(engine, key, done.cursor, { ...done.cursor, pending: done.next as Pending }, false, assertActive) : done.cursor;+}++/** waiveRun's screens: the head, then its followers four at a time while each one screens as a waiver. */+async function screenWaiverRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,+ frozenRun: Parameters<typeof freezeEntry>[4], limit: number): Promise<WaiverRunEntry[] | null> {const first = await screenWaiver(engine, cursor, head, config, frozenRun.signal);if (!first) return null;assertActive();@@ -823,21 +847,7 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:}next += batch.length;}- assertActive();- const observedAt = frozenRun.observedAt ?? new Date().toISOString();- const done = await waiveNoopRun(engine, cursor, run, key, async (tx, prefix) => {- let next: Cursor = cursor;- for (const { waived } of prefix) next = waivedCursor(next, waived);- const paths = prefix.map(({ pending }) => pending.intent.path).filter((path): path is string => typeof path === 'string');- return writeCursor(tx, key, cursor, { ...next, progress: stampProgress(cursor.progress, cursor.index, cursor.index + prefix.length, drainStartedAt) }, async inner => {- for (const path of await heldGitPaths(inner, cursor.sourceId, cursor.incarnation, paths)) await holdClear(cursor, path, observedAt)!(inner);- });- }, tx => currentCursor(tx, key, cursor));- if (!done) return null;- for (let index = cursor.index + 1; index <= cursor.index + done.waived; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length, waived: true });- assertActive();- return done.next && done.cursor.index === cursor.index + done.waived- ? saveCursor(engine, key, done.cursor, { ...done.cursor, pending: done.next as Pending }, false, assertActive) : done.cursor;+ return run;}/** #5984 bulk: freezes the followers of an eligible head and records them with it as the cursor's group. */diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 86872d10b9..838f76d18b 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -17,6 +17,7 @@ import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';+import { withScreeningPaths } from './screening-paths.ts';export interface WaiverCursor { sourceId: string; incarnation: string; root: string; gitRoot: string; slugMode: 'git-root' | 'source-root';binding: { worktree_id: string }; authority: SyncAuthority; runId: string; index: number }@@ -134,6 +135,10 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngineexport async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal,frozen?: { snapshot: PageSnapshot | null }): Promise<NoopWaiver | null> {if (!noopWaiversEnabled() || pending.pageId === null) return null;+ return withScreeningPaths(() => screenWaiverEntry(engine, cursor, pending, config, signal, frozen));+}+async function screenWaiverEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal,+ frozen?: { snapshot: PageSnapshot | null }): Promise<NoopWaiver | null> {const intent = pending.intent;if (intent.kind === 'managed_sync_delete') {if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return null;diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.tsindex 6ffacfefde..2b14216116 100644--- a/src/core/shared-skills/knowledge-guard.ts+++ b/src/core/shared-skills/knowledge-guard.ts@@ -2,7 +2,8 @@ import { isAbsolute, relative, resolve, sep } from 'node:path';import { viewedEngine } from '../persistence/switches.ts';import { fileURLToPath } from 'node:url';import { OperationError } from '../ops/contract.ts';-import { isRelativeFileUri, resolveSourceLocalFilePath } from '../markdown.ts';+import { isRelativeFileUri, resolveSourceLocalFilePath, sourceGitScope } from '../markdown.ts';+import { screeningPath } from '../persistence/screening-paths.ts';import { localHostId } from '../persistence/identity.ts';import type { SqlEngine, WriteRequest } from '../persistence/model.ts';import { canonicalFilesystemPath } from '../persistence/root-registry.ts';@@ -73,7 +74,7 @@ export async function assertKnowledgePublicationAllowed(const roots = [...new Set(packs.flatMap(pack => [...(pack.source_root ? [pack.source_root] : []),...(pack.worktree_root !== null && pack.relative_path !== null ? [resolve(pack.worktree_root, pack.relative_path)] : []),- ]))].map(root => canonicalFilesystemPath(root));+ ]))].map(root => screeningPath(`pack-root\0${root}`, () => canonicalFilesystemPath(root)));const paths = preparedFile ? [preparedFile.path] : [];const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid', [row.source_id, row.source_incarnation]);const sourceRoots = [...new Set([...(source?.local_path ? [source.local_path] : []), ...(preparedFile ? [preparedFile.root] : []),@@ -86,7 +87,7 @@ export async function assertKnowledgePublicationAllowed(for (const alias of aliases) {if (alias.source_path) {paths.push(resolve(root, alias.source_path));- const recorded = resolveSourceLocalFilePath(root, alias.source_path, row.slug);+ const recorded = resolveSourceLocalFilePath(root, alias.source_path, row.slug, undefined, screeningPath(`git-scope\0${root}`, () => sourceGitScope(root)));if (recorded) paths.push(recorded);}if (alias.source_uri?.startsWith('file:') && !isRelativeFileUri(alias.source_uri)) {diff --git a/test/persistence-host-identity-cache.serial.test.ts b/test/persistence-host-identity-cache.serial.test.tsnew file mode 100644index 0000000000..2218fba29d--- /dev/null+++ b/test/persistence-host-identity-cache.serial.test.ts@@ -0,0 +1,105 @@+import { describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { existingLocalHostId, localHostId, localHostIdentity, persistenceHome } from '../src/core/persistence/identity.ts';+import { withEnv } from './helpers/with-env.ts';++const ID_A = '11111111-1111-4111-8111-111111111111';+const ID_B = '22222222-2222-4222-8222-222222222222';++async function inHome(run: (hostFile: string) => void | Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-host-cache-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ mkdirSync(persistenceHome(), { recursive: true, mode: 0o700 });+ await run(join(persistenceHome(), 'host.json'));+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}+const write = (path: string, id: string) => writeFileSync(path, JSON.stringify({ version: 1, id }), { mode: 0o600 });+/** A settled identity file: modified long enough ago to be cacheable. */+const writeSettled = (path: string, id: string) => { write(path, id); const old = new Date(Date.now() - 60_000); utimesSync(path, old, old); };++describe('host identity cache (stat-keyed)', () => {+ test('a repeated read of a settled, unchanged file is served without reading it again', async () => {+ await inHome(path => {+ writeSettled(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ const reads = spyOn(fs, 'readFileSync');+ try {+ expect(localHostId()).toBe(ID_A);+ expect(localHostIdentity().id).toBe(ID_A);+ expect(existingLocalHostId()).toBe(ID_A);+ expect(reads.mock.calls.filter(([file]) => file === path)).toHaveLength(0);+ } finally { reads.mockRestore(); }+ });+ });++ test('an in-place edit is seen (mtime and ctime move)', async () => {+ await inHome(path => {+ writeSettled(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ write(path, ID_B);+ expect(localHostId()).toBe(ID_B);+ });+ });++ test('same-size rewrites inside one timestamp tick are each seen (a recent file is never cached)', async () => {+ await inHome(path => {+ for (const id of [ID_A, ID_B, ID_A, ID_B]) {+ write(path, id);+ expect(localHostId()).toBe(id);+ }+ });+ });++ test('a rename over the path is seen (inode moves), as the fixture harness selects a host', async () => {+ await inHome(path => {+ writeSettled(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ const staged = `${path}.staged`;+ writeSettled(staged, ID_B);+ renameSync(staged, path);+ expect(localHostId()).toBe(ID_B);+ });+ });++ test('a different home reads its own identity', async () => {+ await inHome(async path => {+ writeSettled(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ await inHome(inner => {+ writeSettled(inner, ID_B);+ expect(localHostId()).toBe(ID_B);+ });+ expect(localHostId()).toBe(ID_A);+ });+ });++ test('an absent file is never minted by existingLocalHostId, even after a cached read elsewhere', async () => {+ await inHome(async path => {+ writeSettled(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ rmSync(path);+ expect(existingLocalHostId()).toBeNull();+ expect(existsSync(path)).toBe(false);+ const minted = localHostId();+ expect(minted).not.toBe(ID_A);+ expect(JSON.parse(readFileSync(path, 'utf8')).id).toBe(minted);+ expect(localHostId()).toBe(minted);+ });+ });++ test('an invalid identity file throws on every call and is never cached', async () => {+ await inHome(path => {+ writeFileSync(path, JSON.stringify({ version: 2, id: ID_A }), { mode: 0o600 });+ const old = new Date(Date.now() - 60_000); utimesSync(path, old, old);+ for (let i = 0; i < 3; i++) expect(() => localHostId()).toThrow(expect.objectContaining({ code: 'writer_identity_invalid' }));+ expect(() => existingLocalHostId()).toThrow(expect.objectContaining({ code: 'writer_identity_invalid' }));+ write(path, ID_A);+ expect(localHostId()).toBe(ID_A);+ });+ });+});diff --git a/test/persistence-skip-cost.test.ts b/test/persistence-skip-cost.test.tsnew file mode 100644index 0000000000..b2fbaa3ebe--- /dev/null+++ b/test/persistence-skip-cost.test.ts@@ -0,0 +1,163 @@+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import * as fs from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importManagedFile } from '../src/core/persistence/import-mutations.ts';+import { assertImportPaths } from '../src/core/persistence/import-prepare.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { screeningPath, withScreeningPaths } from '../src/core/persistence/screening-paths.ts';+import { readPageSnapshot } from '../src/core/page-state/snapshot.ts';+import { inspectUnchanged } from '../src/core/persistence/noop-kernel.ts';+import type { PreparedMutation } from '../src/core/persistence/coordinator.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++// GBRA-75 wave 7: the fixed cost of a file the managed import screen skips. A skipped file reads its page+// snapshot once, the snapshot statement computes withdrawal fingerprints only for a page with withdrawals,+// root-level path facts resolve once per screening batch, and a page written after the snapshot is still admitted.++const home = mkdtempSync(join(tmpdir(), 'gbrain-skip-cost-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => { for (const engine of engines) await fn(engine); });+const admissions = async (engine: BrainEngine, sourceId: string) =>+ (await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).length;++async function source(engine: BrainEngine) {+ const sourceId = `skip-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ mkdirSync(root);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ return { sourceId, root };+}++async function importedNote(engine: BrainEngine) {+ const s = await source(engine);+ const file = join(s.root, 'note.md');+ writeFileSync(file, '---\ntitle: Note\n---\nThe first durable observation.\n');+ const run = () => importManagedFile(engine, file, 'note.md', { sourceId: s.sourceId, noEmbed: true });+ expect((await run()).status).toBe('imported');+ expect((await run()).status).toBe('skipped');+ return { ...s, file, run };+}++describe('skipped-file cost', () => {+ test('an unchanged re-import is skipped after one page snapshot read and no admission', async () => each(async engine => {+ const note = await importedNote(engine);+ const before = await admissions(engine, note.sourceId);+ const reads = spyOn(engine, 'readPageSnapshot');+ try {+ expect((await note.run()).status).toBe('skipped');+ expect(reads).toHaveBeenCalledTimes(1);+ } finally { reads.mockRestore(); }+ expect(await admissions(engine, note.sourceId)).toBe(before);+ }));++ test('a file edited after the screen read it is admitted, not skipped (validate re-checks its bytes)', async () => each(async engine => {+ const note = await importedNote(engine);+ const before = await admissions(engine, note.sourceId);+ const original = engine.readPageSnapshot.bind(engine);+ let edited = false;+ const reads = spyOn(engine, 'readPageSnapshot').mockImplementation(async (slug, opts) => {+ if (!edited) { edited = true; writeFileSync(note.file, '---\ntitle: Note\n---\nAn edit that landed during the screen.\n'); }+ return original(slug, opts);+ });+ try { await note.run().catch(() => undefined); } finally { reads.mockRestore(); }+ expect(edited).toBe(true);+ expect(await admissions(engine, note.sourceId)).toBeGreaterThan(before);+ }), 60_000);++ test('the no-op kernel admits a page written after the snapshot the screen prepared against', async () => each(async engine => {+ const note = await importedNote(engine);+ const snapshot = (await engine.readPageSnapshot('note', { sourceId: note.sourceId, includeDeleted: true }))!;+ const prepared = { noop: true, observedRevision: snapshot.revision, validate: async () => {}, apply: async () => ({}) } as unknown as PreparedMutation;+ const inspect = () => inspectUnchanged(engine, { prepared, snapshot, sourcePath: snapshot.page.source_path ?? null, databaseOnly: true });+ expect((await inspect()).admitReason).toBeUndefined();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { await engine.executeRaw("UPDATE pages SET title='Moved' WHERE source_id=$1 AND slug='note'", [note.sourceId]); }+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ expect((await inspect()).admitReason).toBe('revision_moved');+ }));++ test('the snapshot statement computes withdrawal fingerprints only for a page with withdrawals', async () => each(async engine => {+ const note = await importedNote(engine);+ const rows: Array<Record<string, unknown>> = [];+ const query = async <T>(sql: string, params?: unknown[]) => { const r = await engine.executeRaw<T>(sql, params); rows.push(...(r as Array<Record<string, unknown>>)); return r; };+ const plain = await readPageSnapshot(query, 'note', { sourceId: note.sourceId });+ expect(plain?.withdrawals).toEqual([]);+ expect(rows.at(-1)!.fingerprint_body ?? null).toBeNull();+ expect(rows.at(-1)!.fingerprint_timeline ?? null).toBeNull();+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash) VALUES($1,'world','note','h-1')", [note.sourceId]);+ const withdrawn = await readPageSnapshot(query, 'note', { sourceId: note.sourceId });+ expect(withdrawn?.withdrawals.map(w => w.fact_hash)).toEqual(['h-1']);+ expect(String(rows.at(-1)!.fingerprint_body)).toContain('the first durable observation.');+ expect(withdrawn?.page.compiled_truth).toBe(plain?.page.compiled_truth);+ }));++ test('inside one screening batch the other sources\' roots resolve once; outside it every check resolves them', async () => each(async engine => {+ const own = await source(engine);+ const others = [await source(engine), await source(engine)];+ const target = join(own.root, 'note.md');+ writeFileSync(target, 'x\n');+ const realpaths = spyOn(fs, 'realpathSync');+ const otherRootCalls = () => realpaths.mock.calls.filter(([path]) => others.some(o => path === o.root)).length;+ try {+ await assertImportPaths(engine, own.sourceId, own.root, target, target);+ const perCheck = otherRootCalls();+ expect(perCheck).toBeGreaterThanOrEqual(others.length);+ realpaths.mockClear();+ for (let i = 0; i < 3; i++) await assertImportPaths(engine, own.sourceId, own.root, target, target);+ expect(otherRootCalls()).toBe(3 * perCheck);+ realpaths.mockClear();+ await withScreeningPaths(async () => { for (let i = 0; i < 3; i++) await assertImportPaths(engine, own.sourceId, own.root, target, target); });+ expect(otherRootCalls()).toBe(others.length);+ } finally { realpaths.mockRestore(); }+ await expect(assertImportPaths(engine, own.sourceId, own.root, join(others[0]!.root, 'x.md'), join(others[0]!.root, 'x.md')))+ .rejects.toMatchObject({ code: 'source_changed' });+ }));+});++describe('screening path memo', () => {+ test('memoizes per open batch, joins nested batches, forgets on exit and never memoizes a throw', async () => {+ let calls = 0;+ const compute = () => ++calls;+ expect(screeningPath('k', compute)).toBe(1);+ expect(screeningPath('k', compute)).toBe(2);+ let escaped: (() => number) | undefined;+ await withScreeningPaths(async () => {+ expect(screeningPath('k', compute)).toBe(3);+ expect(screeningPath('k', compute)).toBe(3);+ await withScreeningPaths(async () => { expect(screeningPath('k', compute)).toBe(3); });+ let failures = 0;+ const failing = () => { failures++; throw new Error('enoent'); };+ expect(() => screeningPath('bad', failing)).toThrow('enoent');+ expect(() => screeningPath('bad', failing)).toThrow('enoent');+ expect(failures).toBe(2);+ escaped = () => screeningPath('k', compute);+ });+ expect(escaped!()).toBe(4);+ expect(screeningPath('k', compute)).toBe(5);+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 40b51ce850..75296fe03f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -90,6 +90,7 @@ test/persistence-preactivation-claim.test.tstest/persistence-reconcile-git-dirty-6138.test.tstest/persistence-skill-bundles.serial.test.tstest/persistence-skill-crash.slow.test.ts+test/persistence-skip-cost.test.tstest/persistence-sync-cursor-options.test.tstest/persistence-sync-fence-holds.test.tstest/persistence-sync-holds.test.ts