Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/gbra151-notices-get-slices
garrytanf17b18aa0df9
diff --cc docs/architecture/key-files/core-search-2.mdindex a81c2584a2,887a2a62f8..25e7d1dd70--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@@ -7,7 -7,6 +7,7 @@@ Current behavior and load-bearing invar- `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 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/retrieval-coverage.ts` — query-scoped `_meta.retrieval.coverage`: relevant pending and held counts, capped, null on failure.- `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 --cc src/cli/main.tsindex fa717e7b63,cd39ec2996..baeb2941d2--- a/src/cli/main.ts+++ b/src/cli/main.ts@@@ -77,8 -77,8 +77,9 @@@ importtype CliDispatchContext,} from './command-table.ts';import { formatRememberResult } from './remember-format.ts';-import { applyCliOpNotices, captureCapacityNotices, captureOpNotice, captureRetrievalNotices } from './op-notices.ts';+import { applyCliOpNotices, captureCapacityNotices, captureOpNotice, captureRetrievalNotices, retrievalIncompleteLine } from './op-notices.ts';+import { admitAcrossCliCalls } from '../core/notice-ledger.ts';+ import { searchTimingsDocument, searchTimingsLine, timeCliPhase } from './search-timings.ts';// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as adiff --cc src/core/ops/search.tsindex db002f8182,7b1a987b8a..17fb879c64--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@@ -439,23 -437,20 +444,25 @@@ async function buildRetrievalResponseMeconst excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);const excludeSlugPrefixes = resolveHardExcludes();const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);+ const relevance = coverageRelevance(results as SearchResult[], queryText, opts.types, FACT_MATCH_STOPWORDS);+ const readinessScope = { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes };// #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, pending], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld] = await Promise.all([- const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles, sourceFreshness, filterNotice] = await Promise.all([++ const [safeIndexPending, [readiness, pending], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld, filterNotice] = await Promise.all([ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),- probeProjectionReadiness(ctx.engine, { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes }),+ probeProjectionReadiness(ctx.engine, readinessScope).then(async r =>+ [r, r.status === 'projection_pending' ? await countPendingProjections(ctx.engine, readinessScope, relevance) : null] as const),// Facts saved about the entity the query names come first (newest first, one hop through entities they name).opts.entity && ctx.emitResponseMeta ? entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : [],matchingSavedFacts(ctx, scope, queryText, aliases),- stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []),+ stampHeldHits(ctx.engine, results as SearchResult[], scope, relevance, ctx).catch(() => ({ coverage: [], couldAffect: 0 })),// GBRA-133 PR 2a.5: per-source freshness from the notifier's cached coverage record (no git call).readSourceFreshness(ctx.engine, scope),+ countEmbeddingHeld(ctx.engine, readinessScope, relevance),+ opts.filterHintFor ? searchFilterHint(ctx, scope, excludePrivate, queryText, results as SearchResult[], opts.types, opts.filterHintFor) : null,]);+ const heldFiles = held.coverage;+ 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.diff --cc test/fixtures/goldens/cli/tools-json.jsonindex 0ee5197593,9672cc7ac4..257bbf7019--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@@ -2,8 -2,8 +2,8 @@@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 253415,- "stdoutSha256": "3e0e1e0f0e497886944151f27349e995ee3fd14df9526bc28e6f5f309e66bb2b",- "stdoutBytes": 253497,- "stdoutSha256": "20f59ef5300b32f55ca0d2378f7cc7eabd91200d64212dcdcddeef7fd27c4e15",++ "stdoutBytes": 254111,++ "stdoutSha256": "e8043920af2950bd095caa6cc393dd9a0843a9880ec6292a242f81be18cff4d5","toolNames": ["remember","entity",