Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(read): get_page file_held, stale search hits and held_files coverage notice (#5988)
garrytan814a72a55eca
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 702f57e443..369d7af1de 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -9,7 +9,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`empty_retrieval`, `unknown_param`, `listing_truncated`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.+- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.serial.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated.serial.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 554955b745..08659fff84 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -36,14 +36,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`.-- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`.+- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`.- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.- `src/core/ops/persistence.ts` — get/list/cancel own-write receipt controls, all requiring write scope and an explicit current operation grant. SQL principal/source/incarnation plus current operation and prefix predicates precede list pagination; original accepted authority and current source/slug grants remain the final guard. Public output selects receipt fields and target metadata only; a failed receipt adds `write_error_message`, the same allowlisted `writeFailureDiagnostic` message managed sync prints, never raw journal error text (`test/sync-frontmatter-slug-conflict.test.ts`). Cancellation rechecks receipt permission under the same transaction grant locks as the original write. Starter/full expose the helpers; frozen verbs stay unchanged, and existing operation snapshots require explicit regrant. Tests: `test/persistence-receipt-operations.test.ts`, `test/client-grants.test.ts`, `test/mcp-surface.test.ts`.- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`).+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; one summary read and one indexed hold lookup per call; remote callers get counts and flags only). Test: `test/held-read-signals.test.ts`.- `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).diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 29d0b4d224..f0da368630 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -17,7 +17,7 @@- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` count; `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `sources status` / `retry-held`, never `readAllSourceHolds`. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`.+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `sources status` / `retry-held`, never `readAllSourceHolds`. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v199) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c90e62ec79..771263460a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grownsrc/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216)src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key-src/core/types.ts 2123 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes)+src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keyssrc/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -39,6 +39,6 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap insrc/core/config.ts 1824 ratchet +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keyssrc/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook envsrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 659 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts)+src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)src/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= partsrc/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 18bb96e9af..8c6f5e8eb6 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -327,4 +327,6 @@ export const NOTICE_CODES = {onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },+ held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },+ recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex 4a03b6cd98..7bf7c5aacb 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -21,7 +21,7 @@ const MAX_KEYS = 10_000;const TTL_MS = 24 * 60 * 60 * 1000;export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts', 'held_files']);export interface NoticeAudience {transport: Transport;diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex dfaaec3346..00488aa6a2 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -18,6 +18,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { getContentFlag } from '../quarantine.ts';+import { fileHeldField, readHeldPages } from '../persistence/held-reads.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';@@ -77,7 +78,7 @@ const get_page: Operation = {name: 'get_page',idempotent: true,outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },- description: 'Read a page by slug (supports optional fuzzy matching). Slug aliases left by renames redirect to the canonical page in the source that owns the alias (archived sources excluded); a redirected read reports `resolved_slug`. To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (the soft-delete recovery window). `timeline` is only the markdown section after the timeline sentinel; entries written by add_timeline_entry or extraction live in timeline rows, which include_timeline_entries: true returns as `timeline_entries` (the same rows get_timeline returns).',+ description: 'Read a page by slug (supports optional fuzzy matching). Slug aliases left by renames redirect to the canonical page in the source that owns the alias (archived sources excluded); a redirected read reports `resolved_slug`. To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (the soft-delete recovery window). `timeline` is only the markdown section after the timeline sentinel; entries written by add_timeline_entry or extraction live in timeline rows, which include_timeline_entries: true returns as `timeline_entries` (the same rows get_timeline returns). `file_held` means sync holds this page\'s newer file: you are reading the last good revision, and put_page refuses until the file is repaired (follow its fix).',params: {slug: { type: 'string', required: true, description: 'Page slug' },fuzzy: { type: 'boolean', description: 'Enable fuzzy slug resolution (default: false)' },@@ -186,6 +187,8 @@ const get_page: Operation = {// it" signal it would get from search. The marker is also in frontmatter;// this is the clean, documented accessor.const content_flag = getContentFlag(page.frontmatter as Record<string, unknown> | null);+ // #5988: sync holds the page's newer file (one indexed lookup, fail-open).+ const held = (await readHeldPages(ctx.engine, [page.id], ctx).catch(() => null))?.get(page.id);// #2225: `content` is the canonical serialized markdown (frontmatter +// compiled_truth + `<!-- timeline -->` sentinel + timeline). Clients that// edit-and-put_page this field round-trip losslessly; hand-concatenating@@ -204,6 +207,7 @@ const get_page: Operation = {? { timeline_entries: await ctx.engine.getTimeline(page.slug, await readPolicyOpts(ctx, { sourceId: page.source_id })) } : {}),...(resolved_slug ? { resolved_slug } : {}),...(content_flag ? { content_flag } : {}),+ ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}),};},scope: 'read', mutating: false,diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 744ea0ba1e..fa6a999b78 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -34,6 +34,7 @@ import { probeProjectionReadiness } from '../search/projection-readiness.ts';import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';+import { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';import { opError } from './contract.ts';import type { Operation, OperationContext } from './contract.ts';import { invalidParam, paramUse } from './op-fix.ts';@@ -346,6 +347,10 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que* a result for a remote caller whose scope still holds unsealed pages gets* `safe_index_pending` appended, whether it came back empty or partial. The* withholding itself is unchanged.+ *+ * #5988: hits whose page's newer file is held get `stale` (the rows are the+ * call's own copies, stamped in place), and a scope with held files gets+ * `held_files` per source plus the `held_files` degraded notice.*/async function buildRetrievalResponseMeta(ctx: OperationContext,@@ -372,6 +377,9 @@ async function buildRetrievalResponseMeta(});const aliases = aliasDeclarations(results as Array<{ slug: string; title?: string; chunk_text?: string }>, queryText);const savedFacts = await matchingSavedFacts(ctx, scope, queryText, aliases);+ const heldFiles = await stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []);+ const heldNotice = heldFilesNotice(heldFiles, ctx.remote !== false);+ if (heldNotice) ctx.emitNotice?.(heldNotice);const degraded = [...(m?.degraded ?? [])];if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });if (readiness.status !== 'ready') {@@ -395,6 +403,7 @@ async function buildRetrievalResponseMeta(...(opts.typeFilterNotice ? { type_filter_notice: opts.typeFilterNotice } : {}),...(savedFacts.length ? { saved_facts: savedFacts } : {}),...(aliases.length ? { other_names: aliases } : {}),+ ...(heldFiles.length ? { held_files: heldFiles } : {}),...(hint || readiness.hint ? { hint: [hint, readiness.hint].filter(Boolean).join(' ') } : {}),};}diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsnew file mode 100644index 0000000000..856145f566--- /dev/null+++ b/src/core/persistence/held-reads.ts@@ -0,0 +1,149 @@+/**+ * #5988 read-time hold signals. A page whose newer file sync holds keeps its+ * last good revision, and a held new file has no page at all, so an agent+ * answering from reads must learn that coverage is partial:+ *+ * - `get_page` carries `file_held` (code, reason, key, line, since, fix, docs;+ * the file path for trusted local callers only).+ * - search and query hits for such a page carry `stale` (held_since, last_indexed_revision).+ * - retrieval meta carries `held_files` per source in scope (held new files+ * missing, held modified files stale) and a `held_files` degraded notice.+ *+ * Cost: one indexed lookup (`op_checkpoints_sync_hold_page_idx`) for the pages+ * a call returns and one read of the per-source summary rows in scope, each+ * cached per request. Remote callers get codes, counts and flags, never paths,+ * and a fix addressed to the brain host operator.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action, Notice } from '../agent-output.ts';+import { ALL_SOURCES } from '../source-id.ts';+import { GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, gitHoldDocs, gitHoldFix, type GitHoldCode, type GitHoldReason, type GitHoldRecord } from './sync-holds.ts';++type Exec = Pick<BrainEngine, 'executeRaw'>;++export interface HeldPage { record: GitHoldRecord; revision: string | null }++/** Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`). */+export interface HeldCoverage { source_id: string; missing: number; stale: number }++/** `get_page.file_held`. */+export interface FileHeld {+ code: GitHoldCode;+ reason?: GitHoldReason;+ key?: string;+ line?: number;+ since: string;+ /** Source-relative file path; trusted local callers only. */+ path?: string;+ fix: Action;+ docs: string;+}++/** A search or query hit whose page's newer file is held. */+export interface StaleHit { held_since: string; last_indexed_revision: string | null }++const requestCache = new WeakMap<object, Map<string, Promise<unknown>>>();++/** Memoizes one read per request (the OperationContext); without a request object it just runs. */+function cached<T>(request: object | undefined, key: string, read: () => Promise<T>): Promise<T> {+ if (!request) return read();+ let entries = requestCache.get(request);+ if (!entries) requestCache.set(request, entries = new Map());+ if (!entries.has(key)) entries.set(key, read());+ return entries.get(key) as Promise<T>;+}++/** The current-incarnation holds naming these pages, with each page's revision: one indexed read. */+export function readHeldPages(engine: Exec, pageIds: number[], request?: object): Promise<Map<number, HeldPage>> {+ const ids = [...new Set(pageIds.filter(id => Number.isInteger(id)))].sort((a, b) => a - b);+ if (!ids.length) return Promise.resolve(new Map());+ return cached(request, `pages:${ids.join(',')}`, async () => {+ const rows = await engine.executeRaw<{ record: GitHoldRecord; revision: string | null }>(`SELECT h.completed_keys->0 AS record, p.knowledge_revision::text AS revision+ FROM op_checkpoints h+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'+ LEFT JOIN pages p ON p.id::text=h.completed_keys->0->>'page_id'+ WHERE h.op=$1 AND (h.completed_keys->0->>'page_id')=ANY($2::text[])+ ORDER BY h.fingerprint`, [GIT_HOLD_OP, ids.map(String)]);+ const out = new Map<number, HeldPage>();+ for (const row of rows) {+ const id = Number(row.record.page_id);+ if (!out.has(id)) out.set(id, { record: row.record, revision: row.revision });+ }+ return out;+ });+}++/** Per-source held-file counts in a read scope (sources with none are absent): one read of the summary rows. */+export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourceIds?: string[] }, request?: object): Promise<HeldCoverage[]> {+ const ids = scope.sourceIds ?? (scope.sourceId !== undefined && scope.sourceId !== ALL_SOURCES ? [scope.sourceId] : null);+ if (ids && !ids.length) return Promise.resolve([]);+ return cached(request, `coverage:${ids ? [...ids].sort().join(',') : '*'}`, async () => {+ const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string }>(`SELECT s.id AS source_id,+ COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale+ FROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::text+ WHERE h.op=$1 AND s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))+ AND COALESCE((h.completed_keys->0->>'count')::int,0)>0+ ORDER BY s.id`, [GIT_HOLD_SUMMARY_OP, ids]);+ return rows.map(row => {+ const count = Number(row.count), stale = Math.min(Number(row.stale), count);+ return { source_id: row.source_id, missing: count - stale, stale };+ });+ });+}++function repairArgv(sourceId: string): string[] {+ return ['gbrain', 'repair', 'frontmatter', '--source', sourceId];+}++/** The fix a remote caller relays: only the brain host operator can inspect and repair held files. */+function hostOperatorFix(sourceIds: string[], why: string): Action {+ const commands = sourceIds.map(id => `'${repairArgv(id).join(' ')}'`).join(', ');+ return { argv: repairArgv(sourceIds[0]!), consent: [], actor: 'host_admin', requires_exclusive: false, why,+ user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. Please run ${commands} on the brain host to preview the fixes, then apply them.` };+}++/** `get_page.file_held` for a page whose newer file is held; the path only for trusted local callers. */+export function fileHeldField(held: HeldPage, remote: boolean): FileHeld {+ const { record } = held;+ const fix = remote+ ? hostOperatorFix([record.source_id], `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision and is read-only for put_page until the brain host operator repairs the file.`)+ : gitHoldFix(record);+ return { code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}), ...(record.meta.key ? { key: record.meta.key } : {}),+ ...(record.meta.line !== undefined ? { line: record.meta.line } : {}), since: record.held_at, ...(remote ? {} : { path: record.path }),+ fix, docs: gitHoldDocs(record.code, record.meta.reason) };+}++/**+ * Stamps `stale` on hits whose page's newer file is held (one indexed read)+ * and returns the per-source coverage of the read scope. Hits are mutated in+ * place; callers pass their own copies.+ */+export async function stampHeldHits(engine: Exec, hits: Array<{ page_id?: number; stale?: boolean | StaleHit }>, scope: { sourceId?: string; sourceIds?: string[] },+ request?: object): Promise<HeldCoverage[]> {+ const coverage = await readHeldCoverage(engine, scope, request);+ if (!coverage.some(source => source.stale > 0) || !hits.length) return coverage;+ const held = await readHeldPages(engine, hits.flatMap(hit => typeof hit.page_id === 'number' ? [hit.page_id] : []), request);+ for (const hit of hits) {+ const page = typeof hit.page_id === 'number' ? held.get(hit.page_id) : undefined;+ if (page) hit.stale = { held_since: page.record.held_at, last_indexed_revision: page.revision };+ }+ return coverage;+}++/** The `held_files` notice for a read whose scope has held files; null when it has none. */+export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean): Notice | null {+ if (!coverage.length) return null;+ const missing = coverage.reduce((sum, source) => sum + source.missing, 0), stale = coverage.reduce((sum, source) => sum + source.stale, 0);+ const per = coverage.map(source => `${source.source_id}: ${source.missing} missing, ${source.stale} stale`).join('; ');+ const why = `Coverage is partial: sync holds ${missing + stale} file(s) it cannot import (${per}). `+ + `${missing} held new file(s) have no page, so their content is absent from this result; ${stale} page(s) whose newer file is held show their last good revision (hits carry stale). `+ + 'Treat a missing or outdated answer as "held", never as "the brain has nothing on this".';+ const ids = coverage.map(source => source.source_id);+ if (remote) return { code: 'held_files', kind: 'degraded', why: `${why} Only the brain host operator can inspect and repair held files.`, fix: hostOperatorFix(ids, 'The repair preview on the brain host proposes each fix and writes nothing until the operator applies it.') };+ const fix: Action = ids.length === 1+ ? { argv: repairArgv(ids[0]!), consent: [], actor: 'agent', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', ids[0]!, '--json'] },+ why: `Previews the fix for each held file in source ${ids[0]} (gbrain sources status ${ids[0]} lists them); nothing is written until a hash-bound apply.` }+ : { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Doctor lists the held files of each source with its repair preview command (${ids.map(id => repairArgv(id).join(' ')).join('; ')}).` };+ return { code: 'held_files', kind: 'degraded', why, fix };+}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 9fc32b8e7e..50474caa38 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -7,8 +7,10 @@** Storage: one `op_checkpoints` row per hold (op `sync-hold`, fingerprint* `source:incarnation:path`) and one small per-source summary row (op- * `sync-hold-summary`) holding the count, so a sync that holds 20k files- * writes O(1) rows per hold and a status read never loads a source-wide list.+ * `sync-hold-summary`) holding the count (and `stale`, how many name an+ * existing page), so a sync that holds 20k files writes O(1) rows per hold and+ * neither a status read nor a search loads a source-wide list. Read paths find+ * a page's hold by page id through `op_checkpoints_sync_hold_page_idx`.* Managed and legacy sync write the same rows; they survive writer mode* changes and are exempt from the 7-day checkpoint purge.*@@ -106,19 +108,23 @@ const summaryFingerprint = (sourceId: string, incarnation: string) => `${sourceI/** Locks the source's summary row (creating it), so hold writes of one source serialize. */async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Promise<number> {const [row] = await tx.executeRaw<{ count: number | string }>(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)- VALUES($1,$2,jsonb_build_array(jsonb_build_object('source_id',$3::text,'incarnation',$4::text,'count',0)))+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('source_id',$3::text,'incarnation',$4::text,'count',0,'stale',0)))ON CONFLICT(op,fingerprint) DO UPDATE SET updated_at=now()RETURNING COALESCE((completed_keys->0->>'count')::int,0) AS count`,[GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), sourceId, incarnation]);return Number(row?.count ?? 0);}-async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number): Promise<void> {- await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,count}',- to_jsonb(GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta]);+/** `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages). */+async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number): Promise<void> {+ await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)||jsonb_build_object(+ 'count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),+ 'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta]);}+const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record && record.page_id !== null ? 1 : 0;+async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',[GIT_HOLD_OP, gitHoldFingerprint(sourceId, incarnation, path)]);@@ -140,8 +146,11 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'versionawait tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,[GIT_HOLD_OP, gitHoldFingerprint(input.source_id, input.incarnation, input.path), JSON.stringify([record])]);- if (existing) return 'updated';- await adjustSummary(tx, input.source_id, input.incarnation, 1);+ if (existing) {+ if (staleWeight(input) !== staleWeight(existing)) await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing));+ return 'updated';+ }+ await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input));return 'inserted';}@@ -157,7 +166,7 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnatconst existing = await readRow(tx, input.sourceId, input.incarnation, input.path);if (!existing || existing.observed_at > input.observedAt) return false;await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);- await adjustSummary(tx, input.sourceId, input.incarnation, -1);+ await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing));return true;}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 6193bdf631..28b780a0c4 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -393,6 +393,8 @@ CREATE TABLE IF NOT EXISTS op_checkpoints ();CREATE INDEX IF NOT EXISTS op_checkpoints_updated_at_idxON op_checkpoints (updated_at);+CREATE INDEX IF NOT EXISTS op_checkpoints_sync_hold_page_idx+ ON op_checkpoints ((completed_keys->0->>'page_id')) WHERE op = 'sync-hold';CREATE TABLE IF NOT EXISTS op_checkpoint_paths (op TEXT NOT NULL,diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 29b235928e..8fa8276c84 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -784,6 +784,9 @@ CREATE TABLE IF NOT EXISTS op_checkpoints ();CREATE INDEX IF NOT EXISTS op_checkpoints_updated_at_idxON op_checkpoints (updated_at);+-- #5988: read paths find the Git hold of a page by its id (migration v199).+CREATE INDEX IF NOT EXISTS op_checkpoints_sync_hold_page_idx+ ON op_checkpoints ((completed_keys->0->>'page_id')) WHERE op = 'sync-hold';-- #1794: append-only delta storage. One row per completed path; sync's-- appendCompleted INSERTs only the delta instead of rewriting the wholediff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 13fe187cb2..1e20d0c4c3 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -199,6 +199,7 @@ import { v195 } from './v195-f3-access-token-grants.ts';import { v196 } from './v196-f4-planner-stats.ts';import { v197 } from './v197-managed-guard-null-source-fallback.ts';import { v198 } from './v198-publication-failure-detail.ts';+import { v199 } from './v199-sync-hold-page-index.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -396,4 +397,5 @@ export const MIGRATIONS: Migration[] = [v196,v197,v198,+ v199,];diff --git a/src/core/schema-migrations/v199-sync-hold-page-index.ts b/src/core/schema-migrations/v199-sync-hold-page-index.tsnew file mode 100644index 0000000000..4002bcd7b8--- /dev/null+++ b/src/core/schema-migrations/v199-sync-hold-page-index.ts@@ -0,0 +1,18 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #5988 read-time hold signals: get_page, search and query look up the Git+// holds of the pages they return by page id in one indexed read+// (src/core/persistence/held-reads.ts). Partial: only `sync-hold` rows.+const INDEX_SQL = `CREATE INDEX IF NOT EXISTS op_checkpoints_sync_hold_page_idx+ ON op_checkpoints ((completed_keys->0->>'page_id')) WHERE op = 'sync-hold';`;++export const v199: Migration = {+ version: 199,+ name: 'sync_hold_page_index',+ idempotent: true,+ sql: INDEX_SQL,+ sqlFor: { postgres: `SET LOCAL statement_timeout = '30s'; SET LOCAL lock_timeout = '2s';\n ${INDEX_SQL}` },+};diff --git a/src/core/types.ts b/src/core/types.tsindex 0a237fd67b..652952789f 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -809,7 +809,8 @@ export interface SearchResult {chunk_id: number;chunk_index: number;score: number;- stale: boolean;+ /** #5988: `{ held_since, last_indexed_revision }` when sync holds the page's newer file (stampHeldHits). */+ stale: boolean | { held_since: string; last_indexed_revision: string | null };/*** v0.42 (issue #1699) content-quality gate agent-warning channel. Set* when the result's page carries a `frontmatter.content_flag` markerdiff --git a/src/schema.sql b/src/schema.sqlindex 35190bab4b..0ef84a2cdf 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -780,6 +780,9 @@ CREATE TABLE IF NOT EXISTS op_checkpoints ();CREATE INDEX IF NOT EXISTS op_checkpoints_updated_at_idxON op_checkpoints (updated_at);+-- #5988: read paths find the Git hold of a page by its id (migration v199).+CREATE INDEX IF NOT EXISTS op_checkpoints_sync_hold_page_idx+ ON op_checkpoints ((completed_keys->0->>'page_id')) WHERE op = 'sync-hold';-- #1794: append-only delta storage. One row per completed path; sync's-- appendCompleted INSERTs only the delta instead of rewriting the wholediff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 609b8742b2..7bee8218bf 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 193,+ "count": 194,"gaps": [17,18,@@ -28,7 +28,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 198,+ "latest": 199,"records": [{"handler": {@@ -2936,6 +2936,25 @@"transaction": "absent","verify": "absent","version": 198+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "sync_hold_page_index",+ "sql": {+ "length": 142,+ "sha256": "0b4978889af397294e5793f9f68968c06c5d52aeb7dc51dcfe7536e2a90e5e43"+ },+ "sqlFor": {+ "pglite": "absent",+ "postgres": {+ "length": 216,+ "sha256": "c61746809b754cfdae37a083465277079995534ec15223eccc81bccefc97f7ac"+ }+ },+ "transaction": "absent",+ "verify": "absent",+ "version": 199}],"versions": [@@ -3131,7 +3150,8 @@195,196,197,- 198+ 198,+ 199]},"normalizer": "migrations-record-v1"diff --git a/test/held-read-signals.test.ts b/test/held-read-signals.test.tsnew file mode 100644index 0000000000..2169e2d0e0--- /dev/null+++ b/test/held-read-signals.test.ts@@ -0,0 +1,206 @@+/**+ * #5988 read-time hold signals. A page whose newer file sync holds keeps its+ * last good revision and a held new file has no page, so reads say so:+ * get_page carries `file_held` (the path for trusted local callers only),+ * search hits for such a page carry `stale`, and the retrieval meta carries+ * `held_files` per source plus a `held_files` degraded notice. Remote callers+ * get codes, counts and flags, never paths, with a fix addressed to the brain+ * host operator. Each read costs one indexed hold lookup and one summary read.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+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 type { Notice } from '../src/core/agent-output.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { performSync } from '../src/commands/sync.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { PER_CALL_NOTICE_CODES } from '../src/core/notice-ledger.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { readHeldCoverage } from '../src/core/persistence/held-reads.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let engine: BrainEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-held-reads-'));+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();+const getPage = operations.find(op => op.name === 'get_page')!;+const search = operations.find(op => op.name === 'search')!;+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic note about the quarterly widget roadmap and ${title}.\n`;+const BROKEN = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic note about the quarterly widget roadmap.\n';++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engines.push(pglite);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const each of engines) {+ await each.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await each.setConfig('search.mcp_keyword_only', 'true');+ }+}, 120_000);++afterAll(async () => {+ for (const each of engines) if (each.kind === 'pglite') await each.disconnect();+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++const eachEngine = (fn: () => Promise<void>) => withEnv(env, async () => {+ for (const each of engines) { engine = each; await fn(); }+});++async function source(files: Record<string, string>): Promise<{ id: string; root: string }> {+ const id = `hr-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);+ mkdirSync(join(root, 'notes'), { recursive: true }); await makeGitFixture(root);+ commit(root, files);+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ return { id, root };+}++function commit(root: string, files: Record<string, string>): void {+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture content');+}++const sync = (id: string, root: string) => performSync(engine, { repoPath: root, sourceId: id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });++/** A held source: notes/a.md imported then broken (stale), notes/new.md broken from the start (missing), notes/ok.md clean. */+async function heldSource() {+ const s = await source({ 'notes/a.md': note('Alpha'), 'notes/ok.md': note('Okay') });+ await sync(s.id, s.root);+ commit(s.root, { 'notes/a.md': BROKEN, 'notes/new.md': BROKEN });+ await sync(s.id, s.root);+ expect((await readGitSourceHolds(engine, { sourceIds: [s.id] }))[0]?.holds.map(hold => hold.path).sort()).toEqual(['notes/a.md', 'notes/new.md']);+ return s;+}++interface Call { ctx: OperationContext; notices: Notice[]; meta: Record<string, unknown> }+function call(sourceId: string, remote: boolean): Call {+ const notices: Notice[] = [], meta: Record<string, unknown> = {};+ const ctx = {+ engine, config: { engine: engine.kind, embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId,+ emitNotice: (notice: Notice) => { notices.push(notice); },+ emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },+ } as unknown as OperationContext;+ return { ctx, notices, meta };+}++/** Counts the hold-store reads a call makes (an own-property shadow, so transaction handles keep their connection). */+async function countHoldReads<T>(run: () => Promise<T>): Promise<{ value: T; reads: number }> {+ const target = engine as unknown as { executeRaw: (this: unknown, sql: string, params?: unknown[]) => Promise<unknown> };+ const inherited = Object.getPrototypeOf(engine).executeRaw as typeof target.executeRaw;+ let reads = 0;+ target.executeRaw = function (sql, params) {+ if (Array.isArray(params) && (params[0] === 'sync-hold' || params[0] === 'sync-hold-summary')) reads++;+ return inherited.call(this, sql, params);+ };+ try { return { value: await run(), reads }; }+ finally { delete (target as Partial<typeof target>).executeRaw; }+}++test('get_page carries file_held with the path for local callers and without it for remote ones; it clears once the file imports', () => eachEngine(async () => {+ const s = await heldSource();+ const local = await getPage.handler(call(s.id, false).ctx, { slug: 'notes/a' }) as Record<string, any>;+ expect(local.title).toBe('Alpha');+ expect(local.file_held).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2, path: 'notes/a.md',+ docs: 'docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation',+ fix: { actor: 'agent', argv: ['gbrain', 'repair', 'frontmatter', '--source', s.id, '--include-ambiguous'] } });+ expect(Date.parse(local.file_held.since)).not.toBeNaN();++ const remote = await getPage.handler(call(s.id, true).ctx, { slug: 'notes/a' }) as Record<string, any>;+ expect(remote.file_held).toMatchObject({ code: 'invalid_frontmatter', reason: 'needs_interpretation', since: local.file_held.since,+ fix: { actor: 'host_admin', argv: ['gbrain', 'repair', 'frontmatter', '--source', s.id] } });+ expect(remote.file_held.path).toBeUndefined();+ expect(remote.file_held.fix.user_message).toContain(`'gbrain repair frontmatter --source ${s.id}' on the brain host`);+ expect(JSON.stringify(remote.file_held)).not.toContain('notes/a.md');+ expect(JSON.stringify(remote.file_held)).not.toContain('alice-example');++ expect((await getPage.handler(call(s.id, false).ctx, { slug: 'notes/ok' }) as Record<string, unknown>).file_held).toBeUndefined();++ commit(s.root, { 'notes/a.md': note('Alpha fixed') });+ await sync(s.id, s.root);+ const fixed = await getPage.handler(call(s.id, false).ctx, { slug: 'notes/a' }) as Record<string, unknown>;+ expect(fixed.title).toBe('Alpha fixed');+ expect(fixed.file_held).toBeUndefined();+ expect(await readHeldCoverage(engine, { sourceId: s.id })).toEqual([{ source_id: s.id, missing: 1, stale: 0 }]);+}), 120_000);++test('search marks hits of held pages stale, reports held_files per source and emits the held_files notice', () => eachEngine(async () => {+ const s = await heldSource();+ const revision = (await engine.readPageSnapshot('notes/a', { sourceId: s.id }))!.revision;+ const c = call(s.id, false);+ const results = await search.handler(c.ctx, { query: 'quarterly widget roadmap' }) as Array<Record<string, any>>;+ const bySlug = Object.fromEntries(results.map(row => [row.slug, row]));+ expect(bySlug['notes/a']?.stale).toMatchObject({ last_indexed_revision: revision });+ expect(Date.parse(bySlug['notes/a']!.stale.held_since)).not.toBeNaN();+ expect(bySlug['notes/ok']?.stale).toBe(false);+ expect((c.meta.retrieval as Record<string, unknown>).held_files).toEqual([{ source_id: s.id, missing: 1, stale: 1 }]);+ const notice = c.notices.find(n => n.code === 'held_files')!;+ expect(notice).toMatchObject({ kind: 'degraded', fix: { actor: 'agent', argv: ['gbrain', 'repair', 'frontmatter', '--source', s.id],+ verify: { argv: ['gbrain', 'sources', 'status', s.id, '--json'] } } });+ expect(notice.why).toContain('1 held new file(s) have no page');+ expect(notice.why).toContain('1 page(s) whose newer file is held');+ expect(NOTICE_CODES.held_files.kind).toBe('degraded');+ expect(PER_CALL_NOTICE_CODES.has('held_files')).toBe(true);+}), 120_000);++test('a remote search payload carries counts and flags, never paths, and names the host operator command', () => eachEngine(async () => {+ const s = await heldSource();+ const c = call(s.id, true);+ const results = await search.handler(c.ctx, { query: 'quarterly widget roadmap' }) as Array<Record<string, any>>;+ expect(results.find(row => row.slug === 'notes/a')?.stale).toMatchObject({ held_since: expect.any(String) });+ const notice = c.notices.find(n => n.code === 'held_files')!;+ expect(notice.fix).toMatchObject({ actor: 'host_admin', argv: ['gbrain', 'repair', 'frontmatter', '--source', s.id] });+ expect(notice.fix!.user_message).toContain(`'gbrain repair frontmatter --source ${s.id}' on the brain host`);+ expect(notice.why).toContain('Only the brain host operator can inspect and repair held files.');+ const payload = JSON.stringify({ results, meta: c.meta, notices: c.notices });+ for (const path of ['notes/a.md', 'notes/new.md', 'notes/ok.md']) expect(payload).not.toContain(path);+ expect(payload).not.toContain(home);+ expect(payload).not.toContain('alice-example');+ expect((c.meta.retrieval as Record<string, unknown>).held_files).toEqual([{ source_id: s.id, missing: 1, stale: 1 }]);+}), 120_000);++test('a clean source adds no held_files, no notice and no stale hit, with one summary read', () => eachEngine(async () => {+ const s = await source({ 'notes/a.md': note('Alpha'), 'notes/ok.md': note('Okay') });+ await sync(s.id, s.root);+ const c = call(s.id, false);+ const { value: results, reads } = await countHoldReads(() => search.handler(c.ctx, { query: 'quarterly widget roadmap' }) as Promise<Array<Record<string, unknown>>>);+ expect(results.length).toBeGreaterThan(0);+ expect(results.every(row => row.stale === false)).toBe(true);+ expect((c.meta.retrieval as Record<string, unknown>).held_files).toBeUndefined();+ expect(c.notices.find(n => n.code === 'held_files')).toBeUndefined();+ expect(reads).toBe(1);+}), 120_000);++test('reads cost one indexed hold lookup and one summary read per request, never one per hit', () => eachEngine(async () => {+ const s = await heldSource();+ commit(s.root, Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`notes/extra-${i}.md`, note(`Extra ${i}`)])));+ await sync(s.id, s.root);+ const c = call(s.id, false);+ const { value: results, reads } = await countHoldReads(() => search.handler(c.ctx, { query: 'quarterly widget roadmap' }) as Promise<Array<Record<string, unknown>>>);+ expect(results.length).toBeGreaterThan(5);+ expect(reads).toBe(2);+ expect((await countHoldReads(() => getPage.handler(call(s.id, false).ctx, { slug: 'notes/a' }))).reads).toBe(1);++ const request = {};+ const twice = await countHoldReads(async () => [await readHeldCoverage(engine, { sourceId: s.id }, request), await readHeldCoverage(engine, { sourceId: s.id }, request)]);+ expect(twice.reads).toBe(1);+ expect(twice.value[0]).toEqual(twice.value[1]);+ const plan = await engine.transaction(async tx => {+ await tx.executeRaw('SET LOCAL enable_seqscan = off');+ return tx.executeRaw<Record<string, string>>(`EXPLAIN SELECT 1 FROM op_checkpoints h WHERE h.op='sync-hold' AND (h.completed_keys->0->>'page_id')=ANY($1::text[])`, [['1']]);+ });+ expect(plan.map(row => Object.values(row)[0]).join('\n')).toContain('op_checkpoints_sync_hold_page_idx');+}), 120_000);