Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): leave embed_skip pages out of embedding_held coverage

garrytan8ba85d94f2cb
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 72dcba1b41..63ef90061c 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | rate_limited | unreachable | auth | provider_error` (gateway `rate_limit` → `rate_limited`, a transport failure with no HTTP response → `unreachable`, 401/403 → `auth`, 5xx and everything else → `provider_error`; Cat 40 R0, pinned on the real wire by `test/rerank-failure-reason.serial.test.ts`), which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.
-- `src/core/search/retrieval-coverage.ts` — query-scoped coverage for search and query (`_meta.retrieval.coverage`). `coverageRelevance` says what makes a pending or held item relevant (a returned page, a result or `types` type, a query word in title, slug or path; an empty result counts all); `countPendingProjections` (the probe's pending class) and `countEmbeddingHeld` (pages whose budget row still applies, `budgetRowAppliesFilter` only) count in the readiness scope, one statement each, capped at `COVERAGE_COUNT_CAP` (1000, `capped`), null on failure (never zero). Held files are counted by `persistence/held-reads.ts`.
+- `src/core/search/retrieval-coverage.ts` — query-scoped coverage for search and query (`_meta.retrieval.coverage`). `coverageRelevance` says what makes a pending or held item relevant (a returned page, a result or `types` type, a query word in title, slug or path; an empty result counts all); `countPendingProjections` (the probe's pending class) and `countEmbeddingHeld` (pages whose budget row still applies per `budgetRowAppliesFilter`, minus `embed_skip` pages that no embed path releases) count in the readiness scope, one statement each, capped at `COVERAGE_COUNT_CAP` (1000, `capped`), null on failure (never zero). Held files are counted by `persistence/held-reads.ts`.
- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.
- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. `search.long_page_unit` (F2, default `off`): `withLongPagePolicy` (called only by the `search`/`query` caller, so recall, think and `assemble_evidence` never carry it) sets `plan.longPage` (unit plus `search.long_page_min_chars`, default 20,000) under an implied `auto` with no explicit budget (`snippet_chars` does not turn it off; `capDeliveredSnippets` skips `reason: long_page` rows and cuts every other row); `selectLongPages` runs one character/byte-count preflight under the read scope (long = stored body at least `minChars` characters, confirmed on the rendered `pageEvidenceText` at delivery; at most `LONG_PAGE_MAX_PAGES` 5 and `LONG_PAGE_MAX_INPUT_BYTES` 1,000,000, whole pages only; `LONG_PAGE_DEADLINE_MS` 2,000 for preflight plus fetch) and returns exactly `effectivePlan` when no page is long; `deliverEvidence` fetches the selected pages in their own bounded `getChunkWindows` call, delivers them in the unit with `reason: long_page`, and returns any it cannot deliver (limits, deadline, fetch failure, over budget) as their ranked chunk with `reason: long_page_chunk` and a `long_page_*` fallback. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`. Large pages: a `page` (or auto→page) unit over 256 KB is delivered as a window with `fallback_reason: page_over_inline_bytes`; above 1 MiB, hits are located only by stored spans (`locateChunksByStoredSpans`) and the anchor fallback never whitespace-folds the whole text. A segmented page (Wave B PR 2) is planned by `planSegmentedBlock` from the windows `segmented-evidence.ts` reads around its hits, one run per window (emission marks the gap between runs, a section never crosses one); no page text, whole-page projection or `locateChunks` runs for it, and a failed segment read falls back to the hit chunk (`segment_read_failed`, live hits only).
diff --git a/src/core/search/retrieval-coverage.ts b/src/core/search/retrieval-coverage.ts
index e5e7cf9cf5..263c87634f 100644
--- a/src/core/search/retrieval-coverage.ts
+++ b/src/core/search/retrieval-coverage.ts
@@ -106,7 +106,8 @@ export function countPendingProjections(engine: Pick<BrainEngine, 'executeRaw'>,
`p.text_projection_revision IS DISTINCT FROM p.knowledge_revision AND ${projectionClassSql('p', 's')} NOT IN ('protected','archived')`);
}
-/** Pages in scope held from embedding: a held or capped budget row that still applies. */
+/** Pages in scope held from embedding: a held or capped budget row that still applies, on a page no `embed_skip` marker keeps out of embedding for good. */
export function countEmbeddingHeld(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance): Promise<ScopedCount | null> {
- return countInScope(engine, scope, relevance, 'JOIN page_embedding_budget b ON b.page_id = p.id', budgetRowAppliesFilter('b', 'p'));
+ return countInScope(engine, scope, relevance, 'JOIN page_embedding_budget b ON b.page_id = p.id',
+ `${budgetRowAppliesFilter('b', 'p')} AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);
}
diff --git a/test/retrieval-coverage-notices.test.ts b/test/retrieval-coverage-notices.test.ts
index af4723a1e3..06cb8ec8ad 100644
--- a/test/retrieval-coverage-notices.test.ts
+++ b/test/retrieval-coverage-notices.test.ts
@@ -44,9 +44,11 @@ const pending = (slug: string, sourceId = 'default') =>
engine.executeRaw('UPDATE pages SET text_projection_revision = NULL WHERE slug = $1 AND source_id = $2', [slug, sourceId]);
/** A large page (over the inline limit) whose embedding budget is held: no vectors. */
-async function embeddingHeldPage(sourceId: string, slug: string, type: string, title: string) {
+async function embeddingHeldPage(sourceId: string, slug: string, type: string, title: string, embedSkip: string | null = null) {
await page(slug, type, title, 'a long recording transcript', sourceId);
- await engine.executeRaw(`UPDATE pages SET compiled_truth = repeat('x', 1100000) WHERE slug = $1 AND source_id = $2`, [slug, sourceId]);
+ await engine.executeRaw(`UPDATE pages SET compiled_truth = repeat('x', 1100000),
+ frontmatter = CASE WHEN $3::text IS NULL THEN frontmatter ELSE COALESCE(frontmatter, '{}'::jsonb) || jsonb_build_object('embed_skip', $3::text) END
+ WHERE slug = $1 AND source_id = $2`, [slug, sourceId, embedSkip]);
await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE slug = $1 AND source_id = $2', [slug, sourceId]);
await engine.executeRaw(`INSERT INTO page_embedding_budget(page_id, state, reason) SELECT id, 'held', 'upgrade_backfill' FROM pages WHERE slug = $1 AND source_id = $2`, [slug, sourceId]);
}
@@ -187,6 +189,18 @@ describe('pages held from embedding are named in coverage and the held_files lin
expect(notice.why).toContain('1 of them could match this query');
expect(notice.fix).toMatchObject({ argv: ['gbrain', 'embed', '--held', '--dry-run'], actor: 'agent' });
}));
+
+ test('an embed_skip page with an applying budget row is not counted: no embedding path releases it', eachEngine(async () => {
+ await embeddingHeldPage('embed-a', 'notes/acme-example-renewal-held', 'note', 'Acme-example renewal held');
+ const before = call('embed-a');
+ await search.handler(before.ctx, { query: QUERY });
+ const counted = before.meta.retrieval.coverage;
+ expect(counted.could_affect.embedding_held).toBeGreaterThan(0);
+ await embeddingHeldPage('embed-a', 'notes/acme-example-renewal-skipped', 'note', 'Acme-example renewal skipped', 'content_sanity');
+ const c = call('embed-a');
+ await search.handler(c.ctx, { query: QUERY });
+ expect(c.meta.retrieval.coverage).toEqual(counted);
+ }));
});
describe('repeat suppression and worsening (session ledger)', () => {