Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
19.0 KB
Raw Blame
/**
 * hybridSearch pipeline stages (refactor wave 1, W4 hybrid): the two keyword-only return paths (no embedding provider; every vector arm empty).
 * Each stage reads the resolved request (HybridRequest, request.ts) and
 * writes its per-request accumulators only as `req.<field>`.
 */
import { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';
import type { LexicalArms } from './arms.ts';
import { applyFeedbackStage } from '../feedback-boost.ts';
import { type PostFusionOpts, RRF_K, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions } from '../hybrid.ts';
import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';
import type { SearchResult } from '../../types.ts';
import type { FusionListEntry } from '../fusion-lists.ts';
import { applyAliasHop } from '../alias-hop.ts';
import { applyExactLookupTier } from '../exact-lookup.ts';
import { dedupResults, segmentRegions } from '../dedup.ts';
import { enforceTokenBudget } from '../token-budget.ts';
import { isTimeoutError, pushDegraded, stampBudgetStage } from './degraded.ts';
import { markKeywordHits, stampEvidence } from '../evidence.ts';
import { applyEvidenceGate, gateFillRows } from '../decide-stage.ts';
import { isKeywordSkippedAfterTimeout } from '../../postgres-engine/keyword-timeout-cache.ts';
import { collapsePool, prioritize } from './rank.ts';
import { readGeneratedPages } from '../provenance-demotion.ts';
import { warnOncePerProcess } from '../../utils.ts';
import { hasCJK } from '../../cjk.ts';
import { clampSearchLimit } from '../../engine.ts';
import { searchLimitCap } from '../eval-pool-depth.ts';

const pagesOf = (r: SearchResult) => [r.slug, ...(r.collapsed ?? []).map(c => c.slug), ...(r.redirect_to ? [r.redirect_to] : [])].map(slug => `${r.source_id ?? 'default'}:${slug}`);

/**
 * The keyless path's row stages, from the arms' rows to the pool the evidence
 * gate reads. `held` is empty for the request's own rows. The any-word fill
 * (GST-2762) calls it again with the page so far as `held`, so its rows pass
 * the same stages and never repeat a held page.
 */
async function keylessRowStages(
  req: HybridRequest,
  { keywordResults, titleResults, exactLookupOpts }: LexicalArms,
  relationalList: SearchResult[],
  postFusionOpts: PostFusionOpts,
  held: SearchResult[],
): Promise<SearchResult[]> {
  const { engine, query, opts, resolvedMode, ctBoost, aliasHopOpts } = req;
  // v0.43 — fuse the relational arm with keyword so typed-edge answers
  // survive on the no-embedding-provider path (the relational win is most
  // valuable exactly when vector is unavailable). The title arm fuses here
  // too — an exact-title lookup on a keyless install is precisely where
  // chunk-grain keyword FTS alone fails (D1).
  // issue #160: stamp unverified stubs BEFORE fusion so the compiled-truth
  // boost skips them (flag survives fusion's result spread).
  await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);
  let noEmbedResults = keywordResults;
  const trace = held.length ? undefined : opts?.explainTarget;
  if (trace) {
    trace.observe('arm:keyword', keywordResults);
    trace.observe('arm:title', titleResults);
    trace.observe('arm:relational', relationalList);
  }
  if (relationalList.length > 0 || titleResults.length > 0) {
    const fk = opts?.rrfK ?? RRF_K;
    const noEmbedLists: FusionListEntry[] = [{ list: keywordResults, k: fk, arm: 'keyword' }];
    if (titleResults.length > 0) noEmbedLists.push({ list: titleResults, k: fk, arm: 'title' });
    if (relationalList.length > 0) noEmbedLists.push({ list: relationalList, k: fk, arm: 'relational' });
    noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost, opts?.explain === true || trace !== undefined);
  }
  if (noEmbedResults.length > 0) {
    const generatedRead = readGeneratedPages(engine, noEmbedResults);
    await runPostFusionStages(engine, noEmbedResults, postFusionOpts);
    await applyIdentityBoosts(req, noEmbedResults, generatedRead);
    noEmbedResults.sort((a, b) => b.score - a.score);
    noEmbedResults = await applyFeedbackStage(engine, noEmbedResults, { reranked: false });
  }
  // T3/T4 — alias hop + evidence stamp even without an embedding provider
  // (the named-thing fix is most valuable exactly when vector is unavailable).
  trace?.observe('fused', noEmbedResults);
  // Dedup and collapse see the held rows, so a fill row that repeats, redirects to or copies a held page folds away; only rows that touch no held page go on.
  const heldPages = new Set(held.flatMap(pagesOf));
  const own = (rows: SearchResult[]) => held.length ? rows.filter(r => !pagesOf(r).some(k => heldPages.has(k))) : rows;
  const pooled = held.length ? [...held, ...noEmbedResults] : noEmbedResults;
  const noEmbedDeduped = prioritize(req, own(await collapsePool(req, dedupResults(pooled, { regions: await segmentRegions(engine, pooled) }))));
  trace?.observe('deduped', noEmbedDeduped);
  const noEmbedPreExact = await applyAliasHop(engine, noEmbedDeduped, query, aliasHopOpts);
  // #1663 — structural exact-lookup tier (slug / exact-title identity).
  const noEmbedExact = own(await applyExactLookupTier(engine, noEmbedPreExact, query, exactLookupOpts));
  const noEmbedHopped = own(await collapsePool(req, held.length ? [...held, ...noEmbedExact] : noEmbedExact));
  stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
  return noEmbedHopped;
}

