Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: put_pages no longer stalls on slow fenced code (short fence parse cap, tree-sitter timeout mapped, repeated preparation deadline is terminal), accepts byte-identical repeated slugs as one write (changed repeats refused per page), and query skips the image arm on brains with no image embeddings
garrytana49fa8ee6624
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex f8fae482db..f2942aaa50 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. A write whose preparation overruns `preparationMs` is requeued once; the second overrun in the same process ends it as a terminal `preparation_deadline` failure (`failRepeatedDeadline`, `MAX_PREPARATION_DEADLINES = 2`) instead of an endless retry (test: `test/persistence-consumer-scheduling.test.ts`).- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 2a93a53b80..bc6e32856d 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,6 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.+- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`, and no LLM modality tie-break. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b15323bc37..dcf21352f4 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1679,6 +1679,14 @@ Reasons: `timeout`, `live_serve`.More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### preparation_deadline++<a id="preparation_deadline"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Preparing a write ran past its preparation budget twice, so the write ended instead of retrying; nothing was published. | A page whose preparation never fits its budget would otherwise be requeued forever and stall the batch it belongs to. | Resubmit the page with a new request_id; if it overruns again, split it into smaller pages and report it as a gbrain bug. Run: gbrain sources writer status --json | agent | `gbrain doctor --json` | 1 | no |+### preview_changed<a id="preview_changed"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 35d522e799..0ca447aed7 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -35,7 +35,7 @@ src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware tsrc/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verifysrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read-src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)+src/core/chunkers/code.ts 1592 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 1869 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); re-summed at the master c9ba7782 merge (1860 integration + 1864 master - 1856 base); +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts)src/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 optiondiff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 7bda4e454c..8af9a566ee 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -209,6 +209,8 @@ export interface CodeChunkOptions {* smallest common embedder context (e.g. nomic-embed-text, 2048).*/maxChunkTokens?: number;+ /** Parse wall-clock cap for this call (default GBRAIN_CHUNKER_TIMEOUT_MS or 30 s); on expiry the source falls back to text chunks. */+ timeoutMs?: number;}/**@@ -673,7 +675,9 @@ export function parseWithTimeout();}parser.setTimeoutMicros(timeoutMs * 1000);- const tree = parser.parse(source);+ let tree: unknown;+ // web-tree-sitter throws "Parsing failed" itself when the timeout makes the parse return null.+ try { tree = parser.parse(source); } catch (e: unknown) { if (e instanceof Error && e.message === 'Parsing failed') throw new ChunkerTimeoutError(filePath, timeoutMs); throw e; }if (tree === null || tree === undefined) {throw new ChunkerTimeoutError(filePath, timeoutMs);}@@ -757,7 +761,7 @@ async function chunkParsedLanguage(const largeThreshold = opts.largeChunkThresholdTokens ?? 1000;const chunkTarget = opts.chunkSizeTokens ?? 300;- const timeoutMs = resolveChunkerTimeoutMs();+ const timeoutMs = opts.timeoutMs ?? resolveChunkerTimeoutMs();// v0.31.2: parser + tree are always reaped via finally. Pre-fix, the// catch block returned without delete() — a leak Codex flaggeddiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d004dc6238..7e776d83e9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -242,6 +242,7 @@ export const CODES = {plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ preparation_deadline: { class: 'server', summary: "Preparing a write ran past its preparation budget twice, so the write ended instead of retrying; nothing was published.", why: "A page whose preparation never fits its budget would otherwise be requeued forever and stall the batch it belongs to.", suggestion: 'Resubmit the page with a new request_id; if it overruns again, split it into smaller pages and report it as a gbrain bug.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows the writer, its queue and the last preparation error before anything is resubmitted.', requires_exclusive: false } },preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.tsindex 4d967c339d..98af19fabd 100644--- a/src/core/markdown-chunks.ts+++ b/src/core/markdown-chunks.ts@@ -47,6 +47,15 @@ function fenceTagToPseudoPath(lang: string | undefined): string | null {return FENCE_TAG_TO_PSEUDO_PATH[lang.toLowerCase().trim()] ?? null;}+const positiveEnv = (name: string, fallback: number) => {+ const n = Number(process.env[name]);+ return Number.isFinite(n) && n > 0 ? n : fallback;+};+/** Per-fence tree-sitter cap during a page write (GBRAIN_FENCE_PARSE_TIMEOUT_MS, default 2 s). */+export const fenceParseTimeoutMs = () => positiveEnv('GBRAIN_FENCE_PARSE_TIMEOUT_MS', 2_000);+/** All fences of one page together (GBRAIN_FENCE_PARSE_BUDGET_MS, default 5 s), well inside the 30 s preparation budget. */+export const fenceParseBudgetMs = () => positiveEnv('GBRAIN_FENCE_PARSE_BUDGET_MS', 5_000);+/** Sanitize the complete body before scanning any fenced code. */async function extractFencedChunks(markdown: string,@@ -70,6 +79,7 @@ async function extractFencedChunks(}let indexOffset = 0;+ const started = performance.now();for (const fence of fences) {const text = fence.text.trim();if (!text) continue;@@ -77,8 +87,17 @@ async function extractFencedChunks(if (!pseudoPath) continue; // unknown or missing lang tag → prose fallbackconst lang = detectCodeLanguage(pseudoPath);if (!lang) continue;+ // A fence is part of a page write, which has its own preparation budget:+ // each fence parses under a short cap (falling back to text chunks), and+ // once the page's fence budget is spent the remaining fences stay prose+ // (their text is still in the page's body chunks).+ const remaining = fenceParseBudgetMs() - (performance.now() - started);+ if (remaining <= 0) {+ console.warn(`[gbrain] fence parse budget (${fenceParseBudgetMs()}ms/page) spent; remaining fenced code stays in the prose chunks.`);+ break;+ }try {- const chunks = await chunkCodeText(text, pseudoPath);+ const chunks = await chunkCodeText(text, pseudoPath, { timeoutMs: Math.max(1, Math.min(fenceParseTimeoutMs(), remaining)) });for (const c of chunks) {out.push({chunk_index: startChunkIndex + indexOffset++,diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 01d7e07bca..877b0c40bf 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -18,6 +18,7 @@ import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { faultPoint } from './fault-points.ts';+import { OperationError } from '../ops/contract.ts';import { releaseAbandonedClaims } from './effect-journal.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };@@ -55,6 +56,9 @@ export async function runResidentProjectionInvocation(engine: BrainEngine, hostIconst PARKED_WORKER: Promise<void> = Promise.resolve();export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;+/** Preparation deadlines a write may hit before it fails terminally (the first requeues it). */+const MAX_PREPARATION_DEADLINES = 2;+export class PersistenceConsumer {private stopping = false;private timer: ReturnType<typeof setTimeout> | undefined;@@ -91,6 +95,8 @@ export class PersistenceConsumer {private lastLog: { key: string; at: number } | undefined;private lastPhaseError: string | undefined;private preparationAttempts = 0;+ /** Preparation deadlines per request in this process; the second ends the write instead of requeueing it. */+ private deadlineStrikes = new Map<string, number>();private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();private executing = new Set<string>();private abandonedReleased = false;@@ -497,6 +503,7 @@ export class PersistenceConsumer {this.log('preparation', 'deadline_exceeded');}if (!claimLive || this.stopping || abort.signal.aborted) {+ if (claimLive && !this.stopping && observation.deadline_exceeded) { const failed = await this.failRepeatedDeadline(row, budget); if (failed) return this.settled(failed); }await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping'); return false;}this.preparing.delete(row.id);@@ -511,6 +518,7 @@ export class PersistenceConsumer {} catch (error) {if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {+ if (claimLive && !this.stopping && observation.deadline_exceeded) { const failed = await this.failRepeatedDeadline(row, budget); if (failed) return this.settled(failed); }await releaseUnpublishedClaim(this.engine, row, observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping');return false;}@@ -522,10 +530,30 @@ export class PersistenceConsumer {}throw error;} finally {+ if (!observation.deadline_exceeded) this.deadlineStrikes.delete(row.id);closed = true; clearInterval(interval); if (timeout) clearTimeout(timeout);this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id); await renewing;}}+ /**+ * A write whose preparation overruns its budget is requeued once; the second+ * overrun ends it as a terminal `preparation_deadline` failure with a fix,+ * so a page that can never prepare in time does not retry forever.+ */+ private async failRepeatedDeadline(row: WriteRequest, budgetMs: number): Promise<WriteRequest | null> {+ const strikes = (this.deadlineStrikes.get(row.id) ?? 0) + 1;+ this.deadlineStrikes.set(row.id, strikes);+ if (strikes < MAX_PREPARATION_DEADLINES) return null;+ this.deadlineStrikes.delete(row.id);+ const current = await getWriteRequestById(this.engine, row.id);+ if (!current || isTerminal(current) || current.execution_token !== row.execution_token || current.recovery) return null;+ const seconds = Math.round(budgetMs / 1000);+ const done = await finishUnpublishedFailure(this.engine, current, new OperationError('preparation_deadline',+ `Preparing this ${row.operation} for ${row.slug || 'the page'} ran past the ${seconds}s preparation budget ${strikes} times, so the write stopped instead of retrying; nothing was published. Resubmit the page with a new request_id; if it overruns again, split it into smaller pages and report it as a gbrain bug.`,+ 'Check the writer with gbrain sources writer status --json, then resubmit the page with a new request_id.'), 'preparation');+ this.log('preparation', 'preparation_deadline', done.error_message ?? undefined);+ return done;+ }/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */private async executeOrGroup(row: WriteRequest): Promise<boolean> {// #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 1dba8eb1fe..de3cf0ffeb 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -36,8 +36,8 @@ const PREPARE_CONCURRENCY = 8;const BATCH_ADMISSION_BUDGET_MS = 30_000;const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty']);interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown }-interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null }-interface BatchMarker { id: string; index: number; size: number }+interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null; repeatOf?: number }+interface BatchMarker { id: string; index: number; size: number; repeats?: number[] }const invalid = (message: string, suggestion: string) => new OperationError('invalid_params', message, suggestion);@@ -46,7 +46,6 @@ function parsePages(value: unknown): BatchPage[] {throw invalid(`pages must be an array of 1 to ${PAGE_BATCH_MAX_PAGES} pages; nothing was written.`,`Send at most ${PAGE_BATCH_MAX_PAGES} pages per put_pages call, each in its own call with its own request_id. To check an earlier batch, call put_pages with only its request_id.`);}- const seen = new Set<string>();let bytes = 0;const pages = value.map((page, index) => {if (!page || typeof page !== 'object' || Array.isArray(page)) throw invalid(`pages[${index}] must be an object {slug, content}; nothing was written.`, 'Pass each page as {slug, content} with optional expected_revision and allow_empty.');@@ -55,9 +54,6 @@ function parsePages(value: unknown): BatchPage[] {if (extra.length) throw invalid(`pages[${index}] has unsupported fields (${extra.join(', ')}); nothing was written.`, 'Each page accepts only slug, content, expected_revision and allow_empty; put frontmatter inside content.');if (typeof record.slug !== 'string' || !record.slug) throw invalid(`pages[${index}].slug must be a non-empty string; nothing was written.`, 'Give every page its slug, for example "notes/topic-name".');if (typeof record.content !== 'string') throw invalid(`pages[${index}].content must be a string; nothing was written.`, 'Pass the complete markdown page, frontmatter included, as content.');- const key = record.slug.toLowerCase();- if (seen.has(key)) throw invalid(`Slug ${record.slug} appears twice in this batch; nothing was written.`, 'Merge the two pages into one, or send the second one in a later put_pages call.');- seen.add(key);bytes += Buffer.byteLength(record.content);return record as unknown as BatchPage;});@@ -68,6 +64,34 @@ function parsePages(value: unknown): BatchPage[] {return pages;}+interface Repeats { repeatOf: (number | undefined)[]; refusals: Map<number, OperationError> }++/**+ * Pages of one batch that share a slug (case-insensitive). A byte-identical+ * repeat (same content, expected_revision and allow_empty) is one write: it+ * points at its first occurrence. When the repeats differ, every page with+ * that slug is refused on its own, naming the other indexes; the rest of the+ * batch is written.+ */+function findRepeats(pages: BatchPage[]): Repeats {+ const bySlug = new Map<string, number[]>();+ pages.forEach((page, index) => bySlug.set(page.slug.toLowerCase(), [...(bySlug.get(page.slug.toLowerCase()) ?? []), index]));+ const repeatOf: (number | undefined)[] = new Array(pages.length);+ const refusals = new Map<number, OperationError>();+ const same = (a: BatchPage, b: BatchPage) => a.slug === b.slug && a.content === b.content && a.expected_revision === b.expected_revision && a.allow_empty === b.allow_empty;+ for (const indexes of bySlug.values()) {+ if (indexes.length < 2) continue;+ const first = pages[indexes[0]!]!;+ if (indexes.every(index => same(pages[index]!, first))) { for (const index of indexes.slice(1)) repeatOf[index] = indexes[0]; continue; }+ for (const index of indexes) {+ const others = indexes.filter(other => other !== index).map(other => `pages[${other}]`).join(', ');+ refusals.set(index, invalid(`Slug ${pages[index]!.slug} appears at pages[${index}] and ${others} with different content or options; none of them was written. The other pages of this batch were.`,+ `Keep one version of ${pages[index]!.slug}: send it alone in a new put_pages call with a new request_id. Identical repeats of a page are written once and need no change.`));+ }+ }+ return { repeatOf, refusals };+}+function markerOf(row: WriteRequest): BatchMarker | null {const marker = row.intent?.page_batch as Partial<BatchMarker> | undefined;return marker && typeof marker.index === 'number' && typeof marker.size === 'number' ? marker as BatchMarker : null;@@ -82,7 +106,7 @@ async function readBatch(ctx: OperationContext, batchId: string): Promise<WriteR}function pageEntry(result: PageResult): Record<string, unknown> {- const base = { index: result.index, slug: result.slug };+ const base = { index: result.index, slug: result.slug, ...(result.repeatOf !== undefined ? { repeat_of: result.repeatOf } : {}) };if (result.refusal) return { ...base, state: 'refused', error: result.refusal.toJSON() };if (!result.row) return { ...base, state: 'not_admitted' };const row = result.row;@@ -106,7 +130,7 @@ function pageEntry(result: PageResult): Record<string, unknown> {* after its last page settles; the receipt reports their combined state.*/async function batchLinks(ctx: OperationContext, sourceId: string, results: PageResult[]): Promise<Record<string, unknown>> {- const rows = results.flatMap(result => result.row ? [result.row] : []);+ const rows = [...new Map(results.flatMap(result => result.row ? [[result.row.id, result.row] as const] : [])).values()];const committed = rows.filter(row => row.state === 'committed').map(row => row.id);if (committed.length > 1 && rows.every(isTerminal)) await queueLinksReconcile(ctx.engine, { sourceId, requestIds: committed });const effects = committed.length ? await ctx.engine.executeRaw<{ state: string; outcome: Record<string, unknown> | null }>(@@ -158,31 +182,33 @@ async function admitBatch(ctx: OperationContext, batchId: string, admissions: Wr}), BATCH_ADMISSION_BUDGET_MS);}-async function prepareAll(caller: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {+async function prepareAll(caller: OperationContext, batchId: string, sourceId: string, pages: BatchPage[], repeats: Repeats) {// #6007 (workstream A): one writer verification and one shared-read snapshot per batch (page-mutations.ts withBatchAdmission).- return withBatchAdmission(caller, (own, shared) => preparePages(own, shared, batchId, sourceId, pages));+ return withBatchAdmission(caller, (own, shared) => preparePages(own, shared, batchId, sourceId, pages, repeats));}-async function preparePages(own: OperationContext, shared: OperationContext, batchId: string, sourceId: string, pages: BatchPage[]) {- const prepared: (Awaited<ReturnType<typeof preparePageAdmission>> | OperationError)[] = new Array(pages.length);+async function preparePages(own: OperationContext, shared: OperationContext, batchId: string, sourceId: string, pages: BatchPage[], repeats: Repeats) {+ const prepared: (Awaited<ReturnType<typeof preparePageAdmission>> | OperationError | undefined)[] = new Array(pages.length);+ const todo = pages.flatMap((_, index) => repeats.repeatOf[index] === undefined && !repeats.refusals.has(index) ? [index] : []);const prepareOne = async (index: number) => {- const ctx = index === 0 ? own : shared;+ const ctx = index === todo[0] ? own : shared;const page = pages[index]!;+ const copies = repeats.repeatOf.flatMap((first, copy) => first === index ? [copy] : []);const params: Record<string, unknown> = { slug: page.slug, content: page.content, source_id: sourceId };if (page.expected_revision !== undefined) params.expected_revision = page.expected_revision;if (page.allow_empty !== undefined) params.allow_empty = page.allow_empty;try {prepared[index] = await preparePageAdmission(ctx, { operation: 'put_page', params,- batch: { id: batchId, index, size: pages.length, requestId: pageBatchChildRequestId(batchId, index) } });+ batch: { id: batchId, index, size: pages.length, requestId: pageBatchChildRequestId(batchId, index), ...(copies.length ? { repeats: copies } : {}) } });} catch (error) {if (!(error instanceof OperationError)) throw error;prepared[index] = error;}};// The first page may bind the source's worktree; the rest only read.- await prepareOne(0);+ if (todo.length) await prepareOne(todo[0]!);let next = 1;- await Promise.all(Array.from({ length: Math.min(PREPARE_CONCURRENCY, pages.length - 1) }, async () => {- while (next < pages.length) await prepareOne(next++);+ await Promise.all(Array.from({ length: Math.min(PREPARE_CONCURRENCY, todo.length - 1) }, async () => {+ while (next < todo.length) await prepareOne(todo[next++]!);}));return prepared;}@@ -211,6 +237,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<striconst row = byIndex.get(index);return { index, slug: row?.slug ?? '', ...(row ? { row } : {}) };});+ for (const row of settled) for (const copy of markerOf(row)!.repeats ?? []) results[copy] = { index: copy, slug: row.slug, row, repeatOf: markerOf(row)!.index };return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results));}const pages = parsePages(params.pages);@@ -220,11 +247,13 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<strithrow opError('idempotency_conflict', `Batch ${batchId} was first submitted with ${markerOf(resized)!.size} pages; this call has ${pages.length}. Nothing new was admitted.`,`To check the original batch, call put_pages with only request_id ${batchId}. To write a different set of pages, use a new request_id.`);}- const prepared = await prepareAll(ctx, batchId, sourceId, pages);+ const repeats = findRepeats(pages);+ const prepared = await prepareAll(ctx, batchId, sourceId, pages, repeats);// A grant that may not write here refuses every page alike: answer the call with that one error.- const first = prepared[0];+ const attempted = prepared.filter(entry => entry !== undefined);+ const first = attempted[0];if (first instanceof OperationError && first.code === 'permission_denied'- && prepared.every(entry => entry instanceof OperationError && entry.code === first.code && entry.message === first.message)) throw first;+ && attempted.every(entry => entry instanceof OperationError && entry.code === first.code && entry.message === first.message)) throw first;const conflicts = prepared.flatMap((entry, index) => entry instanceof OperationError && entry.code === 'idempotency_conflict' ? [pages[index]!.slug] : []);if (conflicts.length) {throw opError('idempotency_conflict', `Batch ${batchId} was already accepted with different content for ${conflicts.join(', ')}. Nothing new was admitted.`,@@ -234,6 +263,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<striconst admissions: { index: number; admission: WriteAdmission }[] = [];const rows: WriteRequest[] = [];prepared.forEach((entry, index) => {+ if (entry === undefined) return;if (entry instanceof OperationError) results[index]!.refusal = entry;else if (entry.prior) results[index]!.row = entry.prior;else { admissions.push({ index, admission: entry.admission }); results[index]!.typeWarning = entry.typeWarning; }@@ -251,9 +281,15 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<stri}admissions.forEach((entry, position) => { results[entry.index]!.row = admitted[position]!; });}+ for (const [index, refusal] of repeats.refusals) results[index]!.refusal = refusal;const journaled = results.filter(result => result.row);const settled = await waitForWrites(ctx.engine, journaled.map(result => result.row!), ctx.config, remaining());journaled.forEach((result, position) => { result.row = settled[position]!; });+ repeats.repeatOf.forEach((firstIndex, index) => {+ if (firstIndex === undefined) return;+ const original = results[firstIndex]!;+ results[index] = { ...original, index, repeatOf: firstIndex };+ });return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results));}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 140958c213..8e9c0cebc8 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -137,7 +137,7 @@ function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<const OWNER_FILE_INTENTS: ReadonlySet<string> = new Set(['managed_file_import', 'managed_file_repair']);/** #6007: a `put_pages` child: its batch, its position and the batch size are part of its identity. */-export interface PageBatchMember { id: string; index: number; size: number; requestId: string }+export interface PageBatchMember { id: string; index: number; size: number; requestId: string; repeats?: number[] }export async function submitPageMutation(ctx: OperationContext,input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true }): Promise<Record<string, unknown>> {@@ -171,7 +171,7 @@ export async function preparePageAdmission(ctx: OperationContext,}const { page_batch: _forged, ...params } = input.params;const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };- if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size };+ if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size, ...(input.batch.repeats?.length ? { repeats: input.batch.repeats } : {}) };const requestId = input.batch ? input.batch.requestId : typeof p.request_id === 'string' ? p.request_id : randomUUID();const sourceId = pageMutationSource(ctx, p, input.operation);await initializeLocalPersistence(ctx);diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex aa7c89d416..a181d9604a 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -16,7 +16,7 @@ export const WRITE_ERROR_CODES = ['unsupported_mutation_protocol', 'writer_upgrade_required', 'writer_not_quiesced','skill_bundle_required', 'take_row_collision', 'invalid_source_uri', 'writer_admin_locked','connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout',- 'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',+ 'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline', 'preparation_deadline',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex 25fba1a107..706ca87193 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -3,6 +3,7 @@* Each stage reads the resolved request (HybridRequest, request.ts) and* writes its per-request accumulators only as `req.<field>`.*/+import { brainHasImageVectors } from '../image-vector-presence.ts';import type { ModalityMode } from '../query-intent.ts';import type { ExactLookupOpts } from '../exact-lookup.ts';import type { HybridRequest } from './request.ts';@@ -49,6 +50,10 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {// We classify modality early (it's also computed after for the modality// branch). The classification is pure regex via classifyQuery; running it// here is cheap.+ // An inferred image/both modality on a brain with no image embeddings is+ // text: the image arm has nothing to search and would only fail open (and+ // 'image' would drop the keyword arm). Later stages read the same suggestion.+ if (!(opts?.crossModal && opts.crossModal !== 'auto') && (suggestions.suggestedModality ?? 'text') !== 'text' && !await brainHasImageVectors(engine)) suggestions.suggestedModality = 'text';const earlyModality = (opts?.crossModal && opts.crossModal !== 'auto')? opts.crossModal: (suggestions.suggestedModality ?? 'text');@@ -198,6 +203,8 @@ export async function resolveModalityAndQueries(req: HybridRequest) {const explicitModality =opts?.crossModal && opts.crossModal !== 'auto' ? opts.crossModal : undefined;let regexModality = explicitModality ?? suggestions.suggestedModality ?? 'text';+ // A text-only brain has no image column to search, so the LLM tie-break toward one is skipped.+ const imageArmPossible = explicitModality !== undefined || await brainHasImageVectors(req.engine);// LLM tie-break fires ONLY when:// - no explicit per-call override// - regex returned 'text' (not confident image/both)@@ -206,6 +213,7 @@ export async function resolveModalityAndQueries(req: HybridRequest) {if (explicitModality === undefined &®exModality === 'text' &&+ imageArmPossible &&resolvedMode.cross_modal_llm_intent &&isAmbiguousModalityQuery(query)) {diff --git a/src/core/search/image-vector-presence.ts b/src/core/search/image-vector-presence.tsnew file mode 100644index 0000000000..95bdc38f3d--- /dev/null+++ b/src/core/search/image-vector-presence.ts@@ -0,0 +1,31 @@+/**+ * Whether a brain holds any image embeddings (`content_chunks.embedding_image`).+ * The cross-modal image arm can only return rows from that column, so a+ * text-only brain skips it: a question that mentions photos neither pays for+ * a multimodal embed nor reports a failed vector arm while the text arm+ * answers. One EXISTS probe per engine, cached for a minute; a probe error+ * reads as "has images" so behavior falls back to the pre-probe path.+ */+import type { BrainEngine } from '../engine.ts';++const TTL_MS = 60_000;+const cache = new WeakMap<object, { at: number; value: boolean }>();++export async function brainHasImageVectors(engine: Pick<BrainEngine, 'executeRaw'>, now = Date.now()): Promise<boolean> {+ const hit = cache.get(engine);+ if (hit && now - hit.at < TTL_MS) return hit.value;+ let value = true;+ try {+ const [row] = await engine.executeRaw<{ present: boolean }>('SELECT EXISTS (SELECT 1 FROM content_chunks WHERE embedding_image IS NOT NULL) AS present');+ value = row?.present === true || (row?.present as unknown) === 't';+ } catch {+ value = true;+ }+ cache.set(engine, { at: now, value });+ return value;+}++/** Test seam: forget the cached answer for an engine (after writing image chunks). */+export function forgetImageVectorPresence(engine: object): void {+ cache.delete(engine);+}diff --git a/test/cross-modal-hybrid-integration.serial.test.ts b/test/cross-modal-hybrid-integration.serial.test.tsindex 8f31d2e36d..6efaede2d6 100644--- a/test/cross-modal-hybrid-integration.serial.test.ts+++ b/test/cross-modal-hybrid-integration.serial.test.ts@@ -5,6 +5,7 @@// correct embeddingColumn.import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { forgetImageVectorPresence } from '../src/core/search/image-vector-presence.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import {@@ -33,6 +34,7 @@ afterAll(async () => {beforeEach(async () => {await resetPgliteState(engine);+ forgetImageVectorPresence(engine);fetchHandler = null;fetchUrlsSeen = [];fetchBodiesSeen = [];@@ -58,6 +60,15 @@ afterEach(() => {resetGateway();});+/** One image chunk, so the brain counts as holding image embeddings for auto routing. */+async function seedImageChunk() {+ await engine.putPage('media/hackathon-photo', { type: 'note', title: 'Hackathon photo', compiled_truth: 'A hackathon photo.', timeline: '' });+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'media/hackathon-photo'");+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality, embedding_image)+ VALUES ($1, 1, 'hackathon photo', 'image_asset', 'image', $2::vector)`, [page!.id, `[${Array(1024).fill(0.1).join(',')}]`]);+ forgetImageVectorPresence(engine);+}+function configureBoth() {// Gateway needs BOTH text and multimodal models configured. Use a single// openai recipe stub for text — we won't hit it for image-only queries.@@ -166,11 +177,20 @@ describe('hybridSearch cross-modal routing (Phase 1 integration)', () => {}), { status: 200 });};+ await seedImageChunk();await hybridSearch(engine, 'show me photos from the hackathon', { limit: 5 });// Auto-detection should have fired image routing.expect(fetchUrlsSeen.some(u => u.includes('multimodalembeddings'))).toBe(true);});+ test('on a brain with no image embeddings, auto-detection stays on text and never calls the multimodal endpoint', async () => {+ configureBoth();+ let meta: { degraded?: Array<{ stage?: string } | string> } | undefined;+ await hybridSearch(engine, 'show me photos from the hackathon', { limit: 5, onMeta: m => { meta = m as typeof meta; } });+ expect(fetchUrlsSeen.some(u => u.includes('multimodalembeddings'))).toBe(false);+ expect((meta?.degraded ?? []).map(d => typeof d === 'string' ? d : d.stage)).not.toContain('vector_arm_failed');+ });+test("'both' mode hits BOTH endpoints in parallel", async () => {configureBoth();let textCalled = 0;diff --git a/test/markdown-fence-parse-budget.test.ts b/test/markdown-fence-parse-budget.test.tsnew file mode 100644index 0000000000..c759cc034f--- /dev/null+++ b/test/markdown-fence-parse-budget.test.ts@@ -0,0 +1,65 @@+/**+ * Fenced code in a page write parses under a short cap. A fence whose+ * tree-sitter parse runs long (a pathological Lua block in a chat history)+ * falls back to text chunks instead of eating the 30 s preparation budget,+ * and once a page's fence budget is spent the remaining fences stay in the+ * prose chunks. web-tree-sitter reports a timed-out parse as "Parsing failed";+ * that reads as a timeout, not as the language being unavailable.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { ChunkerTimeoutError, parseWithTimeout } from '../src/core/chunkers/code.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const SLOW_LUA = 'if a then\n'.repeat(3000) + 'end\n'.repeat(3000);+const body = (fences: string[]) => `A chat about scripting.\n\n${fences.map(f => '```lua\n' + f + '```\n').join('\nAnd another one:\n\n')}\nThanks!\n`;++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+beforeEach(async () => { await disposePersistenceConsumer(engine); await resetPgliteState(engine); });++describe('fenced code parse budget', () => {+ test('a "Parsing failed" throw from the parser is a timeout', () => {+ const parser = { setTimeoutMicros() {}, parse() { throw new Error('Parsing failed'); } };+ expect(() => parseWithTimeout(parser, 'x', 5, 'fence.lua')).toThrow(ChunkerTimeoutError);+ const broken = { setTimeoutMicros() {}, parse() { throw new Error('something else'); } };+ expect(() => parseWithTimeout(broken, 'x', 5, 'fence.lua')).toThrow('something else');+ });++ test('a fence that overruns its cap falls back to text chunks quickly', async () => withEnv({ GBRAIN_FENCE_PARSE_TIMEOUT_MS: '1' }, async () => {+ const started = performance.now();+ const chunks = await prepareMarkdownChunks({ compiled_truth: body([SLOW_LUA]) });+ expect(performance.now() - started).toBeLessThan(3_000);+ expect(chunks.some(c => c.chunk_source === 'compiled_truth')).toBe(true);+ const fenced = chunks.filter(c => c.chunk_source === 'fenced_code');+ expect(fenced.length).toBeGreaterThan(0);+ expect(fenced.every(c => !c.symbol_name)).toBe(true);+ }));++ test('once the page fence budget is spent, later fences stay in the prose chunks', async () => withEnv({ GBRAIN_FENCE_PARSE_TIMEOUT_MS: '1', GBRAIN_FENCE_PARSE_BUDGET_MS: '1' }, async () => {+ const chunks = await prepareMarkdownChunks({ compiled_truth: body([SLOW_LUA, 'print("second")\n', 'print("third")\n']) });+ expect(chunks.filter(c => c.chunk_source === 'fenced_code' && c.chunk_text.includes('third'))).toHaveLength(0);+ expect(chunks.some(c => c.chunk_source === 'compiled_truth' && c.chunk_text.includes('third'))).toBe(true);+ }));++ test('put_pages lands a page whose Lua fence parses slowly', async () => withEnv({ GBRAIN_FENCE_PARSE_TIMEOUT_MS: '1' }, async () => {+ const ctx = { engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: true, sourceId: 'default' } as unknown as OperationContext;+ const putPages = operations.find(op => op.name === 'put_pages')!;+ const result = await putPages.handler(ctx, { request_id: randomUUID(), pages: [+ { slug: 'chat/lua-session', content: `---\ntype: note\ntitle: Lua session\n---\n\n${body([SLOW_LUA])}` },+ { slug: 'chat/plain-session', content: '---\ntype: note\ntitle: Plain\n---\n\nNo code here.\n' },+ ] }) as { state: string; counts: { committed: number } };+ expect(result).toMatchObject({ state: 'committed', counts: { committed: 2 } });+ expect(await engine.readPageSnapshot('chat/lua-session', { sourceId: 'default' })).not.toBeNull();+ }), 30_000);+});diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.tsindex 96a1de7968..8ef75b3dbd 100644--- a/test/persistence-consumer-scheduling.test.ts+++ b/test/persistence-consumer-scheduling.test.ts@@ -232,6 +232,32 @@ for (const cooperates of [true, false]) test(`preparation deadline retains track}}), 5000);+test('a write whose preparation overruns its deadline twice ends as a terminal preparation_deadline failure, not an endless retry', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'deadline-twice', 'never prepares in time'));+ let attempts = 0;+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, _current, _c, signal?: AbortSignal) => {+ attempts++;+ await new Promise<void>((_, reject) => signal?.addEventListener('abort', () => reject(signal.reason), { once: true }));+ throw new Error('unreachable');+ }, { hostId: config.hostId, pollMs: 20, preparationMs: 40 });+ try {+ consumer.start();+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'failed');+ const done = (await getWriteRequestById(engine, row.id))!;+ expect(attempts).toBe(2);+ expect(done.error_code).toBe('preparation_deadline');+ expect(done.error_message).toContain('preparation budget 2 times');+ expect(done.error_message).toContain('new request_id');+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();+ await Bun.sleep(100);+ expect(attempts).toBe(2);+ await assertConservation(engine);+ } finally {+ await consumer.stop();+ }+}), 5000);+test('an edit_page preparation shares the preparation deadline (#5616)', async () => withEnv(env, async () => {const sources = await fixtures(engine, config);const row = await admitWrite(engine, admission(config, sources[0], 'edit-page-deadline', 'edited body', 0, { operation: 'edit_page' }));diff --git a/test/put-pages-batch.test.ts b/test/put-pages-batch.test.tsindex 5e98599e9d..29aa28b0f2 100644--- a/test/put-pages-batch.test.ts+++ b/test/put-pages-batch.test.ts@@ -78,12 +78,10 @@ describe('put_pages', () => {expect(await engine.readPageSnapshot('notes/ok', { sourceId: 'default' })).not.toBeNull();});- test('caps, duplicates and a missing request_id refuse before anything is written', async () => {+ test('caps and a missing request_id refuse before anything is written', async () => {const count = await requestCount();const tooMany = Array.from({ length: PAGE_BATCH_MAX_PAGES + 1 }, (_, i) => page(`notes/m${i}`));await expect(putPages.handler(ctx(), { request_id: randomUUID(), pages: tooMany })).rejects.toMatchObject({ code: 'invalid_params' });- await expect(putPages.handler(ctx(), { request_id: randomUUID(), pages: [page('notes/d'), page('Notes/D')] }))- .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('twice') });await expect(putPages.handler(ctx(), { request_id: randomUUID(), pages: [page('notes/huge', 'x'.repeat(9 * 1024 * 1024))] })).rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('bytes') });await expect(putPages.handler(ctx(), { request_id: randomUUID(), pages: [{ ...page('notes/k'), kind: 'managed_file_import' }] }))@@ -93,6 +91,34 @@ describe('put_pages', () => {expect(await requestCount()).toBe(count);});+ test('a byte-identical repeat of a slug is one write; status and replay report it as a repeat', async () => {+ const batch = randomUUID();+ const pages = [page('notes/same', 'One session.'), page('notes/other'), page('notes/same', 'One session.')];+ const before = await requestCount();+ const result = await putPages.handler(ctx(), { request_id: batch, pages }) as any;+ expect(result).toMatchObject({ state: 'committed', terminal: true, counts: { total: 3, committed: 3, failed: 0 }, next: { action: 'done' } });+ expect(result.pages[2]).toMatchObject({ index: 2, slug: 'notes/same', state: 'committed', repeat_of: 0, request_id: result.pages[0].request_id, revision: result.pages[0].revision });+ expect(result.pages[0].repeat_of).toBeUndefined();+ expect(await requestCount()).toBe(before + 2);+ const status = await putPages.handler(ctx(), { request_id: batch }) as any;+ expect(status.pages.map((p: any) => [p.index, p.slug, p.state, p.repeat_of])).toEqual([[0, 'notes/same', 'committed', undefined], [1, 'notes/other', 'committed', undefined], [2, 'notes/same', 'committed', 0]]);+ await putPages.handler(ctx(), { request_id: batch, pages, wait_ms: 1000 });+ expect(await requestCount()).toBe(before + 2);+ });++ test('repeats of a slug that differ are each refused with their own error; the rest of the batch is written', async () => {+ const result = await putPages.handler(ctx(), { request_id: randomUUID(), pages: [page('notes/x', 'First.'), page('notes/y'), page('notes/x', 'Second.'), page('Notes/X', 'First.')] }) as any;+ expect(result).toMatchObject({ state: 'partial', terminal: true, counts: { total: 4, committed: 1, failed: 3 }, next: { action: 'fix_pages' } });+ expect(result.pages[1]).toMatchObject({ slug: 'notes/y', state: 'committed' });+ for (const index of [0, 2, 3]) {+ expect(result.pages[index]).toMatchObject({ state: 'refused', error: { code: 'invalid_params' } });+ expect(result.pages[index].error.message).toContain(`pages[${index}]`);+ }+ expect(result.pages[0].error.message).toContain('pages[2], pages[3]');+ expect(await engine.readPageSnapshot('notes/x', { sourceId: 'default' })).toBeNull();+ expect(await engine.readPageSnapshot('notes/y', { sourceId: 'default' })).not.toBeNull();+ });+test('capacity is reserved for the whole batch or none of it', async () => {await engine.setConfig(journalLimitKey('principalOutstanding'), '2');try {diff --git a/test/search-image-arm-text-only.test.ts b/test/search-image-arm-text-only.test.tsnew file mode 100644index 0000000000..c7d9ea1560--- /dev/null+++ b/test/search-image-arm-text-only.test.ts@@ -0,0 +1,56 @@+/**+ * The cross-modal image arm on a text-only brain: a question that mentions+ * photos infers image modality, but a brain with no `embedding_image` rows+ * has nothing for that arm to search. It is skipped, so no multimodal embed+ * is attempted and no failed vector arm is reported while the text arm+ * answers. A brain that holds image vectors still tries the arm.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { hybridSearch } from '../src/core/search/hybrid.ts';+import type { HybridSearchMeta } from '../src/core/types.ts';+import { brainHasImageVectors, forgetImageVectorPresence } from '../src/core/search/image-vector-presence.ts';+import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';++let engine: PGLiteEngine;+let sourceId: string;+const Q = 'show me the photos from the beach trip';+const embed = (text: string) => { const v = new Float32Array(1024); for (let i = 0; i < text.length; i++) v[(text.charCodeAt(i) * 31 + i) % 1024]! += 1; return v; };++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ sourceId = await newSource(engine);+ await putPage(engine, sourceId, 'notes/beach-trip', page('note', 'Beach trip', 'We took photos at the beach trip in June and shared them with the family.'));+}, 120_000);++afterAll(async () => { await engine?.disconnect(); }, 60_000);++async function search(): Promise<{ slugs: string[]; meta: HybridSearchMeta | null }> {+ let meta: HybridSearchMeta | null = null;+ const rows = await hybridSearch(engine, Q, { sourceId, limit: 5, queryEmbedFn: embed, onMeta: m => { meta = m; } });+ return { slugs: rows.map(r => r.slug), meta };+}+const stages = (meta: HybridSearchMeta | null) => ((meta as { degraded?: Array<{ stage?: string } | string> } | null)?.degraded ?? []).map(d => typeof d === 'string' ? d : d.stage);++describe('cross-modal image arm', () => {+ test('a text-only brain skips it: the text arm answers and no vector arm is reported failed', async () => {+ forgetImageVectorPresence(engine);+ expect(await brainHasImageVectors(engine)).toBe(false);+ const { slugs, meta } = await search();+ expect(slugs).toContain('notes/beach-trip');+ expect(stages(meta)).not.toContain('vector_arm_failed');+ });++ test('a brain with image vectors still runs the image arm (here it fails open: no multimodal provider is configured)', async () => {+ const [chunk] = await engine.executeRaw<{ id: number }>('SELECT cc.id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 LIMIT 1', ['notes/beach-trip']);+ await engine.executeRaw(`UPDATE content_chunks SET embedding_image = $2::vector WHERE id = $1`, [chunk!.id, `[${Array.from(embed('beach'), x => x || 0).join(',')}]`]);+ forgetImageVectorPresence(engine);+ expect(await brainHasImageVectors(engine)).toBe(true);+ const { meta } = await search();+ expect(stages(meta)).toContain('vector_arm_failed');+ await engine.executeRaw('UPDATE content_chunks SET embedding_image = NULL WHERE id = $1', [chunk!.id]);+ forgetImageVectorPresence(engine);+ });+});