Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): frontmatter where filter on search, query and list_pages, plus a filter hint (#7159)

garrytan1b229ad36ed0
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index b1e9987d88..435af4b03c 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -33,6 +33,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.
- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
+- `src/core/search/frontmatter-where.ts` + `src/core/ops/where-param.ts` — the `where` frontmatter equality filter on `search`, `query` and `list_pages` (#7159; CLI `--where key=value`, repeat for AND, `key=a,b` for any-of, parsed in `cli/op-param-values.ts`). `parseFrontmatterWhere` caps keys (8, `[A-Za-z_][A-Za-z0-9_-]{0,63}`), values (32 per key, 256 chars) and rejects nested values as `invalid_params`. Each value becomes OR'd `p.frontmatter @> $n::text::jsonb` containments (scalar, one-element list, and the number/boolean a string spells), keys ANDed, so the GIN index `idx_pages_frontmatter` serves it; keys and values travel only inside bound JSON. The clause is pushed into every SQL leg (keyword, title, vector, CJK, `listPages`), a filtered call skips the hybrid cache, and `keepFrontmatterMatches` re-checks the finished rows for arms outside those legs (exact lookup, alias fan-out, facts). Visibility, source and private filters are unchanged. Tests: `test/search-frontmatter-where.test.ts`, `test/e2e/search-frontmatter-where-parity.test.ts`.
+- `src/core/search/filter-hint.ts` — the one `search_filter_hint` info notice (deduped per session) a first-page `search`/`query` gets when it looks like it wanted a filter: the query names a page type the caller can see and under 80% of the top rows are that type (`types`), names a time (`since`/`until`; `search` points at `query`), or 90% of at least 8 top rows are one type it did not name. Never changes results, never throws. Test: `test/search-frontmatter-where.test.ts`.
- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1da2fb613d..04e3186049 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,10 +20,10 @@ src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 242 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)
-src/core/pglite-engine.ts 3085 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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)
-src/core/postgres-engine.ts 3107 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); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)
+src/core/pglite-engine.ts 3087 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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +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); +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); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move)
+src/core/postgres-engine.ts 3110 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); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
-src/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)
+src/core/types.ts 2329 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +4 #7159: SearchOpts.where and PageFilters.where (interface fields; parsing in search/frontmatter-where.ts)
src/core/minions/queue.ts 2533 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 keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); 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); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
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)
@@ -40,7 +40,7 @@ src/core/config.ts 1989 ratchet +2 W5: search.page_rank_cut / page_rank_cut_fact
src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/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 716 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)
+src/core/ops/pages.ts 719 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); +3 #7159: list_pages where param, its import and the listPages pass-through (param and parsing in ops/where-param.ts)
src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +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= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)
src/commands/eval-longmemeval.ts 1544 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); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1499 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge)
diff --git a/src/cli/main.ts b/src/cli/main.ts
index b689fbfad0..e75a6cd7c9 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -49,7 +49,7 @@ import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usage
import type { Notice } from '../core/agent-output.ts';
import { opError, opOwnsSource } from '../core/ops/contract.ts';
import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
-import { opParamValue, opStructuredValue } from './op-param-values.ts';
+import { opFlagValue, opParamValue, opStructuredValue } from './op-param-values.ts';
import { SEGMENTED_STREAMED, formatGetPage, printPagedPage, remoteErrorCode, streamSegmentedGet, wantsWholePage } from './page-render.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';
import { runCliPreflight } from '../core/cli-preflight.ts';
@@ -1063,7 +1063,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
const def = op.params[key];
if (def) {
const raw = arg.slice(eq + 1);
- params[key] = def.type === 'boolean' ? raw !== 'false' : opParamValue(op, key, def, raw);
+ params[key] = def.type === 'boolean' ? raw !== 'false' : opFlagValue(op, key, def, raw, params[key]);
continue;
}
}
@@ -1110,8 +1110,8 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
// positionally, then --content clobbered it). Warn to stderr; when
// the discarded value names an existing file, point at capture --file.
const prevValue = params[key];
- params[key] = opParamValue(op, key, paramDef, args[++i]);
- if (prevValue !== undefined && prevValue !== params[key]) {
+ params[key] = opFlagValue(op, key, paramDef, args[++i], prevValue);
+ if (prevValue !== undefined && prevValue !== params[key] && !paramDef?.cliKeyValue) {
let fileHint = '';
try {
if (typeof prevValue === 'string' && prevValue && existsSync(prevValue)) {
@@ -2936,6 +2936,9 @@ const OP_HELP_EXAMPLES: Record<string, string[]> = {
'gbrain backlinks companies/acme-example --source-id business',
'gbrain backlinks companies/acme-example --all-sources --json',
],
+ search: ['gbrain search "acme-example pricing" --types company,deal --where stage=seed # --where key=value, repeat for AND; key=a,b matches any'],
+ query: ['gbrain query "what changed at acme-example" --types meeting --since 2026-01-01 --until 2026-03-31', 'gbrain query "open deals" --where stage=seed,series-a'],
+ list_pages: ['gbrain list --type deal --where stage=seed --where partner=alice-example --updated-after 2026-01-01 --sort updated_asc'],
// #6255: the receipt command's routing flags and states.
get_write_request: ['gbrain write-request --brain host -- <request_id> [--json] # queued/running: pending, read again after retry_after_ms; committed/conflict/failed/cancelled: final'],
traverse_graph: [
diff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.ts
index d22af6f71d..e5413afa98 100644
--- a/src/cli/op-param-values.ts
+++ b/src/cli/op-param-values.ts
@@ -29,18 +29,44 @@ export function opParamValue(op: Operation, key: string, def: ParamDef | undefin
return raw;
}
+/**
+ * The value for one `--flag value` token. A `cliKeyValue` object param
+ * (`--where key=value`) collects every repetition into a list that
+ * `opStructuredValue` turns into the object; every other flag is one value.
+ */
+export function opFlagValue(op: Operation, key: string, def: ParamDef | undefined, raw: string, prev: unknown): unknown {
+ if (def?.cliKeyValue) return [...(Array.isArray(prev) ? prev : []), raw];
+ return opParamValue(op, key, def, raw);
+}
+
/**
* An object/array param from its CLI text: JSON, or for a string-item array
- * a bare value or comma list (`--types company`, `--types person,company`,
- * the form the op's own errors suggest). Other values pass through.
+ * a comma list (`--types person,company`), or for a `cliKeyValue` object
+ * repeated `key=value` pairs, where `key=a,b` is a list and a repeated key
+ * merges. Other values pass through.
*/
export function opStructuredValue(key: string, def: ParamDef, value: unknown): unknown {
const flag = `--${key.replace(/_/g, '-')}`;
- if ((def.type !== 'object' && def.type !== 'array') || typeof value !== 'string') return value;
- if (def.type === 'array' && def.items?.type === 'string' && !value.trimStart().startsWith('[')) return value.split(',').map(v => v.trim()).filter(Boolean);
+ if (def.cliKeyValue && Array.isArray(value) && !(value.length === 1 && String(value[0]).trimStart().startsWith('{'))) {
+ const out: Record<string, string | string[]> = {};
+ for (const pair of value as string[]) {
+ const eq = pair.indexOf('=');
+ const name = eq > 0 ? pair.slice(0, eq).trim() : '';
+ if (!name) {
+ throw usageError(`${flag} takes key=value; got '${inertText(pair, 40)}'.`,
+ `Pass ${flag} key=value, repeated for more keys (all must match), e.g. ${flag} status=active ${flag} stage=seed,series-a.`);
+ }
+ const values = [...[out[name] ?? []].flat(), ...pair.slice(eq + 1).split(',').map(v => v.trim())];
+ out[name] = values.length === 1 ? values[0]! : values;
+ }
+ return out;
+ }
+ const text = def.cliKeyValue && Array.isArray(value) ? value[0] : value;
+ if ((def.type !== 'object' && def.type !== 'array') || typeof text !== 'string') return value;
+ if (def.type === 'array' && def.items?.type === 'string' && !text.trimStart().startsWith('[')) return text.split(',').map(v => v.trim()).filter(Boolean);
const jsonError = () => usageError(`${flag} requires a JSON ${def.type}.`, `Pass JSON, e.g. ${flag} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);
let parsed: unknown;
- try { parsed = JSON.parse(value); } catch { throw jsonError(); }
+ try { parsed = JSON.parse(text); } catch { throw jsonError(); }
if (def.type === 'array' ? !Array.isArray(parsed) : parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw jsonError();
return parsed;
}
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 3fb62400a4..412ce83a47 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -35,6 +35,7 @@ import { stagingNeedsTextSql } from '../page-body/schema.ts';
import { atomRetirementPurgeHold } from '../persistence/atom-retirement-hold.ts';
import { createPageVersion } from '../page-state/versions.ts';
import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';
+import { frontmatterWhereFragment } from '../search/frontmatter-where.ts';
import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';
import { pickCanonicalOrigin } from '../persistence/origin-guard.ts';
@@ -496,6 +497,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
const effectiveBeforeCondition = filters?.effective_before
? sqlFragment`AND p.effective_date <= ${filters.effective_before}::timestamptz`
: sqlFragment``;
+ const whereCondition = frontmatterWhereFragment(filters?.where);
// v0.29: ORDER BY threading via PAGE_SORT_SQL whitelist (no SQL injection).
const sortKey = filters?.sort && PAGE_SORT_SQL[filters.sort] ? filters.sort : 'updated_desc';
@@ -508,7 +510,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
const { rows } = await exec.run(sqlFragment`
SELECT ${columns}, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p
${tagJoin}
- WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition}${excludedSlugCondition} ${slugAfterCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
+ WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition}${excludedSlugCondition} ${slugAfterCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}${whereCondition}
ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}
`);
return rows.map(rowToPage);
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index d53a36762c..ee6c987e66 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -816,6 +816,7 @@ export const NOTICE_CODES = {
former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },
identity_siblings_capped: { kind: 'info', summary: 'More than three pages share an entity\'s title subject, so the card shows no identity siblings; the fix (for the user) lists them with `gbrain extract mentions --explain`.' },
alias_fanout: { kind: 'info', summary: 'search fanned out over an entity\'s other names and stopped at the per-call cap; the skipped names are listed and can be searched directly.' },
+ search_filter_hint: { kind: 'info', summary: 'A search or query looked like it wanted a filter it did not pass (the query names a page type or a time, or one type fills the top results); the notice names types, since/until or where and the call to repeat. Results are unchanged.' },
mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },
degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },
source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index b0aa76284b..fc8dccd40e 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -512,7 +512,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"name": "list_pages",
"idempotent": true,
"outputRedaction": "retrieval",
- "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row.",
+ "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row. Filters: type, tag, updated_after, where (frontmatter fields); sort: updated_desc, updated_asc, created_desc, slug.",
"params": {
"type": {
"type": "string",
@@ -552,6 +552,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "boolean",
"description": "Include soft-deleted pages."
},
+ "where": {
+ "type": "object",
+ "cliKeyValue": true,
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any."
+ },
"source_id": {
"type": "string",
"description": "One source, or '__all__'."
@@ -1225,7 +1230,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"name": "search",
"idempotent": true,
"outputRedaction": "retrieval",
- "description": "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.",
+ "description": "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. Filters: types, where (frontmatter fields); dates: `query`. fields: \"full\" adds diagnostics.",
"params": {
"query": {
"type": "string",
@@ -1267,6 +1272,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"description": "Page types, e.g. ['person']."
},
+ "where": {
+ "type": "object",
+ "cliKeyValue": true,
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any."
+ },
"snippet_chars": {
"type": "number",
"description": "Chars per row (0 = full)."
@@ -1344,7 +1354,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"name": "query",
"idempotent": true,
"outputRedaction": "retrieval",
- "description": "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",
+ "description": "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. Filters: types, since/until, where (frontmatter fields). fields: \"full\" adds diagnostics.",
"params": {
"query": {
"type": "string",
@@ -1374,6 +1384,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"description": "Page types, e.g. ['person']."
},
+ "where": {
+ "type": "object",
+ "cliKeyValue": true,
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any."
+ },
"snippet_chars": {
"type": "number",
"description": "Chars per row (0 = full)."
diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.ts
index a604de7fd1..9ef468dfa3 100644
--- a/src/core/operations-descriptions.ts
+++ b/src/core/operations-descriptions.ts
@@ -46,13 +46,13 @@ export const GET_RECENT_TRANSCRIPTS_DESCRIPTION =
// ──────────────────────────────────────────────────────────────────────────────
export const LIST_PAGES_DESCRIPTION =
- "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row.";
+ "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row. Filters: type, tag, updated_after, where (frontmatter fields); sort: updated_desc, updated_asc, created_desc, slug.";
export const QUERY_DESCRIPTION =
- "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.";
+ "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. Filters: types, since/until, where (frontmatter fields). fields: \"full\" adds diagnostics.";
export const SEARCH_DESCRIPTION =
- "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.";
+ "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. Filters: types, where (frontmatter fields); dates: `query`. fields: \"full\" adds diagnostics.";
/** `search`'s `match` param (Cat 40 Hard F2). */
export const SEARCH_MATCH_DESCRIPTION = 'keyword: every match, paged.';
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 32a7128481..26d36ed953 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -256,6 +256,8 @@ export interface ParamDef {
properties?: Record<string, ParamDef>;
/** Advertised on the full MCP surface only (keeps the starter tool list inside its size budget). */
fullSurfaceOnly?: boolean;
+ /** An object param the CLI takes as repeated `--flag key=value` (`key=a,b` is a list); MCP passes the object. */
+ cliKeyValue?: boolean;
}
export interface Logger {
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 741c9d2f17..f11f9ba216 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -34,6 +34,7 @@ import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descr
import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagination.ts';
import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';
import { invalidParam, readFix } from './op-fix.ts';
+import { WHERE_PARAM, whereOpParam } from './where-param.ts';
import { isDatetimeInputError } from '../utils.ts';
import { rethrowNamingRevisionSource } from './put-page-revision-source.ts';
import {
@@ -518,6 +519,7 @@ const list_pages: Operation = {
enum: [...LIST_PAGES_SORT_VALUES],
},
include_deleted: { type: 'boolean', description: 'Include soft-deleted pages.' },
+ where: WHERE_PARAM,
// #4400 — list_pages had no source-scoping param at all: unlike
// search/query it silently ignored any caller-supplied source and always
// fell back to whatever federatedSearchScope() resolved from ctx alone,
@@ -611,6 +613,7 @@ const list_pages: Operation = {
sort,
excludePrivate,
listColumnsOnly: true,
+ where: whereOpParam(ctx, 'list_pages', p.where),
...scope,
}).catch((e: unknown) => {
// #6103: an updated_after the database cannot parse is the caller's input, not a server fault.
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 0b20dfd8a3..ac7ed89741 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -36,6 +36,9 @@ import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { leanRowsKeepId, projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { buildScoreDetails } from '../search/explain-formatter.ts';
import { SearchTimings } from '../search/stage-timings.ts';
+import { keepFrontmatterMatches } from '../search/frontmatter-where.ts';
+import { WHERE_PARAM, whereOpParam } from './where-param.ts';
+import { searchFilterHint } from '../search/filter-hint.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, pagePlanHits, resolveEvidencePlan, selectLongPages, unsupportedDelivery, withLongPagePolicy, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
@@ -420,7 +423,7 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search'; entity?: ResolvedEntity } = {},
+ opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search'; entity?: ResolvedEntity; hint?: { op: 'search' | 'query'; p: Record<string, unknown> } } = {},
): Promise<Record<string, unknown>> {
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
@@ -432,7 +435,7 @@ async function buildRetrievalResponseMeta(
const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);
// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres
// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.
- const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles, sourceFreshness] = await Promise.all([
+ const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles, sourceFreshness, filterNotice] = await Promise.all([
ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),
probeProjectionReadiness(ctx.engine, { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes }),
// Facts saved about the entity the query names come first (newest first, one hop through entities they name).
@@ -441,7 +444,9 @@ async function buildRetrievalResponseMeta(
stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []),
// GBRA-133 PR 2a.5: per-source freshness from the notifier's cached coverage record (no git call).
readSourceFreshness(ctx.engine, scope),
+ opts.hint ? searchFilterHint(ctx, scope, excludePrivate, queryText, results as SearchResult[], opts.types, opts.hint) : null,
]);
+ if (filterNotice) ctx.emitNotice?.(filterNotice);
const heldBySource = new Map(heldFiles.map(h => [h.source_id, h.missing + h.stale]));
const freshness = sourceFreshness.map(f => ({ ...f, held_count: heldBySource.get(f.source_id) ?? 0 }));
// A fact the facts arm already returned as a row is not repeated beside the blocks.
@@ -657,6 +662,7 @@ const search: Operation = {
source_id: { type: 'string', description: SOURCE_ID_PARAM_DESCRIPTION },
// #3985: multi-type filter (plumbing shipped v0.33; exposed here).
types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },
+ where: WHERE_PARAM,
// #3800: subagent token economy — per-call snippet cap.
snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
return_unit: RETURN_UNIT_PARAM,
@@ -683,6 +689,7 @@ const search: Operation = {
const offset = paging.offset;
// #3985: validated multi-type filter, threaded into both branches below.
let types = normalizeTypesParam(ctx, 'search', p.types);
+ const where = whereOpParam(ctx, 'search', p.where);
// #3800: snippet cap (param > subagent config default > full text).
const snippetCap = await setup(() => resolveSnippetCap(ctx, p));
const plan = await setup(() => evidencePlanFor(ctx, p, snippetCap, 'search'));
@@ -710,7 +717,7 @@ const search: Operation = {
// hybrid `search` contract (privacy/cost: no query text to an embedding
// provider). Defaults to cheap-hybrid (D4/D15).
const keywordOnly = (await setup(() => ctx.engine.getConfig('search.mcp_keyword_only'))) === 'true';
- const readOpts = { excludePrivate, requireSafeChunks: ctx.remote !== false, ...scope };
+ const readOpts = { excludePrivate, requireSafeChunks: ctx.remote !== false, ...scope, ...(where ? { where } : {}) };
if (keywordOnly || paging.match === 'keyword') {
if (types) {
@@ -734,11 +741,11 @@ const search: Operation = {
}
const lexicalDone = Promise.withResolvers<void>();
const keywordCount = page ? null : timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, undefined, keywordOpts, lexicalDone.promise));
- const results = (page ? page.rows : dedupResults(await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts })).finally(lexicalDone.resolve))).map(r => ({ ...r }));
+ const results = await keepFrontmatterMatches(ctx.engine, (page ? page.rows : dedupResults(await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, ...keywordOpts })).finally(lexicalDone.resolve))).map(r => ({ ...r })), where);
await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt, timings);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap, timings,
- async rows => withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice }),
+ async rows => withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, hint: { op: 'search', p } }),
page ?? keywordCountMeta(await keywordCount!, offset + limit)), page !== null);
}
@@ -756,6 +763,7 @@ const search: Operation = {
requireSafeChunks: ctx.remote !== false,
takesHoldersAllowList: readHolders(ctx),
...(types ? { types } : {}),
+ ...(where ? { where } : {}),
...scope,
...(perCallMode ? { mode: perCallMode } : {}),
// #4415: agent-explicit recency + salience (same posture as `query`).
@@ -775,14 +783,14 @@ const search: Operation = {
: { results: primary };
let results = fanned.results.map(r => ({ ...r }));
await emitFanoutNotices(ctx, fanned.fanout, scope);
- results = await timings.stage('anchoring', () => anchorOpResults(ctx.engine, p, queryText, results, { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan }));
+ results = await keepFrontmatterMatches(ctx.engine, await timings.stage('anchoring', () => anchorOpResults(ctx.engine, p, queryText, results, { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types || !!where, evidencePlan: !!plan })), where);
stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap, timings,
- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, hint: { op: 'search', p } })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
keywordCountMeta(await keywordCount, offset + limit)));
},
scope: 'read', mutating: false,
@@ -826,6 +834,7 @@ const query: Operation = {
offset: { type: 'number', description: 'Rows to skip.' },
// #3985: multi-type filter (plumbing shipped v0.33; exposed here).
types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },
+ where: WHERE_PARAM,
// #3800: subagent token economy — per-call snippet cap.
snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
return_unit: RETURN_UNIT_PARAM,
@@ -864,7 +873,7 @@ const query: Operation = {
const queryText = p.query as string | undefined;
// #3985: validated multi-type filter (text path; the image-similarity
// branch below also honors it — searchVector filters types at SQL level).
- let types = normalizeTypesParam(ctx, 'query', p.types);
+ let types = normalizeTypesParam(ctx, 'query', p.types); const where = whereOpParam(ctx, 'query', p.where);
// #3800: snippet cap (param > subagent config default > full text).
const snippetCap = await setup(() => resolveSnippetCap(ctx, p));
const plan = await setup(() => evidencePlanFor(ctx, p, snippetCap, 'query'));
@@ -921,7 +930,7 @@ const query: Operation = {
excludePrivate,
requireSafeChunks: ctx.remote !== false,
takesHoldersAllowList: readHolders(ctx),
- ...(types ? { types } : {}),
+ ...(types ? { types } : {}), ...(where ? { where } : {}),
...querySourceScope,
...dates,
onVectorPoolMeta: info => {
@@ -988,8 +997,8 @@ const query: Operation = {
// T4/D5 — per-call mode (local/trusted only; remote ignored).
...((): { mode?: string } => { const m = resolvePerCallMode(ctx, p.mode); return m ? { mode: m } : {}; })(),
detail,
- // #3985: multi-type filter — SearchOpts.types reaches every leg.
- types,
+ // #3985 / #7159: type and frontmatter filters reach every leg.
+ types, where,
language: (p.lang as string) || undefined,
symbolKind: (p.symbol_kind as string) || undefined,
nearSymbol: (p.near_symbol as string) || undefined,
@@ -1030,7 +1039,7 @@ const query: Operation = {
const fanned = await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primaryRows, queryText, { ...querySourceScope, excludePrivate },
{ excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...querySourceScope }, () => declarations.scan(primaryRows, queryText)));
await emitFanoutNotices(ctx, fanned.fanout, querySourceScope);
- results = await applyQueryArms(ctx.engine, p, queryText, fanned.results, { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p), timer: timings });
+ results = await applyQueryArms(ctx.engine, p, queryText, fanned.results, { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types || !!where, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p), timer: timings });
// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;
// reads the stamped honesty signals: evidence, exact_lookup, rerank
// score), attach grade + query shape to the retrieval meta on EVERY call,
@@ -1085,7 +1094,7 @@ const query: Operation = {
detail,
// Preserve the caller's #3985 type filter on the re-run, as
// normalized for the base call (#5390: [] and "" stay absent).
- ...(types ? { types } : {}),
+ ...(types ? { types } : {}), ...(where ? { where } : {}),
language: (p.lang as string) || undefined,
symbolKind: (p.symbol_kind as string) || undefined,
// Preserve the caller's symbol-proximity constraints too — an
@@ -1153,7 +1162,7 @@ const query: Operation = {
}
const latency_ms = Date.now() - startedAt;
- results = results.map(r => ({ ...r }));
+ results = (await keepFrontmatterMatches(ctx.engine, results, where)).map(r => ({ ...r }));
stampDeepResearchIds(results);
// v0.37.0 (D11): op-layer last_retrieved_at write-back. Same shape as the
@@ -1191,7 +1200,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap, timings,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, hint: { op: 'query', p } })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/ops/where-param.ts b/src/core/ops/where-param.ts
new file mode 100644
index 0000000000..1548c6c6d0
--- /dev/null
+++ b/src/core/ops/where-param.ts
@@ -0,0 +1,20 @@
+/**
+ * The `where` param shared by search, query and list_pages (#7159):
+ * frontmatter equality, validated once at the op boundary
+ * (search/frontmatter-where.ts holds the semantics and the SQL).
+ */
+import type { OperationContext, ParamDef } from './contract.ts';
+import { invalidParam } from './op-fix.ts';
+import { FrontmatterWhereError, WHERE_EXAMPLE, parseFrontmatterWhere, type FrontmatterWhere } from '../search/frontmatter-where.ts';
+
+export const WHERE_PARAM: ParamDef = { type: 'object', cliKeyValue: true, description: 'Frontmatter equality, e.g. {status: "active"}; a list matches any.' };
+
+/** The validated filter, or undefined when absent; a bad key or value is invalid_params. */
+export function whereOpParam(ctx: Pick<OperationContext, 'remote' | 'transport'>, tool: string, raw: unknown): FrontmatterWhere | undefined {
+ try {
+ return parseFrontmatterWhere(raw);
+ } catch (e) {
+ if (!(e instanceof FrontmatterWhereError)) throw e;
+ throw invalidParam(ctx, tool, 'where', e.message, { example: ctx.remote === false ? 'status=active' : WHERE_EXAMPLE });
+ }
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 066d197824..aa57653696 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -153,6 +153,7 @@ import * as sourcesImpl from './engine-sql/sources.ts';
import * as filesImpl from './engine-sql/files.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { KeywordPageWindow } from './search/keyword-statement.ts';
+import { frontmatterWhereSql } from './search/frontmatter-where.ts';
import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import * as chunksImpl from './engine-sql/chunks.ts';
import * as pageBodyImpl from './engine-sql/page-body.ts';
@@ -1449,6 +1450,7 @@ export class PGLiteEngine implements BrainEngine {
params.push(opts.types);
extraFilter += ` AND p.type = ANY($${params.length}::text[])`;
}
+ extraFilter += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
// Postgres parity: single-type filter and exact-slug excludes.
if (opts?.type) {
params.push(opts.type);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..94396af495 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -140,6 +140,7 @@ import * as sourcesImpl from './engine-sql/sources.ts';
import * as filesImpl from './engine-sql/files.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { KeywordPageWindow } from './search/keyword-statement.ts';
+import { frontmatterWhereSql } from './search/frontmatter-where.ts';
import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import * as chunksImpl from './engine-sql/chunks.ts';
import * as pageBodyImpl from './engine-sql/page-body.ts';
@@ -1039,6 +1040,7 @@ export class PostgresEngine implements BrainEngine {
params.push(opts.types);
typesClause = `AND p.type = ANY($${params.length}::text[])`;
}
+ typesClause += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
let excludeSlugsClause = '';
if (excludeSlugs?.length) {
params.push(excludeSlugs);
@@ -1258,6 +1260,7 @@ export class PostgresEngine implements BrainEngine {
params.push(opts.types);
typesClause = `AND p.type = ANY($${params.length}::text[])`;
}
+ typesClause += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
let excludeSlugsClause = '';
if (excludeSlugs?.length) {
params.push(excludeSlugs);
diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.ts
index f783922359..52eaf75ff4 100644
--- a/src/core/search/cjk-keyword-sql.ts
+++ b/src/core/search/cjk-keyword-sql.ts
@@ -22,6 +22,7 @@
*/
import type { SearchOpts } from '../types.ts';
import { buildBestPerPagePoolCte } from './sql-ranking.ts';
+import { frontmatterWhereSql } from './frontmatter-where.ts';
import { escapeLikePattern, cjkMatchTerms } from '../cjk.ts';
/** Query-shape context shared by both engines' CJK fallback call sites. */
@@ -205,6 +206,7 @@ function shapeFilters(opts: SearchOpts | undefined, params: unknown[]): string {
params.push(opts.types);
extraFilter += ` AND p.type = ANY($${params.length}::text[])`;
}
+ extraFilter += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
if (opts?.exclude_slugs?.length) {
params.push(opts.exclude_slugs);
extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;
diff --git a/src/core/search/filter-hint.ts b/src/core/search/filter-hint.ts
new file mode 100644
index 0000000000..a774c0c976
--- /dev/null
+++ b/src/core/search/filter-hint.ts
@@ -0,0 +1,112 @@
+/**
+ * One filter hint per search/query (#7159): agents rarely find `types`,
+ * `since`/`until` and `where`, so when a call looks like it wanted one,
+ * the response carries one `search_filter_hint` notice naming the filter and
+ * the exact next call. It never changes the results.
+ *
+ * Rules, first match wins, none when the caller already filtered that axis:
+ * 1. The query names a page type the brain has pages of (the active schema
+ * pack's type names and aliases, singular or plural) and the top rows are
+ * not already mostly that type: suggest `types: [<type>]`.
+ * 2. The query has a date word (a year, a month, "last week", "recent"…):
+ * suggest `since`/`until` (`search` has none, so it points at `query`).
+ * 3. At least 8 rows came back and 9 in 10 of the top ten share one type the
+ * query does not name: say so and list other types to filter by.
+ * First page only. Deduped per session per suggestion on MCP.
+ */
+import type { Notice } from '../agent-output.ts';
+import type { BrainEngine } from '../engine.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+
+export interface FilterHintInput {
+ op: 'search' | 'query';
+ query: string;
+ rows: ReadonlyArray<{ type?: string | null }>;
+ /** Type names the brain declares (pack names and aliases). */
+ packTypes: readonly string[];
+ /** Whether the brain holds a page of this type. */
+ hasPages: (type: string) => Promise<boolean>;
+ filtered: { types: boolean; dates: boolean };
+}
+
+const DATE_WORDS = /\b((19|20)\d{2}|q[1-4]|jan(uary)?|feb(ruary)?|mar(ch)?|apr(il)?|may|june?|july?|aug(ust)?|sept?(ember)?|oct(ober)?|nov(ember)?|dec(ember)?|spring|summer|autumn|fall|winter|today|yesterday|recent(ly)?|latest|ago|(last|this|past|next) (week|month|quarter|year))\b/i;
+const TOP = 10;
+
+const words = (text: string) => ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ')} `;
+
+/** The forms of a type name a query may use: `meeting`, `meetings`, `office hours` for `office-hours`, `companies`. */
+function typeForms(type: string): string[] {
+ const base = type.toLowerCase().replace(/[-_]+/g, ' ');
+ return [base, `${base}s`, `${base}es`, base.replace(/y$/, 'ies')];
+}
+
+function share(rows: FilterHintInput['rows'], type: string): number {
+ const top = rows.slice(0, TOP);
+ return top.length === 0 ? 0 : top.filter(r => r.type === type).length / top.length;
+}
+
+export async function filterHint(input: FilterHintInput): Promise<Notice | null> {
+ const q = words(input.query);
+ const named = input.packTypes.filter(t => typeForms(t).some(form => q.includes(` ${form} `)));
+ const cli = (args: string[]) => ['gbrain', input.op, input.query, ...args];
+ if (!input.filtered.types) {
+ for (const type of named) {
+ if (share(input.rows, type) >= 0.8 || !await input.hasPages(type).catch(() => false)) continue;
+ return {
+ code: 'search_filter_hint', kind: 'info', dedupe_key: `types:${type}`,
+ why: `The query names the page type "${type}"; types: ["${type}"] (CLI --types ${type}) returns only ${type} pages.`,
+ fix: readFix(`Repeat the ${input.op} restricted to ${type} pages.`, { argv: cli(['--types', type]), mcp: { tool: input.op, arguments: { query: input.query, types: [type] } } }),
+ };
+ }
+ }
+ if (!input.filtered.dates && DATE_WORDS.test(input.query)) {
+ const why = input.op === 'query'
+ ? 'The query names a time; since/until (CLI --since YYYY-MM-DD, --until) restrict results to pages dated in that window.'
+ : 'The query names a time; search has no date filter, query takes since/until (CLI --since YYYY-MM-DD, --until) for pages dated in that window.';
+ return {
+ code: 'search_filter_hint', kind: 'info', dedupe_key: 'dates', why,
+ fix: readFix('Repeat it as a query with a date window (fill in the dates).', { argv: ['gbrain', 'query', input.query, '--since', 'YYYY-MM-DD'], mcp: { tool: 'query', arguments: { query: input.query, since: 'YYYY-MM-DD' } } }),
+ };
+ }
+ if (input.filtered.types || input.rows.length < 8) return null;
+ const dominant = input.rows[0]?.type;
+ if (!dominant || share(input.rows, dominant) < 0.9 || named.includes(dominant)) return null;
+ const others = input.packTypes.filter(t => t !== dominant).slice(0, 8);
+ if (others.length === 0) return null;
+ return {
+ code: 'search_filter_hint', kind: 'info', dedupe_key: `dominant:${dominant}`,
+ why: `The top results are almost all "${dominant}" pages. To read another kind, pass types (CLI --types <type>); this brain's types include ${others.join(', ')}. Frontmatter fields filter with where (CLI --where key=value).`,
+ };
+}
+
+/** The brain's declared type names for the hint (pack names and aliases); empty when no pack loads. */
+export async function packTypeNames(engine: BrainEngine, sourceId: string | undefined): Promise<string[]> {
+ try {
+ const pack = await loadActivePackForEngine(engine, { remote: true, sourceId });
+ return [...new Set(pack.manifest.page_types.flatMap(t => [t.name, ...(t.aliases ?? [])]))];
+ } catch {
+ return [];
+ }
+}
+
+/** Whether the caller can see any page of this type: one listing row under the caller's own source and private-page scope. */
+export async function callerHasType(engine: BrainEngine, type: string, scope: { sourceId?: string; sourceIds?: string[]; excludePrivate: boolean }): Promise<boolean> {
+ return (await engine.listPages({ type, limit: 1, listColumnsOnly: true, ...scope })).length > 0;
+}
+
+/** The op-side wrapper: the hint for a search/query first page, or null (never throws). */
+export async function searchFilterHint(ctx: { engine: BrainEngine; sourceId?: string }, scope: { sourceId?: string; sourceIds?: string[] }, excludePrivate: boolean,
+ query: string, rows: ReadonlyArray<{ type?: string | null }>, types: string[] | undefined, call: { op: 'search' | 'query'; p: Record<string, unknown> }): Promise<Notice | null> {
+ if (!query.trim() || Number(call.p.offset ?? 0) > 0 || call.p.cursor !== undefined) return null;
+ try {
+ return await filterHint({
+ op: call.op, query, rows,
+ packTypes: await packTypeNames(ctx.engine, scope.sourceId ?? scope.sourceIds?.[0] ?? ctx.sourceId),
+ hasPages: type => callerHasType(ctx.engine, type, { ...scope, excludePrivate }),
+ filtered: { types: (types?.length ?? 0) > 0, dates: typeof call.p.since === 'string' || typeof call.p.until === 'string' },
+ });
+ } catch {
+ return null;
+ }
+}
diff --git a/src/core/search/frontmatter-where.ts b/src/core/search/frontmatter-where.ts
new file mode 100644
index 0000000000..ab542f59bb
--- /dev/null
+++ b/src/core/search/frontmatter-where.ts
@@ -0,0 +1,107 @@
+/**
+ * Frontmatter equality filter (#7159): `where: { key: value | [values] }` on
+ * search, query and list_pages (CLI `--where key=value`, repeatable). Keys
+ * AND; a key's values OR. A value matches a page whose top-level frontmatter
+ * field equals it, or whose field is a list containing it. A string that reads
+ * as a number or a boolean also matches that JSON value, since the CLI only
+ * sends strings (`--where cycle=2024` matches `cycle: 2024`).
+ *
+ * SQL: one `p.frontmatter @> $n::text::jsonb` containment per accepted JSON form,
+ * so the GIN index on pages.frontmatter (idx_pages_frontmatter, jsonb_ops)
+ * serves every key; values are always bound parameters, never SQL text, and
+ * keys travel inside the bound JSON. Keys are still held to a plain
+ * identifier charset so a typo or an injection attempt fails loudly.
+ * The filter only narrows rows: every visibility, source and private-page
+ * predicate a caller already gets still applies.
+ */
+import { joinFragments, sqlFragment, type SqlFragment } from '../engine-sql/fragment.ts';
+
+export type FrontmatterValue = string | number | boolean;
+/** Normalized: every key maps to a non-empty value list. */
+export type FrontmatterWhere = Record<string, FrontmatterValue[]>;
+
+export const FRONTMATTER_KEY_RE = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
+const MAX_KEYS = 8;
+const MAX_VALUES = 32;
+const MAX_VALUE_CHARS = 256;
+export const WHERE_EXAMPLE = { status: 'active' };
+
+export class FrontmatterWhereError extends Error {}
+
+/** Validate a caller's `where`; undefined when absent or empty. Throws FrontmatterWhereError on a bad key or value. */
+export function parseFrontmatterWhere(raw: unknown): FrontmatterWhere | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
+ throw new FrontmatterWhereError('`where` must be an object of frontmatter keys to a value or a list of values.');
+ }
+ const entries = Object.entries(raw as Record<string, unknown>);
+ if (entries.length > MAX_KEYS) throw new FrontmatterWhereError(`\`where\` takes at most ${MAX_KEYS} keys (got ${entries.length}).`);
+ const out: FrontmatterWhere = {};
+ for (const [key, value] of entries) {
+ if (!FRONTMATTER_KEY_RE.test(key)) {
+ throw new FrontmatterWhereError(`\`where\` key "${key.slice(0, 64)}" is not a frontmatter field name (letters, digits, _ and -, starting with a letter or _, at most 64 characters).`);
+ }
+ const values = Array.isArray(value) ? value : [value];
+ if (values.length === 0 || values.length > MAX_VALUES) {
+ throw new FrontmatterWhereError(`\`where.${key}\` needs 1 to ${MAX_VALUES} values (got ${values.length}).`);
+ }
+ for (const v of values) {
+ const scalar = typeof v === 'string' || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v));
+ if (!scalar || (typeof v === 'string' && v.length > MAX_VALUE_CHARS)) {
+ throw new FrontmatterWhereError(`\`where.${key}\` values must be strings (at most ${MAX_VALUE_CHARS} characters), finite numbers or booleans.`);
+ }
+ }
+ out[key] = [...new Set(values as FrontmatterValue[])];
+ }
+ return entries.length > 0 ? out : undefined;
+}
+
+/** The JSON documents one value matches by containment: itself, as a list member, and a numeric/boolean reading of a string. */
+function containmentDocs(key: string, value: FrontmatterValue): string[] {
+ const forms = new Set<FrontmatterValue>([value]);
+ if (typeof value === 'string') {
+ if (/^-?(0|[1-9]\d*)(\.\d+)?$/.test(value)) forms.add(Number(value));
+ if (value === 'true' || value === 'false') forms.add(value === 'true');
+ }
+ return [...forms].flatMap(v => [JSON.stringify({ [key]: v }), JSON.stringify({ [key]: [v] })]);
+}
+
+/** One `AND (...)` clause per key, values bound through `bind` (which returns the placeholder). */
+export function frontmatterWhereClauses(alias: string, where: FrontmatterWhere | undefined, bind: (json: string) => string): string[] {
+ if (!where) return [];
+ return Object.entries(where).map(([key, values]) =>
+ `AND (${values.flatMap(v => containmentDocs(key, v)).map(doc => `${alias}.frontmatter @> ${bind(doc)}::text::jsonb`).join(' OR ')})`);
+}
+
+/** The same clauses as one string with a leading space each ('' without a filter). */
+export function frontmatterWhereSql(alias: string, where: FrontmatterWhere | undefined, bind: (json: string) => string): string {
+ return frontmatterWhereClauses(alias, where, bind).map(c => ` ${c}`).join('');
+}
+
+/** The same predicate as a composable engine-sql fragment, each clause with a leading space ('' without a filter). */
+export function frontmatterWhereFragment(where: FrontmatterWhere | undefined): SqlFragment {
+ if (!where) return sqlFragment``;
+ return joinFragments(Object.entries(where).map(([key, values]) =>
+ sqlFragment` AND (${joinFragments(values.flatMap(v => containmentDocs(key, v)).map(doc => sqlFragment`p.frontmatter @> ${doc}::text::jsonb`), ' OR ')})`), '');
+}
+
+/**
+ * The authoritative check on finished rows: arms that do not run through the
+ * filtered SQL legs (exact lookup, relational, alias fan-out, facts) can add
+ * pages, so a filtered search keeps only rows whose page matches. One
+ * indexed read over the result's page ids; a row with no page id is dropped.
+ */
+export async function keepFrontmatterMatches<T extends { page_id?: number | null }>(
+ engine: { executeRaw<R>(sql: string, params?: unknown[]): Promise<R[]> },
+ rows: T[],
+ where: FrontmatterWhere | undefined,
+): Promise<T[]> {
+ if (!where || rows.length === 0) return rows;
+ const ids = [...new Set(rows.flatMap(r => typeof r.page_id === 'number' && r.page_id > 0 ? [r.page_id] : []))];
+ if (ids.length === 0) return [];
+ const params: unknown[] = [ids];
+ const clause = frontmatterWhereSql('p', where, json => `$${params.push(json)}`);
+ const matched = await engine.executeRaw<{ id: number | string }>(`SELECT p.id FROM pages p WHERE p.id = ANY($1::bigint[])${clause}`, params);
+ const keep = new Set(matched.map(r => Number(r.id)));
+ return rows.filter(r => typeof r.page_id === 'number' && keep.has(r.page_id));
+}
diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.ts
index bfc957e50f..d9d4cbc680 100644
--- a/src/core/search/hybrid/cache-stages.ts
+++ b/src/core/search/hybrid/cache-stages.ts
@@ -224,7 +224,8 @@ export function semanticCacheSkipped(opts: HybridSearchOpts | undefined, semanti
// #3985: type-filtered requests skip the cache — `types` is not part of
// knobsHash, so a filtered result set could be served to an unfiltered
// lookup (and vice versa). Mirrors the #3442 date-filter bypass.
- const typeFiltered = Boolean(opts?.type) || (opts?.types?.length ?? 0) > 0;
+ // #7159: a frontmatter filter is not in knobsHash either.
+ const typeFiltered = Boolean(opts?.type) || (opts?.types?.length ?? 0) > 0 || opts?.where !== undefined;
// Offset pages are cache-hostile until the pre-slice POOL itself is what's
// stored: the cache holds the already offset/limit-sliced page (bare
// hybridSearch slices before returning), so a hit for any other offset
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 2505f3eba3..348587f216 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -232,6 +232,8 @@ export async function resolveHybridRequest(
// type filter to SQL level so the limit budget goes to candidate-typed
// pages instead of being eaten by note/transcript/article pages.
types: opts?.types,
+ // #7159: frontmatter equality, pushed into the same legs.
+ where: opts?.where,
// Exact-slug and prefix exclusions are caller contract too (grade-takes
// passes exclude_slugs; SDK callers pass prefix excludes); dropping them
// here silently ignored them on every arm.
diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.ts
index 4fdc591a0b..1ddf693666 100644
--- a/src/core/search/keyword-statement.ts
+++ b/src/core/search/keyword-statement.ts
@@ -22,6 +22,7 @@
import type { SearchOpts } from '../types.ts';
import { escapeLikePattern, hasCJK, cjkMatchTerms } from '../cjk.ts';
import { getFtsLanguage } from '../fts-language.ts';
+import { frontmatterWhereSql } from './frontmatter-where.ts';
import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';
import { buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';
@@ -69,6 +70,7 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):
if (opts?.symbolKind) filters += add(opts.symbolKind, n => `cc.symbol_type = ${n}`);
if (opts?.type) filters += add(opts.type, n => `p.type = ${n}`);
if (opts?.types?.length) filters += add(opts.types, n => `p.type = ANY(${n}::text[])`);
+ filters += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
if (opts?.exclude_slugs?.length) filters += add(opts.exclude_slugs, n => `p.slug != ALL(${n}::text[])`);
const dated = `COALESCE(p.effective_date, p.updated_at, p.created_at)`;
if (opts?.afterDate) filters += add(opts.afterDate, n => `${dated} ${opts.afterDateInclusive ? '>=' : '>'} ${n}::text::timestamptz`);
diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.ts
index 7e5bae7efa..5ccf778a6f 100644
--- a/src/core/search/title-statement.ts
+++ b/src/core/search/title-statement.ts
@@ -11,6 +11,7 @@ import { searchLimitCap } from './eval-pool-depth.ts';
import { getFtsLanguage } from '../fts-language.ts';
import { chunkGenerationFilter, requiresSafeChunks } from './safe-chunks.ts';
import { normalizeAlias } from './alias-normalize.ts';
+import { frontmatterWhereSql } from './frontmatter-where.ts';
import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';
import {
boundWebsearchQuery,
@@ -73,6 +74,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und
params.push(opts.types);
filters += ` AND p.type = ANY($${params.length}::text[])`;
}
+ filters += frontmatterWhereSql('p', opts?.where, json => `$${params.push(json)}`);
if (opts?.exclude_slugs?.length) {
params.push(opts.exclude_slugs);
filters += ` AND p.slug != ALL($${params.length}::text[])`;
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index c8f0047055..e15294de9b 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -61,6 +61,7 @@ import type { SearchOpts } from '../types.ts';
import { hnswIndexExpected } from '../vector-index.ts';
import { unverifiedExtractionFragment } from '../extraction-review.ts';
import { buildVectorCastFragment, normalizeEngineColumn } from './embedding-column.ts';
+import { frontmatterWhereClauses } from './frontmatter-where.ts';
import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';
import { buildBestPerPagePoolCte, buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';
import { chunkGenerationProbe } from './safe-chunks.ts';
@@ -304,6 +305,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
if (opts?.type) filters.push(`AND p.type = ${bind(opts.type)}`);
// v0.33: multi-type filter for whoknows, AND-applied with `type`.
if (opts?.types && opts.types.length > 0) filters.push(`AND p.type = ANY(${bind(opts.types)}::text[])`);
+ filters.push(...frontmatterWhereClauses('p', opts?.where, bind));
if (opts?.exclude_slugs?.length) filters.push(`AND p.slug != ALL(${bind(opts.exclude_slugs)}::text[])`);
if (opts?.language) filters.push(`AND cc.language = ${bind(opts.language)}`);
if (opts?.symbolKind) filters.push(`AND cc.symbol_type = ${bind(opts.symbolKind)}`);
@@ -333,7 +335,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
// the caller narrowing the search; the walk would usually come back short,
// so those keep the joined statement alone.
const share = input.scope?.share, chunks = input.scope?.chunks;
- const narrowed = !!(opts?.type || opts?.types?.length || opts?.afterDate || opts?.beforeDate)
+ const narrowed = !!(opts?.type || opts?.types?.length || opts?.where || opts?.afterDate || opts?.beforeDate)
|| (share !== undefined && share < INDEX_WALK_MIN_SCOPE_SHARE);
const scopeScan = relaxed && share !== undefined && share < SCOPE_SCAN_MAX_SHARE && chunks !== undefined && chunks <= SCOPE_SCAN_MAX_CHUNKS;
const walk = relaxed && !narrowed && !(scopeScan && chunks! <= SCOPE_SCAN_FIRST_MAX_CHUNKS);
diff --git a/src/core/types.ts b/src/core/types.ts
index 7ccf11683d..4224940af2 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -398,6 +398,8 @@ export interface PageFilters {
* read none of those fields (list_pages).
*/
listColumnsOnly?: boolean;
+ /** #7159: frontmatter equality (search/frontmatter-where.ts). */
+ where?: import('./search/frontmatter-where.ts').FrontmatterWhere;
}
/** v0.26.5 — opts for getPage / softDeletePage / restorePage. */
@@ -1261,6 +1263,8 @@ export interface SearchOpts extends PageReadPolicy {
* entity-only search reuses the parameter.
*/
types?: PageType[];
+ /** #7159: frontmatter equality, pushed into every SQL leg (search/frontmatter-where.ts). */
+ where?: import('./search/frontmatter-where.ts').FrontmatterWhere;
exclude_slugs?: string[];
/**
* Slug-prefix excludes — additive over DEFAULT_HARD_EXCLUDES (test/,
diff --git a/test/e2e/search-frontmatter-where-parity.test.ts b/test/e2e/search-frontmatter-where-parity.test.ts
new file mode 100644
index 0000000000..5605172b63
--- /dev/null
+++ b/test/e2e/search-frontmatter-where-parity.test.ts
@@ -0,0 +1,68 @@
+/**
+ * #7159 engine parity: the frontmatter `where` filter returns the same pages
+ * on PGLite and Postgres for search, query and list_pages, and a remote
+ * caller never reaches a private page through it (Postgres arm runs when
+ * DATABASE_URL is set; the PGLite arm always runs).
+ *
+ * Postgres reads jsonb containment through postgres.js parameters and the
+ * GIN index on pages.frontmatter; a cast or parameter-type slip there would
+ * drop or widen matches only on Postgres.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { operations } from '../../src/core/operations.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { searchCtx } from '../helpers/keyword-paging-fixture.ts';
+import { PRIVATE_WHERE, PRIVATE_WHERE_LOCAL, PRIVATE_WHERE_REMOTE, TERM, WHERE_CASES, seedFrontmatterCorpus } from '../helpers/frontmatter-where-fixture.ts';
+
+const backends = process.env.DATABASE_URL ? ['pglite', 'postgres'] as const : ['pglite'] as const;
+const engines: Partial<Record<(typeof backends)[number], BrainEngine>> = {};
+const closers: Array<() => Promise<void>> = [];
+
+async function slugs(engine: BrainEngine, name: string, params: Record<string, unknown>, remote = true): Promise<string[]> {
+ const rows = await operations.find(o => o.name === name)!.handler(searchCtx(engine, remote) as never, params) as Array<{ slug: string }>;
+ return [...new Set(rows.map(r => r.slug))].sort();
+}
+
+beforeAll(async () => {
+ for (const backend of backends) {
+ let engine: BrainEngine;
+ if (backend === 'postgres') {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = isolated.engine;
+ closers.push(isolated.close);
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ closers.push(() => engine.disconnect());
+ }
+ await seedFrontmatterCorpus(engine);
+ engines[backend] = engine;
+ }
+}, 300_000);
+
+afterAll(async () => { for (const close of closers) await close(); });
+
+for (const backend of backends) {
+ describe(`where filter on ${backend}`, () => {
+ for (const [label, where, expected] of WHERE_CASES) {
+ test(label, async () => {
+ const engine = engines[backend]!;
+ expect(await slugs(engine, 'search', { query: TERM, where })).toEqual(expected);
+ expect(await slugs(engine, 'search', { query: TERM, where, match: 'keyword' })).toEqual(expected);
+ expect(await slugs(engine, 'query', { query: TERM, where, expand: false })).toEqual(expected);
+ expect(await slugs(engine, 'list_pages', { where })).toEqual(expected);
+ });
+ }
+
+ test('remote callers stay private-filtered; the local CLI does not', async () => {
+ const engine = engines[backend]!;
+ for (const name of ['search', 'list_pages']) {
+ expect(await slugs(engine, name, { query: TERM, where: PRIVATE_WHERE })).toEqual(PRIVATE_WHERE_REMOTE);
+ expect(await slugs(engine, name, { query: TERM, where: PRIVATE_WHERE }, false)).toEqual(PRIVATE_WHERE_LOCAL);
+ }
+ });
+ });
+}
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 5ffff0a2f5..329a4755e0 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -718,7 +718,7 @@
"stdout": [
"Usage: gbrain query <query> [options]",
"",
- "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",
+ "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. Filters: types, since/until, where (frontmatter fields). fields: \"full\" adds diagnostics.",
"",
"Options:",
" <query> Question or topic (required unless image).",
@@ -727,6 +727,7 @@
" --limit Default 10/25/50 by search mode.",
" --offset Rows to skip.",
" --types Page types, e.g. ['person'].",
+ " --where Frontmatter equality, e.g. {status: \"active\"}; a list matches any.",
" --snippet-chars Chars per row (0 = full).",
" --return-unit Default auto: whole conversations.",
" --return-window Window radius 1-3.",
@@ -751,7 +752,11 @@
" --relational Relationship-graph arm (default on).",
" --min-trust Lowest trust tier to return (the connection floor still applies).",
" --explain Per-row score_details.",
- " --explain-target Expected page (slug or source:slug): why it is missing."
+ " --explain-target Expected page (slug or source:slug): why it is missing.",
+ "",
+ "Examples:",
+ " gbrain query \"what changed at acme-example\" --types meeting --since 2026-01-01 --until 2026-03-31",
+ " gbrain query \"open deals\" --where stage=seed,series-a"
]
},
{
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index fc9e438d91..db35325d05 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 252798,
- "stdoutSha256": "71b348f0e16ec33eeb7b856a2fa24821a5f971503416d541e00226572381ab56",
+ "stdoutBytes": 253571,
+ "stdoutSha256": "31c6500d8507ce0715716ce0fe98260cc3e9ca6a68224775308bdab5325add64",
"toolNames": [
"remember",
"entity",
@@ -718,7 +718,7 @@
"scope": "write"
},
{
- "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row.",
+ "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows; truncated: continue with updated_after + updated_after_slug from the last row. Filters: type, tag, updated_after, where (frontmatter fields); sort: updated_desc, updated_asc, created_desc, slug.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -732,7 +732,8 @@
"tag": "string?",
"type": "string?",
"updated_after": "string?",
- "updated_after_slug": "string?"
+ "updated_after_slug": "string?",
+ "where": "object?"
},
"required_scopes": [],
"schema": {
@@ -778,6 +779,10 @@
"updated_after_slug": {
"description": "Last row's slug (with updated_after).",
"type": "string"
+ },
+ "where": {
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any.",
+ "type": "object"
}
},
"required": [],
@@ -1566,7 +1571,7 @@
"scope": "write"
},
{
- "description": "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. fields: \"full\" adds diagnostics.",
+ "description": "Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. NOT proof of coverage; match: \"keyword\" pages every keyword match and takes OR across quoted names or codes (\"A\" OR \"B\" OR …): one call lists every page matching any. Name lists: entity names. Concepts/landscape or people/companies/projects by topic: `query`; lists: list_pages; personal: get_recent_salience. return_unit: sections or conversations. Filters: types, where (frontmatter fields); dates: `query`. fields: \"full\" adds diagnostics.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -1587,7 +1592,8 @@
"snippet_chars": "number?",
"source_id": "string?",
"token_budget": "number?",
- "types": "array?"
+ "types": "array?",
+ "where": "object?"
},
"required_scopes": [],
"schema": {
@@ -1691,6 +1697,10 @@
"type": "string"
},
"type": "array"
+ },
+ "where": {
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any.",
+ "type": "object"
}
},
"required": [
@@ -1701,7 +1711,7 @@
"scope": "read"
},
{
- "description": "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",
+ "description": "Hybrid search for concept/landscape questions and people/companies/projects by topic; expand adds multi-query expansion (expansion recovers synonyms). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. Filters: types, since/until, where (frontmatter fields). fields: \"full\" adds diagnostics.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -1737,7 +1747,8 @@
"token_budget": "number?",
"types": "array?",
"until": "string?",
- "walk_depth": "number?"
+ "walk_depth": "number?",
+ "where": "object?"
},
"required_scopes": [],
"schema": {
@@ -1903,6 +1914,10 @@
"walk_depth": {
"description": "Code walk depth 1-2.",
"type": "number"
+ },
+ "where": {
+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any.",
+ "type": "object"
}
},
"required": [],
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index de6eb6e6a5..7fccda6f0e 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -962,7 +962,8 @@
"tag?: string | undefined",
"type?: string | undefined",
"updatedAfterKeyset?: { updatedAt: string; slug: string; } | undefined",
- "updated_after?: string | undefined"
+ "updated_after?: string | undefined",
+ "where?: FrontmatterWhere | undefined"
],
"name": "PageFilters"
},
@@ -1464,7 +1465,8 @@
"until?: string | undefined",
"useCache?: boolean | undefined",
"vectorLegacyGuard?: boolean | undefined",
- "walkDepth?: number | undefined"
+ "walkDepth?: number | undefined",
+ "where?: FrontmatterWhere | undefined"
],
"name": "SearchOpts"
},
@@ -6465,6 +6467,7 @@
{
"kind": "interface",
"members": [
+ "cliKeyValue?: boolean | undefined",
"default?: unknown",
"description?: string | undefined",
"enum?: string[] | undefined",
@@ -7939,7 +7942,8 @@
"until?: string | undefined",
"useCache?: boolean | undefined",
"vectorLegacyGuard?: boolean | undefined",
- "walkDepth?: number | undefined"
+ "walkDepth?: number | undefined",
+ "where?: FrontmatterWhere | undefined"
],
"name": "HybridSearchOpts"
},
@@ -9213,7 +9217,8 @@
"tag?: string | undefined",
"type?: string | undefined",
"updatedAfterKeyset?: { updatedAt: string; slug: string; } | undefined",
- "updated_after?: string | undefined"
+ "updated_after?: string | undefined",
+ "where?: FrontmatterWhere | undefined"
],
"name": "PageFilters"
},
@@ -9468,7 +9473,8 @@
"until?: string | undefined",
"useCache?: boolean | undefined",
"vectorLegacyGuard?: boolean | undefined",
- "walkDepth?: number | undefined"
+ "walkDepth?: number | undefined",
+ "where?: FrontmatterWhere | undefined"
],
"name": "SearchOpts"
},
diff --git a/test/helpers/frontmatter-where-fixture.ts b/test/helpers/frontmatter-where-fixture.ts
new file mode 100644
index 0000000000..ffc108f076
--- /dev/null
+++ b/test/helpers/frontmatter-where-fixture.ts
@@ -0,0 +1,34 @@
+/**
+ * #7159 fixture: deal/person/meeting pages with frontmatter fields, one
+ * private page, shared by the PGLite unit test and the engine parity E2E.
+ * All names are placeholders.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { seedPage } from './keyword-paging-fixture.ts';
+
+export const TERM = 'widget';
+
+export const WHERE_CASES: Array<[string, Record<string, unknown>, string[]]> = [
+ ['equality', { stage: 'seed' }, ['deals/acme-example', 'deals/gamma-example']],
+ ['list member', { partner: 'carol-example' }, ['deals/gamma-example']],
+ ['scalar or list member', { partner: 'alice-example' }, ['deals/acme-example', 'deals/gamma-example', 'meetings/standup-example']],
+ ['any of', { stage: ['seed', 'series-a'] }, ['deals/acme-example', 'deals/beta-example', 'deals/gamma-example']],
+ ['keys AND', { stage: 'seed', partner: 'carol-example' }, ['deals/gamma-example']],
+ ['numeric string matches a number', { year: '2024' }, ['deals/acme-example']],
+ ['boolean string matches a boolean', { active: 'true' }, ['deals/gamma-example']],
+ ['no match', { stage: 'growth' }, []],
+ ['a quote in a value is data, not SQL', { stage: "seed' OR '1'='1" }, []],
+];
+
+export const PRIVATE_WHERE = { stage: 'seed', partner: 'alice-example' };
+export const PRIVATE_WHERE_REMOTE = ['deals/acme-example', 'deals/gamma-example'];
+export const PRIVATE_WHERE_LOCAL = ['deals/acme-example', 'deals/gamma-example', 'deals/private-example'];
+
+export async function seedFrontmatterCorpus(engine: BrainEngine): Promise<void> {
+ await seedPage(engine, 'deals/acme-example', `Acme-example ${TERM} deal: seed round notes.`, { type: 'deal', frontmatter: { stage: 'seed', partner: 'alice-example', year: 2024 } });
+ await seedPage(engine, 'deals/beta-example', `Beta-example ${TERM} deal: series A notes.`, { type: 'deal', frontmatter: { stage: 'series-a', partner: 'bob-example', year: 2025 } });
+ await seedPage(engine, 'deals/gamma-example', `Gamma-example ${TERM} deal: seed extension notes.`, { type: 'deal', frontmatter: { stage: 'seed', partner: ['alice-example', 'carol-example'], active: true } });
+ await seedPage(engine, 'deals/private-example', `Private-example ${TERM} deal: seed round, private.`, { type: 'deal', frontmatter: { stage: 'seed', partner: 'alice-example', visibility: 'private' } });
+ await seedPage(engine, 'people/alice-example', `Alice-example reviews every ${TERM} deal.`, { type: 'person', frontmatter: { role: 'partner' } });
+ await seedPage(engine, 'meetings/standup-example', `Standup about the ${TERM} roadmap.`, { type: 'meeting', frontmatter: { partner: 'alice-example' } });
+}
diff --git a/test/search-frontmatter-where.test.ts b/test/search-frontmatter-where.test.ts
new file mode 100644
index 0000000000..b41ec75e8a
--- /dev/null
+++ b/test/search-frontmatter-where.test.ts
@@ -0,0 +1,127 @@
+/**
+ * #7159: the frontmatter equality filter on search, query and list_pages
+ * (`where` over MCP, `--where key=value` on the CLI), and the one filter
+ * hint a search/query carries when it looks like it wanted a filter.
+ *
+ * PGLite; the same scenarios run on Postgres in
+ * test/e2e/search-frontmatter-where-parity.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations } from '../src/core/operations.ts';
+import { parseOpArgs } from '../src/cli/main.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+import { frontmatterWhereClauses, parseFrontmatterWhere } from '../src/core/search/frontmatter-where.ts';
+import { filterHint } from '../src/core/search/filter-hint.ts';
+import { searchCtx } from './helpers/keyword-paging-fixture.ts';
+import { PRIVATE_WHERE, PRIVATE_WHERE_LOCAL, PRIVATE_WHERE_REMOTE, TERM, WHERE_CASES, seedFrontmatterCorpus } from './helpers/frontmatter-where-fixture.ts';
+
+let engine: PGLiteEngine;
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+async function run(name: string, params: Record<string, unknown>, remote: boolean): Promise<{ slugs: string[]; notices: Notice[] }> {
+ const notices: Notice[] = [];
+ const ctx = { ...searchCtx(engine, remote), emitNotice: (n: Notice) => { notices.push(n); } };
+ const rows = await op(name).handler(ctx as never, params) as Array<{ slug: string }>;
+ return { slugs: [...new Set(rows.map(r => r.slug))].sort(), notices };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedFrontmatterCorpus(engine);
+}, 120_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+describe('where filter (#7159)', () => {
+ for (const [label, where, expected] of WHERE_CASES) {
+ test(`remote search, query and list_pages agree: ${label}`, async () => {
+ expect((await run('search', { query: TERM, where }, true)).slugs).toEqual(expected);
+ expect((await run('query', { query: TERM, where, expand: false }, true)).slugs).toEqual(expected);
+ expect((await run('list_pages', { where }, true)).slugs).toEqual(expected);
+ });
+ }
+
+ test('keyword-mode search pages the filtered set', async () => {
+ expect((await run('search', { query: TERM, where: { stage: 'seed' }, match: 'keyword' }, true)).slugs).toEqual(['deals/acme-example', 'deals/gamma-example']);
+ });
+
+ test('a remote caller never sees a private page through the filter; the local CLI does', async () => {
+ const where = PRIVATE_WHERE;
+ expect((await run('search', { query: TERM, where }, true)).slugs).toEqual(PRIVATE_WHERE_REMOTE);
+ expect((await run('query', { query: TERM, where, expand: false }, true)).slugs).toEqual(PRIVATE_WHERE_REMOTE);
+ expect((await run('list_pages', { where }, true)).slugs).toEqual(PRIVATE_WHERE_REMOTE);
+ expect((await run('search', { query: TERM, where }, false)).slugs).toEqual(PRIVATE_WHERE_LOCAL);
+ expect((await run('list_pages', { where }, false)).slugs).toEqual(PRIVATE_WHERE_LOCAL);
+ });
+
+ test('list_pages where composes with type, updated_after and sort', async () => {
+ const rows = await op('list_pages').handler(searchCtx(engine, true) as never, { type: 'deal', where: { stage: 'seed' }, sort: 'slug', updated_after: '2000-01-01' }) as Array<{ slug: string }>;
+ expect(rows.map(r => r.slug)).toEqual(['deals/acme-example', 'deals/gamma-example']);
+ });
+
+ test('an invalid key or value is invalid_params on every op', async () => {
+ for (const name of ['search', 'query', 'list_pages']) {
+ for (const where of [{ 'bad key': 'x' }, { "k'); DROP TABLE pages; --": 'x' }, { stage: [] }, { stage: { nested: 1 } }, 'stage=seed', ['stage']]) {
+ await expect(op(name).handler(searchCtx(engine, true) as never, { query: TERM, where })).rejects.toMatchObject({ code: 'invalid_params' });
+ }
+ }
+ });
+
+ test('values are bound parameters and keys travel only inside the bound JSON', () => {
+ const params: string[] = [];
+ const clauses = frontmatterWhereClauses('p', parseFrontmatterWhere({ stage: "seed'--" }), json => `$${params.push(json)}`);
+ expect(clauses).toEqual(['AND (p.frontmatter @> $1::text::jsonb OR p.frontmatter @> $2::text::jsonb)']);
+ expect(params.map(p => JSON.parse(p))).toEqual([{ stage: "seed'--" }, { stage: ["seed'--"] }]);
+ });
+});
+
+describe('CLI parsing', () => {
+ test('--where key=value repeats, key=a,b is a list, a repeated key merges', () => {
+ expect(parseOpArgs(op('search') as never, ['q', '--where', 'stage=seed,series-a', '--where', 'partner=alice-example', '--where=stage=growth']).where)
+ .toEqual({ stage: ['seed', 'series-a', 'growth'], partner: 'alice-example' });
+ expect(parseOpArgs(op('list_pages') as never, ['--where', '{"stage":"seed"}']).where).toEqual({ stage: 'seed' });
+ expect(parseOpArgs(op('query') as never, ['q', '--where', 'stage=seed']).where).toEqual({ stage: 'seed' });
+ expect(() => parseOpArgs(op('query') as never, ['q', '--where', 'stage'])).toThrow('--where takes key=value');
+ });
+});
+
+describe('filter hint', () => {
+ const hint = (notices: Notice[]) => notices.find(n => n.code === 'search_filter_hint');
+
+ test('a query naming a page type gets one hint naming types, and the same results', async () => {
+ const hinted = await run('search', { query: `${TERM} meetings` }, true);
+ const h = hint(hinted.notices);
+ expect(h?.why).toContain('types: ["meeting"]');
+ expect(h?.fix?.argv).toEqual(['gbrain', 'search', `${TERM} meetings`, '--types', 'meeting']);
+ expect(hinted.slugs).toContain('deals/acme-example');
+ expect(hinted.notices.filter(n => n.code === 'search_filter_hint')).toHaveLength(1);
+ });
+
+ test('no hint once the caller filters by type, or for a plain query', async () => {
+ expect(hint((await run('search', { query: `${TERM} meetings`, types: ['meeting'] }, true)).notices)).toBeUndefined();
+ expect(hint((await run('search', { query: TERM }, true)).notices)).toBeUndefined();
+ });
+
+ test('a date word gets the since/until hint; search points at query', async () => {
+ const q = (await run('query', { query: `${TERM} roadmap in 2024`, expand: false }, true)).notices;
+ expect(hint(q)?.why).toContain('since/until');
+ expect(hint(q)?.fix?.mcp).toEqual({ tool: 'query', arguments: { query: `${TERM} roadmap in 2024`, since: 'YYYY-MM-DD' } });
+ expect(hint((await run('search', { query: `${TERM} roadmap last week` }, true)).notices)?.why).toContain('search has no date filter');
+ expect(hint((await run('query', { query: `${TERM} roadmap in 2024`, since: '2024-01-01', expand: false }, true)).notices)).toBeUndefined();
+ });
+
+ test('top results filled by one unnamed type get the dominance hint', async () => {
+ const rows = Array.from({ length: 10 }, () => ({ type: 'note' }));
+ const n = await filterHint({ op: 'search', query: 'roadmap', rows, packTypes: ['note', 'person', 'deal'], hasPages: async () => true, filtered: { types: false, dates: false } });
+ expect(n?.why).toContain('almost all "note" pages');
+ expect(n?.why).toContain('person, deal');
+ expect(await filterHint({ op: 'search', query: 'roadmap', rows: rows.slice(0, 5), packTypes: ['note', 'person'], hasPages: async () => true, filtered: { types: false, dates: false } })).toBeNull();
+ });
+
+ test('a named type with no pages the caller can see gets no hint', async () => {
+ expect(await filterHint({ op: 'search', query: 'company roadmap', rows: [], packTypes: ['company'], hasPages: async () => false, filtered: { types: false, dates: false } })).toBeNull();
+ });
+});