/**
 * GST-2762: on a brain with no embedding provider, a first page the all-words
 * rows leave short is filled with pages that hold only some of the words. The
 * fill rows come from the keyword arm's own statement (SearchOpts.orFill), go
 * through keylessRowStages behind the page so far and through the evidence
 * gate's request (gateFillRows), and are returned to be appended: scored at or
 * below the page's lowest row, marked keyword_fill, never more than the empty
 * slots. A failed fetch or a check that did not judge them adds nothing and
 * reports keyword_candidates_incomplete. Only callers that pass
 * HybridSearchOpts.anyWordFill (the search and query operations) get it.
 *
 * Invariant (pinned by the property tests in test/search/keyless-any-word-fill.test.ts):
 * with the fill on, the response begins with exactly the rows the fill-off
 * response returns, here and at the search and query operations (chooseFill in
 * ops/search.ts), and a fill row passes every stage a normal row passes,
 * visibility and source scope included.
 */
async function anyWordFill(req: HybridRequest, lexical: LexicalArms, postFusionOpts: PostFusionOpts, pool: SearchResult[]): Promise<SearchResult[]> {
  const { engine, query, opts, limit, offset, degraded, searchOpts } = req;
  const { earlyModality, keywordResults } = lexical;
  const room = limit - pool.length;
  // Only a caller that asked gets the fill, and a Chinese, Japanese or Korean question has no any-word form: its keyword arm already matches term by term.
  if (opts?.anyWordFill !== true || hasCJK(query)) return [];
  if (opts?.decide?.keywordOnly || offset > 0 || room <= 0 || earlyModality === 'image') return [];
  if (keywordResults.length === 0 || keywordResults.some(r => r.keyword_relaxed) || keywordResults.length >= (searchOpts.limit ?? Infinity)) return [];
  const heldPages = new Set(pool.flatMap(pagesOf));
  let candidates: SearchResult[];
  try {
    const anyWord = await engine.searchKeyword(query, { ...searchOpts, ...(opts?.useCache === false ? {} : { keywordTimeoutCache: true }), orFill: true });
    // Pages the keyword arm returned are left out, the rest fit the arm's limit, each scored below the arm's lowest row.
    const armPages = new Set(keywordResults.map(r => r.page_id));
    const floor = Math.min(...keywordResults.map(r => r.score));
    const top = Math.max(...anyWord.map(r => r.score));
    candidates = anyWord.filter(r => r.keyword_fill === true && !armPages.has(r.page_id)).slice(0, clampSearchLimit(searchOpts.limit, 20, searchLimitCap()) - keywordResults.length)
      .map(r => ({ ...r, score: floor * 0.5 * (top > 0 ? r.score / top : 1) })).filter(r => !heldPages.has(pagesOf(r)[0]!));
  } catch (err) {
    pushDegraded(degraded, 'keyword_candidates_incomplete', isTimeoutError(err) || isKeywordSkippedAfterTimeout(err) ? 'timeout' : 'provider_error');
    return [];
  }
  if (candidates.length === 0) return [];
  // GST-2786: a fault in the fill's own stages or checks withholds the fill; the page keeps the rows it had without it.
  let judged: SearchResult[] | null;
  try {
    markKeywordHits(candidates);
    const staged = await keylessRowStages(req, { ...lexical, keywordResults: candidates, titleResults: [] }, [], postFusionOpts, pool);
    let ceiling = Math.min(Infinity, ...pool.map(r => r.score).filter(Number.isFinite));
    const marked = staged.map(r => {
      const cap = ceiling > 0 ? ceiling * 0.99 : ceiling;
      ceiling = Number.isFinite(r.score) ? Math.min(r.score, cap) : Number.isFinite(cap) ? cap : 0;
      return { ...r, keyword_fill: true as const, score: ceiling };
    });
    judged = await gateFillRows(req.decide, query, marked, pool.length);
  } catch {
    judged = null;
  }
  if (judged === null) {
    pushDegraded(degraded, 'keyword_candidates_incomplete', 'provider_error');
    return [];
  }
  const fill = judged.slice(0, room);
  opts?.explainTarget?.observe('arm:keyword_fill', fill);
  return fill;
}

/** No embedding provider (and no multimodal route): keyword + title + relational only. */
export async function searchWithoutEmbeddings(
  req: HybridRequest,
  lexical: LexicalArms,
  relationalList: SearchResult[],
  postFusionOpts: PostFusionOpts,
  providerProbe: string | undefined,
): Promise<SearchResult[]> {
  const { engine, query, opts, resolvedMode, resolvedCol, limit, offset, suggestions, detailResolved, degraded } = req;
  const { earlyModality, keywordResults } = lexical;
  const trace = opts?.explainTarget;
  const noEmbedHopped = await keylessRowStages(req, lexical, relationalList, postFusionOpts, []);
  // System One S3 evidence gate (no-op when the slot is off), at the fused path's position.
  const noEmbedGated = await applyEvidenceGate(req.decide, query, noEmbedHopped);
  // #3995 — guaranteed page-1 relational evidence: a fired arm's answer is
  // often lexically unrecoverable, so its single-arm fused row can land
  // beyond the limit slice on keyword-heavy corpora. Promote/inject before
  // slicing (first page only; pure no-op when the arm didn't fire).
  let noEmbedPool = noEmbedGated;
  let noEmbedRelSlot: RelationalEvidenceSlotDecision | undefined;
  if (relationalList.length > 0) {
    const r = ensureRelationalEvidenceSlot(noEmbedGated, relationalList, limit, offset, {
      cosineFloor: resolvedMode.evidence_cosine_floor,
    }, resolvedMode.relational_chain_slots);
    noEmbedPool = r.pool;
    noEmbedRelSlot = r.decision;
  }
  const noEmbedFill = await anyWordFill(req, lexical, postFusionOpts, noEmbedPool);
  if (noEmbedFill.length > 0) noEmbedPool = [...noEmbedPool, ...noEmbedFill];
  trace?.observe('return_pool', noEmbedPool);
  const noEmbedSliced = noEmbedPool.slice(offset, offset + limit);
  trace?.observe('limit_slice', noEmbedSliced);
  // v0.32.3 search-lite: budget enforcement on the no-embedding-provider path.
  const { results: noEmbedBudgeted, meta: noEmbedBudgetMeta } = enforceTokenBudget(noEmbedSliced, resolvedMode.tokenBudget);
  trace?.observe('token_budget', noEmbedBudgeted);
  await stampContentFlags(engine, noEmbedBudgeted, opts);
  req.lastResultsCount = noEmbedBudgeted.length;
  req.lastRank1Score = noEmbedBudgeted[0] ? (noEmbedBudgeted[0].base_score ?? noEmbedBudgeted[0].score) : undefined;
  // WP2/T3 — no silent bypass: the keyword-only-config branch names why
  // vector didn't run, and whether the keyword arm itself came up empty
  // (skipped-by-modality is not a keyword miss, hence the image gate).
  // System One S6 fire retrieval asks for keyword-only on purpose: vector is not degraded.
  if (!opts?.decide?.keywordOnly && opts?._embeddingOptedOut) {
    // The brain opted out of embedding: keyword-only by choice, and the query text never left the brain.
    pushDegraded(degraded, 'embed_unavailable', 'embedding_disabled');
    warnOncePerProcess(
      'search-vector-leg-opted-out',
      '[gbrain] embeddings are off on this brain by choice (embedding_disabled), so search is keyword-only and no query text is sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.',
    );
  } else if (!opts?.decide?.keywordOnly) {
    pushDegraded(degraded, 'embed_unavailable', 'no_provider');
    // #3808: meta names the degradation for programmatic callers, but a CLI
    // human never saw it — mirror the embed-failure warn (once per process,
    // stderr) with the diagnose reason so a silently keyword-only brain is
    // visible the first time it ships results.
    try {
      const { diagnoseEmbedding } = await import('../../ai/gateway.ts');
      const diag = diagnoseEmbedding(providerProbe);
      const reason = diag.ok ? 'provider_unreachable' : (diag.reason ?? 'provider_unreachable');
      warnOncePerProcess(
        'search-vector-leg-unavailable',
        `[gbrain] vector search unavailable (${reason}) — results are keyword-only. Run \`gbrain doctor\` to diagnose.`,
      );
    } catch {
      // Fail-open like every sibling stage: the warning is best-effort and a
      // gateway import/diagnose throw must never fail the already-computed
      // keyword-only degraded results it exists to explain.
    }
  }
  if (keywordResults.length === 0 && earlyModality !== 'image') {
    pushDegraded(degraded, 'keyword_zero');
  }
  stampBudgetStage(degraded, noEmbedBudgetMeta);
  emitHybridMeta(req, {
    vector_enabled: false,
    detail_resolved: detailResolved,
    expansion_applied: false,
    intent: suggestions.intent,
    mode: resolvedMode.resolved_mode,
    embedding_column: resolvedCol.name,
    degraded: [...degraded],
    retrieved_count: noEmbedSliced.length,
    ...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0
      ? { token_budget: noEmbedBudgetMeta }
      : {}),
    ...(noEmbedRelSlot ? { relational_evidence_slot: noEmbedRelSlot } : {}),
  });
  return noEmbedBudgeted;
}

/** Every vector arm came back empty or failed: keyword fallback. */
export async function searchVectorFallback(
  req: HybridRequest,
  { earlyModality, keywordResults, titleResults, exactLookupOpts }: LexicalArms,
  relationalList: SearchResult[],
  postFusionOpts: PostFusionOpts,
): Promise<SearchResult[]> {
  const { engine, query, opts, resolvedMode, resolvedCol, limit, offset, suggestions, detailResolved, ctBoost, aliasHopOpts, degraded } = req;
  // Embed/vector failed silently; record that vector did not run.
  // v0.29.1 codex pass-2 #4: this is the third return path. Apply
  // post-fusion stages here too — without it, salience='on' silently
  // does nothing on embed failures.
  // v0.43: fuse the relational arm with keyword via RRF so typed-edge
  // answers survive even when vector is unavailable. The title arm fuses
  // here too (same rationale as the no-embedding-provider path — D1).
  // issue #160: stamp unverified stubs BEFORE fusion (see the
  // no-embedding-provider path for rationale).
  await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);
  let fallbackResults = keywordResults;
  const trace = opts?.explainTarget;
  if (trace) {
    trace.observe('arm:keyword', keywordResults);
    trace.observe('arm:title', titleResults);
    trace.observe('arm:relational', relationalList);
  }
  if (relationalList.length > 0 || titleResults.length > 0) {
    const fk = opts?.rrfK ?? RRF_K;
    const fallbackLists: FusionListEntry[] = [{ list: keywordResults, k: fk, arm: 'keyword' }];
    if (titleResults.length > 0) fallbackLists.push({ list: titleResults, k: fk, arm: 'title' });
    if (relationalList.length > 0) fallbackLists.push({ list: relationalList, k: fk, arm: 'relational' });
    fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost, opts?.explain === true || trace !== undefined);
  }
  if (fallbackResults.length > 0) {
    const generatedRead = readGeneratedPages(engine, fallbackResults);
    await runPostFusionStages(engine, fallbackResults, postFusionOpts);
    await applyIdentityBoosts(req, fallbackResults, generatedRead);
    fallbackResults.sort((a, b) => b.score - a.score);
    fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });
  }
  trace?.observe('fused', fallbackResults);
  const kwDeduped = prioritize(req, await collapsePool(req, dedupResults(fallbackResults, { regions: await segmentRegions(engine, fallbackResults) })));
  trace?.observe('deduped', kwDeduped);
  const kwPreExact = await applyAliasHop(engine, kwDeduped, query, aliasHopOpts);
  // #1663 — structural exact-lookup tier (slug / exact-title identity).
  const kwHopped = await collapsePool(req, await applyExactLookupTier(engine, kwPreExact, query, exactLookupOpts));
  stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
  // System One S3 evidence gate (no-op when the slot is off), at the fused path's position.
  const kwGated = await applyEvidenceGate(req.decide, query, kwHopped);
  // #3995 — the same guaranteed page-1 relational evidence as the other two
  // return paths: a vector failure must not drop a fired arm's answer.
  let kwPool = kwGated;
  let kwRelSlot: RelationalEvidenceSlotDecision | undefined;
  if (relationalList.length > 0) {
    const r = ensureRelationalEvidenceSlot(kwGated, relationalList, limit, offset, { cosineFloor: resolvedMode.evidence_cosine_floor }, resolvedMode.relational_chain_slots);
    kwPool = r.pool;
    kwRelSlot = r.decision;
  }
  trace?.observe('return_pool', kwPool);
  const kwSliced = kwPool.slice(offset, offset + limit);
  trace?.observe('limit_slice', kwSliced);
  // v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.
  const { results: kwBudgeted, meta: kwBudgetMeta } = enforceTokenBudget(kwSliced, resolvedMode.tokenBudget);
  trace?.observe('token_budget', kwBudgeted);
  await stampContentFlags(engine, kwBudgeted, opts);
  req.lastResultsCount = kwBudgeted.length;
  req.lastRank1Score = kwBudgeted[0] ? (kwBudgeted[0].base_score ?? kwBudgeted[0].score) : undefined;
  // WP2/T3 — the embed/vector failure that emptied vectorArms already
  // pushed its stage above; add the keyword-arm outcome (skipped-by-
  // modality is not a keyword miss, hence the image gate).
  if (keywordResults.length === 0 && earlyModality !== 'image') {
    pushDegraded(degraded, 'keyword_zero');
  }
  stampBudgetStage(degraded, kwBudgetMeta);
  emitHybridMeta(req, {
    vector_enabled: false,
    detail_resolved: detailResolved,
    expansion_applied: req.expansionApplied,
    intent: suggestions.intent,
    mode: resolvedMode.resolved_mode,
    embedding_column: resolvedCol.name,
    degraded: [...degraded],
    retrieved_count: kwSliced.length,
    ...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0
      ? { token_budget: kwBudgetMeta }
      : {}),
    ...(kwRelSlot ? { relational_evidence_slot: kwRelSlot } : {}),
  });
  return kwBudgeted;
}