Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search: multi-relation query planner and one-hop orientation

garrytan71de35b22d4c
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index acf203827e..9c6155bd70 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 2986 ratchet +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 P7 relationalChainHop delegate
src/core/postgres-engine.ts 2923 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); +4 P7 relationalChainHop delegate
src/core/search/hybrid.ts 1584 ratchet +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
-src/core/types.ts 2169 ratchet +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); +1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types
+src/core/types.ts 2201 ratchet +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); +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
src/core/minions/queue.ts 2523 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
src/commands/init.ts 1869 ratchet 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)
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)
@@ -36,9 +36,9 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1843 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts)
+src/core/config.ts 1848 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
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 663 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)
-src/core/search/mode.ts 1527 ratchet +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
+src/core/search/mode.ts 1594 ratchet +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)
src/commands/eval-longmemeval.ts 1518 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)
diff --git a/src/core/config.ts b/src/core/config.ts
index 9adde4eba6..f6b1dc373a 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1350,6 +1350,11 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.expansion_variant_budget',
// Ranker wave (R1): relational-arm rows re-pinned above reranked text rows (mode.ts reads; `off` | 0..10).
'search.relational_rerank_pin',
+ // Multi-hop planner (mode.ts reads; boolean) and typed one-hop orientation (boolean; unset follows the planner).
+ 'search.relational_planner',
+ 'search.relational_orient_onehop',
+ // Multi-hop chain slots: chain rows leading page 1 when a chain fired (mode.ts reads; 0..10).
+ 'search.relational_chain_slots',
// Ranker wave (Phase E2): keyword-arm confidence floor — weak keyword arm fuses at half weight (mode.ts reads; `off` | (0, 1]).
'search.keyword_arm_confidence_floor',
// Ranker wave (Phase E3): metadata boost gate — `lexical` skips post-fusion metadata boosts when the vector arm was the only voter (mode.ts reads; `always` | `lexical`).
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index ed7f07f2b0..12838fab55 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1,3 +1,5 @@
+import { parseRelationalPlan } from '../search/relational-plan.ts';
+import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
import { randomUUID } from 'node:crypto';
@@ -442,12 +444,7 @@ const recall: Operation = {
const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
if (!isAvailable('embedding')) {
- const raw = await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, requireSafeChunks: ctx.remote !== false, ...searchScope });
- searchResults = dedupResults(raw);
- // #3783 — direct FTS path: every row is a keyword hit by construction.
- markKeywordHits(searchResults);
- stampEvidenceSafe(searchResults);
- await stampContentFlags(ctx.engine, searchResults, { ...searchScope, excludePrivate });
+ searchResults = await keylessRecallRows(ctx, queryText, limit, excludePrivate, searchScope);
searchDegraded = 'keyword_only_no_embedding_provider';
} else {
searchResults = await hybridSearchCached(ctx.engine, queryText, {
@@ -1063,3 +1060,33 @@ export function parseTtlParam(raw: unknown): Date | null {
export const factsOperations: Operation[] = [
extract_facts, recall, context_pack, delta, forget_fact,
];
+
+/**
+ * Keyless recall's page arm: direct keyword FTS, except that a planned
+ * multi-relation question (planner on) goes through hybridSearch's keyless
+ * path, which runs keyword + title + the relational chain (zero LLM).
+ */
+async function keylessRecallRows(
+ ctx: OperationContext, queryText: string, limit: number, excludePrivate: boolean,
+ searchScope: { sourceId?: string; sourceIds?: string[] },
+): Promise<SearchResult[]> {
+ if (await keylessChainQuestion(ctx, queryText)) {
+ return hybridSearchCached(ctx.engine, queryText, {
+ limit, expansion: false, excludePrivate, requireSafeChunks: ctx.remote !== false,
+ takesHoldersAllowList: readHolders(ctx), ...searchScope,
+ });
+ }
+ const rows = dedupResults(await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, requireSafeChunks: ctx.remote !== false, ...searchScope }));
+ // #3783 — direct FTS path: every row is a keyword hit by construction.
+ markKeywordHits(rows);
+ stampEvidenceSafe(rows);
+ await stampContentFlags(ctx.engine, rows, { ...searchScope, excludePrivate });
+ return rows;
+}
+
+/** Keyless recall routes a planned multi-relation question through the relational chain when the planner is on. */
+async function keylessChainQuestion(ctx: OperationContext, queryText: string): Promise<boolean> {
+ if (parseRelationalPlan(queryText).kind !== 'plan') return false;
+ const modeInput = await loadSearchModeConfig(ctx.engine);
+ return resolveSearchMode({ mode: modeInput.mode, overrides: modeInput.overrides }).relational_planner;
+}
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index ecd2fb6e31..ac599a5235 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -1,3 +1,5 @@
+import type { RelationalPlanMeta } from '../search/relational-recall.ts';
+import type { Notice } from '../agent-output.ts';
import { readHolders } from './context.ts';
/**
* Search operation cluster (search + query) — pure move from operations.ts
@@ -434,6 +436,8 @@ async function buildRetrievalResponseMeta(
if (readiness.status !== 'ready') {
degraded.push({ stage: readiness.status === 'projection_pending' ? 'projection_pending' : 'projection_status_unknown' });
}
+ const planNotice = relationalPlanNotice(m?.relational_plan);
+ if (planNotice) ctx.emitNotice?.(planNotice);
return {
returned_count: results.length,
retrieved_count: m?.retrieved_count ?? results.length,
@@ -446,6 +450,7 @@ async function buildRetrievalResponseMeta(
...(m.decide ? { decide: m.decide } : {}),
...(m.rerank ? { rerank: m.rerank } : {}),
...(m.answerability ? { answerability: m.answerability } : {}),
+ ...(m.relational_plan ? { relational_plan: m.relational_plan } : {}),
} : {}),
...((m?.degraded !== undefined || degraded.length > 0) ? { degraded } : {}),
projection_readiness: readiness,
@@ -1231,3 +1236,27 @@ const cache_stats: Operation = {
export const searchOperations: Operation[] = [
search, query, assemble_evidence, search_stats, search_modes, search_tune, cache_stats,
];
+
+/**
+ * A multi-relation question whose chain did not produce answers gets a
+ * notice naming why and the next call, so the agent never reads ordinary
+ * results as "the graph has no answer".
+ */
+function relationalPlanNotice(plan: RelationalPlanMeta | undefined): Notice | null {
+ if (!plan || plan.status === 'fired') return null;
+ const base = { consent: [] as [], actor: 'agent' as const, requires_exclusive: false };
+ if (plan.status === 'unsupported') {
+ return { code: 'relational_chain', kind: 'degraded', why: `This question chains relationships in a way the planner does not run (${plan.reason ?? 'unsupported'}), so no graph answer is included; split it into one-relationship questions, or call traverse_graph with explicit hops.` };
+ }
+ if (plan.status === 'anchor_not_found') {
+ return { code: 'relational_chain', kind: 'degraded', why: `No page matches "${plan.anchor ?? ''}" in the searched sources, so the relationship chain did not run; the results are ordinary text matches.`,
+ fix: { ...base, mcp: { tool: 'search', arguments: { query: plan.anchor ?? '' } }, why: 'Find the entity page first, then ask again with its exact name (or call traverse_graph with its slug and explicit hops).' } };
+ }
+ if (plan.status === 'truncated') {
+ return { code: 'relational_chain', kind: 'info', why: `The relationship chain hit its ${plan.cap_hit?.cap ?? ''} cap at hop ${plan.cap_hit?.hop ?? '?'}, so lower-ranked answers were dropped; narrow the question or start from a more specific entity.` };
+ }
+ const hop = plan.empty_hop ?? 1;
+ const slug = plan.anchor_slugs?.[0];
+ return { code: 'relational_chain', kind: 'degraded', why: `Hop ${hop} of the relationship chain found no typed links${hop === 1 ? ` from "${plan.anchor ?? ''}"` : ''}; the relationship may only be written as plain mentions. The results are ordinary text matches.`,
+ ...(slug ? { fix: { ...base, mcp: { tool: 'traverse_graph', arguments: { slug, depth: 1 } }, why: 'A depth-1 walk shows what the start page is linked to.' } } : {}) };
+}
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index a52a61787e..25fba1a107 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -181,7 +181,12 @@ export async function buildRelationalList(req: HybridRequest): Promise<SearchRes
excludePrivate: opts?.excludePrivate,
requireSafeChunks: opts?.requireSafeChunks,
takesHoldersAllowList: opts?.takesHoldersAllowList,
- onMeta: opts?.onRelationalMeta,
+ planner: resolvedMode.relational_planner,
+ orientOneHop: resolvedMode.relational_orient_onehop ?? resolvedMode.relational_planner,
+ onMeta: (m) => {
+ if (m.plan) req.relationalPlan = m.plan;
+ opts?.onRelationalMeta?.(m);
+ },
});
}
return relationalList;
diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.ts
index 24cb84100d..ccd2ce7f97 100644
--- a/src/core/search/hybrid/cache-stages.ts
+++ b/src/core/search/hybrid/cache-stages.ts
@@ -5,6 +5,7 @@
* returns false), so on the production path only resolveCacheSearchMode and
* semanticCacheSkipped run.
*/
+import { normalizeChainSlots } from '../relational-chain.ts';
import type { BrainEngine } from '../../engine.ts';
import type { HybridSearchMeta, SearchResult } from '../../types.ts';
import { type HybridSearchOpts, cacheScopeKey, filterResultsByCallerScope } from '../hybrid.ts';
@@ -81,6 +82,10 @@ export async function resolveCacheSearchMode(engine: BrainEngine, opts: HybridSe
expansion_variant_budget: normalizeExpansionVariantBudget(opts?.expansionVariantBudget),
// Ranker wave — threaded here too so knobsHash's `rrp=` part reflects the per-call pin.
relational_rerank_pin: normalizeRelationalRerankPin(opts?.relationalRerankPin),
+ // Multi-hop planner — threaded here too so knobsHash's `rp=`/`ro=` parts reflect per-call values.
+ relational_planner: typeof opts?.relationalPlanner === 'boolean' ? opts.relationalPlanner : undefined,
+ relational_orient_onehop: typeof opts?.relationalOrientOneHop === 'boolean' ? opts.relationalOrientOneHop : undefined,
+ relational_chain_slots: normalizeChainSlots(opts?.relationalChainSlots),
// Ranker wave (Phase E2) — threaded here too so knobsHash's `kacf=` part reflects the per-call floor.
keyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),
// Ranker wave (Phase E3) — threaded here too so knobsHash's `mbg=` part reflects the per-call gate.
diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.ts
index b0a35cae25..400be3082f 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -64,7 +64,7 @@ export async function searchWithoutEmbeddings(
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;
}
@@ -161,7 +161,7 @@ export async function searchVectorFallback(
let kwPool = kwGated;
let kwRelSlot: RelationalEvidenceSlotDecision | undefined;
if (relationalList.length > 0) {
- const r = ensureRelationalEvidenceSlot(kwGated, relationalList, limit, offset, { cosineFloor: resolvedMode.evidence_cosine_floor });
+ const r = ensureRelationalEvidenceSlot(kwGated, relationalList, limit, offset, { cosineFloor: resolvedMode.evidence_cosine_floor }, resolvedMode.relational_chain_slots);
kwPool = r.pool;
kwRelSlot = r.decision;
}
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index c6f01df81b..63cde90942 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -23,7 +23,7 @@ import { applyAliasHop } from '../alias-hop.ts';
import { effectiveRrfK } from '../intent-weights.ts';
import { enforceTokenBudget } from '../token-budget.ts';
import { expandAnchors, hydrateChunks } from '../two-pass.ts';
-import { parseRelationalQuery } from '../relational-intent.ts';
+import { isRelationalQuery } from '../relational-plan.ts';
import { pushDegraded, stampBudgetStage } from './degraded.ts';
import { requiresSafeChunks } from '../safe-chunks.ts';
import { stampEvidence } from '../evidence.ts';
@@ -119,7 +119,7 @@ export async function fuseArms(
titleFusionList,
relationalList,
includeRelational: effectiveModality !== 'image',
- relationalQuery: parseRelationalQuery(query) !== null,
+ relationalQuery: isRelationalQuery(query, resolvedMode.relational_planner),
onKeywordArmConfidence: (d) => { keywordArmConfidence = d; },
ks: { vectorK, textRrfK, imageRrfK, keywordK, baseRrfK },
knobs: {
@@ -417,7 +417,7 @@ export async function sizeReturnPool(
if (relationalList.length > 0 && effectiveModality !== 'image') {
const r = ensureRelationalEvidenceSlot(returnPool, relationalList, limit, offset, {
cosineFloor: resolvedMode.evidence_cosine_floor,
- });
+ }, resolvedMode.relational_chain_slots);
returnPool = r.pool;
relationalSlotDecision = r.decision;
}
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 00849d620b..298231d95b 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -3,6 +3,7 @@
* Each stage reads the resolved request (HybridRequest, request.ts) and
* writes its per-request accumulators only as `req.<field>`.
*/
+import { normalizeChainSlots } from '../relational-chain.ts';
import type { BrainEngine } from '../../engine.ts';
import { perArmPoolLimit } from '../eval-pool-depth.ts';
import type { DegradedStageEntry, HybridSearchMeta, SearchOpts, SearchResult } from '../../types.ts';
@@ -16,7 +17,7 @@ import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';
import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';
import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';
import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';
-import { parseRelationalQuery } from '../relational-intent.ts';
+import { isRelationalQuery } from '../relational-plan.ts';
import { pushDegraded } from './degraded.ts';
import { recordSearchTelemetry } from '../telemetry.ts';
import { resolveBoostMap, resolveHardExcludes } from '../source-boost.ts';
@@ -64,6 +65,8 @@ export interface HybridRequest {
decide?: DecideSearchContext;
/** Set by the rerank stage when the System One reranker answered. */
rerankMeta?: { model_resolved: string };
+ /** Set by the relational arm when the multi-hop planner ran (meta.relational_plan). */
+ relationalPlan?: import('../relational-recall.ts').RelationalPlanMeta;
}
const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1';
@@ -124,6 +127,10 @@ export async function resolveHybridRequest(
// Ranker wave (R1) — relational rerank pin per-call thread-through (eval
// A/B); normalized through the ONE range contract (relational-rerank-pin.ts).
relational_rerank_pin: normalizeRelationalRerankPin(opts?.relationalRerankPin),
+ // Multi-hop planner + one-hop orientation per-call thread-through (eval A/B).
+ relational_planner: typeof opts?.relationalPlanner === 'boolean' ? opts.relationalPlanner : undefined,
+ relational_orient_onehop: typeof opts?.relationalOrientOneHop === 'boolean' ? opts.relationalOrientOneHop : undefined,
+ relational_chain_slots: normalizeChainSlots(opts?.relationalChainSlots),
// Ranker wave (Phase E2) — keyword-arm confidence floor per-call thread-through.
keyword_arm_confidence_floor: normalizeKeywordArmConfidenceFloor(opts?.keywordArmConfidenceFloor),
// Ranker wave (Phase E3) — metadata boost gate per-call thread-through (eval A/B).
@@ -284,14 +291,14 @@ export async function resolveHybridRequest(
// Intent identity boosts (exact/mentioned title or slug, mentioned alias),
// shared by the fused path and both keyword-only paths. Caller re-sorts.
export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult[]): Promise<void> {
- const { engine, query, opts, suggestions, intentWeightingOn, intentWeights } = req;
+ const { engine, query, opts, suggestions, intentWeightingOn, intentWeights, resolvedMode } = req;
if (intentWeights.exactMatchBoost === 1.0) {
// #4694: general and temporal questions still honor a multi-token
// title that is the query's subject. Not concept intent (Cat 13: a
// lexical title decoy is exactly what paraphrase probes must not
// reward) and not a relational question ("who invested in <title>"),
// whose answer is the pages linked to that title, not the title page.
- if (intentWeightingOn && suggestions.intent !== 'concept' && parseRelationalQuery(query) === null) {
+ if (intentWeightingOn && suggestions.intent !== 'concept' && !isRelationalQuery(query, resolvedMode.relational_planner)) {
applyTitleMentionBoost(list, query);
}
return;
@@ -314,8 +321,11 @@ export function emitHybridMeta(req: HybridRequest, rawMeta: HybridSearchMeta): v
const { engine, opts } = req;
const decide = decideMetaFor(req.decide);
const answerability = req.decide?.answerability;
- const meta: HybridSearchMeta = decide || req.rerankMeta || answerability
- ? { ...rawMeta, ...(decide ? { decide } : {}), ...(req.rerankMeta ? { rerank: req.rerankMeta } : {}), ...(answerability ? { answerability } : {}) }
+ const meta: HybridSearchMeta = decide || req.rerankMeta || answerability || req.relationalPlan
+ ? {
+ ...rawMeta, ...(decide ? { decide } : {}), ...(req.rerankMeta ? { rerank: req.rerankMeta } : {}),
+ ...(answerability ? { answerability } : {}), ...(req.relationalPlan ? { relational_plan: req.relationalPlan } : {}),
+ }
: rawMeta;
try {
opts?.onMeta?.(meta);
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 7c8f2542ca..899cfa8ed5 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -23,6 +23,7 @@
* embedding similarity. See `[CDX-4]` in the plan.
*/
+import { normalizeChainSlots } from './relational-chain.ts';
import { createHash } from 'crypto';
import { CR_MODES, type CRMode } from '../types.ts';
import { getFtsLanguage } from '../fts-language.ts';
@@ -357,6 +358,27 @@ export interface ModeBundle {
* autocut (`relational_pinned` stamp) and are excluded from its cliff math.
*/
relational_rerank_pin: number;
+ /**
+ * Multi-relation planner: questions that chain 2-3 typed relations ("who
+ * founded the companies Alice invested in?") walk typed hop chains
+ * (relational-plan.ts + relational-chain.ts). Also routes keyless `recall`
+ * relational questions through the relational arm. Override: per-call
+ * SearchOpts.relationalPlanner → `search.relational_planner` → bundle.
+ */
+ relational_planner: boolean;
+ /**
+ * Typed one-hop walks read edges stored from either page's side by the
+ * relation's type signature. `null` follows `relational_planner`. Override:
+ * per-call SearchOpts.relationalOrientOneHop → `search.relational_orient_onehop`.
+ */
+ relational_orient_onehop: boolean | null;
+ /**
+ * Chain slots: when a multi-hop chain fired, up to this many chain rows
+ * (answers, then their evidence pages) lead page 1. 0 = only the single
+ * page-1 evidence slot. Override: per-call SearchOpts.relationalChainSlots →
+ * `search.relational_chain_slots` (0..10).
+ */
+ relational_chain_slots: number;
/**
* Ranker wave (Phase E2, Cat 13) — arm-confidence-weighted fusion of the
* LEXICAL arms (arm-confidence.ts). When the keyword arm's scale-free
@@ -457,6 +479,10 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
relational_retrieval_depth: 2,
// Ranker wave (R1) — relational rows re-pinned above reranked text rows (0 = off).
relational_rerank_pin: DEFAULT_RELATIONAL_RERANK_PIN,
+ // Multi-hop planner: default set by its held-out eval (off until then).
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
autocut_jump: 0.2,
autocut_min_top: 0.35,
autocut_min_keep: 1,
@@ -519,6 +545,10 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
relational_retrieval_depth: 2,
// Ranker wave (R1) — relational rows re-pinned above reranked text rows (0 = off).
relational_rerank_pin: DEFAULT_RELATIONAL_RERANK_PIN,
+ // Multi-hop planner: default set by its held-out eval (off until then).
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
autocut_jump: 0.2,
autocut_min_top: 0.35,
autocut_min_keep: 1,
@@ -581,6 +611,10 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =
relational_retrieval_depth: 2,
// Ranker wave (R1) — relational rows re-pinned above reranked text rows (0 = off).
relational_rerank_pin: DEFAULT_RELATIONAL_RERANK_PIN,
+ // Multi-hop planner: default set by its held-out eval (off until then).
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
autocut_jump: 0.2,
autocut_min_top: 0.35,
autocut_min_keep: 1,
@@ -646,6 +680,9 @@ export interface SearchKeyOverrides {
relationalRetrieval?: boolean;
relational_retrieval_depth?: number;
relational_rerank_pin?: number;
+ relational_planner?: boolean;
+ relational_orient_onehop?: boolean | null;
+ relational_chain_slots?: number;
// Ranker wave (Phase E2) — keyword-arm confidence floor override (null = off; (0, 1]).
keyword_arm_confidence_floor?: number | null;
// Ranker wave (Phase E3) — metadata boost gate override (`always` | `lexical`).
@@ -710,6 +747,9 @@ export interface SearchPerCallOpts {
relational_retrieval_depth?: number;
// Ranker wave — relational rerank pin per-call override (0 = off; [0, 10]).
relational_rerank_pin?: number;
+ relational_planner?: boolean;
+ relational_orient_onehop?: boolean | null;
+ relational_chain_slots?: number;
// Ranker wave (Phase E2) — keyword-arm confidence floor per-call override (null = off; (0, 1]).
keyword_arm_confidence_floor?: number | null;
// Ranker wave (Phase E3) — metadata boost gate per-call override (`always` | `lexical`).
@@ -815,6 +855,9 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearch
relationalRetrieval: pick('relationalRetrieval'),
relational_retrieval_depth: pick('relational_retrieval_depth'),
relational_rerank_pin: pick('relational_rerank_pin'),
+ relational_planner: pick('relational_planner'),
+ relational_orient_onehop: pick('relational_orient_onehop'),
+ relational_chain_slots: pick('relational_chain_slots'),
keyword_arm_confidence_floor: pick('keyword_arm_confidence_floor'),
metadata_boost_gate: pick('metadata_boost_gate'),
resolved_mode,
@@ -1156,6 +1199,11 @@ export function knobsHash(
// System One (append-only, emitted only when a decide slot is not off, so
// the all-off key is unchanged and needs no version bump).
...(ctx?.decide ? [`dec=${ctx.decide}`] : []),
+ // Multi-hop planner (append-only, emitted only when on, so every
+ // planner-off key is unchanged and needs no version bump).
+ ...(knobs.relational_planner ? ['rp=1'] : []),
+ ...(knobs.relational_orient_onehop ?? knobs.relational_planner ? ['ro=1'] : []),
+ ...(knobs.relational_planner && knobs.relational_chain_slots ? [`rcs=${knobs.relational_chain_slots}`] : []),
];
// #5691 (append-only, no version bump): only a non-empty query prefix adds
// a part, so every row written without one keeps its key.
@@ -1382,6 +1430,13 @@ export function loadOverridesFromConfig(
const n = normalizeRelationalRerankPin(rrp);
if (n !== undefined) out.relational_rerank_pin = n;
}
+ // Multi-hop planner + one-hop orientation (booleans; anything else falls through).
+ const rp = parseBoolKnob(get('search.relational_planner'));
+ if (rp !== undefined) out.relational_planner = rp;
+ const roh = parseBoolKnob(get('search.relational_orient_onehop'));
+ if (roh !== undefined) out.relational_orient_onehop = roh;
+ const rcs = normalizeChainSlots(get('search.relational_chain_slots'));
+ if (rcs !== undefined) out.relational_chain_slots = rcs;
// Ranker wave (Phase E2) — keyword-arm confidence floor: the literal
// `off`/`null` pins the knob off (null); a number in (0, 1] is the floor;
// anything else falls through to the bundle. ONE range contract with the
@@ -1450,6 +1505,9 @@ export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Objec
relationalRetrieval: 'search.relational_retrieval',
relational_retrieval_depth: 'search.relational_retrieval_depth',
relational_rerank_pin: 'search.relational_rerank_pin',
+ relational_planner: 'search.relational_planner',
+ relational_orient_onehop: 'search.relational_orient_onehop',
+ relational_chain_slots: 'search.relational_chain_slots',
keyword_arm_confidence_floor: 'search.keyword_arm_confidence_floor',
metadata_boost_gate: 'search.metadata_boost_gate',
});
@@ -1525,3 +1583,12 @@ export async function loadSearchModeConfig(
...(decide ? { decide } : {}),
};
}
+
+/** `true`/`1`/`on` → true, `false`/`0`/`off` → false, anything else (or unset) → undefined. */
+function parseBoolKnob(v: string | undefined): boolean | undefined {
+ if (v === undefined) return undefined;
+ const l = v.trim().toLowerCase();
+ if (l === 'true' || l === '1' || l === 'on') return true;
+ if (l === 'false' || l === '0' || l === 'off') return false;
+ return undefined;
+}
diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.ts
index 9226278968..d9a90e57cd 100644
--- a/src/core/search/modes-report.ts
+++ b/src/core/search/modes-report.ts
@@ -60,6 +60,9 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {
relationalRetrieval: 'Typed-edge relational recall arm (relational queries walk the graph; no-op otherwise)',
relational_retrieval_depth: 'Max hops for relational traversal (1..3, 2 default)',
relational_rerank_pin: 'Relational-arm rows re-pinned above reranked text rows in fused order (0 = off; 0..10, 3 default)',
+ relational_planner: 'Multi-hop planner: questions chaining 2-3 typed relations walk typed hop chains with evidence (also keyless recall)',
+ relational_orient_onehop: 'Typed one-hop walks read edges written on either page by the relation type signature (null = follow relational_planner)',
+ relational_chain_slots: 'When a multi-hop chain fired, up to this many chain rows (answers, then evidence pages) lead page 1 (0..10; 0 = single evidence slot)',
// Ranker wave (Phase E2) arm-confidence fusion
keyword_arm_confidence_floor: 'Keyword-arm confidence floor: below this margin ratio the keyword + title lists fuse at half weight (null = off; (0, 1])',
// Ranker wave (Phase E3) metadata boost gate
diff --git a/src/core/search/relational-chain.ts b/src/core/search/relational-chain.ts
index bbb815faf4..8df5406aca 100644
--- a/src/core/search/relational-chain.ts
+++ b/src/core/search/relational-chain.ts
@@ -273,22 +273,28 @@ export async function runRelationalChain(
canonical_chunk_id: chunkIds.get(nodeKey(a.source_id, a.id)) ?? null,
});
}
- for (const a of answers) {
- const best = a.paths[0];
- best.ids.slice(1, -1).forEach((id, j) => push({
- source_id: a.source_id, slug: best.slugs[j + 1], page_id: id, role: 'support', hop: j + 1,
- path_count: 0, score: 0,
- best_path: { nodes: best.slugs.slice(0, j + 2), edges: best.edges.slice(0, j + 1).map(evidence) },
- canonical_chunk_id: chunkIds.get(nodeKey(a.source_id, id)) ?? null,
- }));
- best.edges.forEach((e, j) => {
- if (e.origin_page_id == null || e.origin_slug == null || best.ids.includes(e.origin_page_id)) return;
- push({
- source_id: a.source_id, slug: e.origin_slug, page_id: e.origin_page_id, role: 'origin', hop: j + 1,
- path_count: 0, score: 0, best_path: { nodes: [e.stored_from_slug, e.stored_to_slug], edges: [evidence(e)] },
- canonical_chunk_id: null,
+ // Evidence pages: every retained path of every answer (best paths first),
+ // so each answer's supporting pages are all present, not only its best path's.
+ const maxPaths = Math.max(...answers.map(a => a.paths.length));
+ for (let k = 0; k < maxPaths; k++) {
+ for (const a of answers) {
+ const path = a.paths[k];
+ if (!path) continue;
+ path.ids.slice(1, -1).forEach((id, j) => push({
+ source_id: a.source_id, slug: path.slugs[j + 1], page_id: id, role: 'support', hop: j + 1,
+ path_count: 0, score: 0,
+ best_path: { nodes: path.slugs.slice(0, j + 2), edges: path.edges.slice(0, j + 1).map(evidence) },
+ canonical_chunk_id: chunkIds.get(nodeKey(a.source_id, id)) ?? null,
+ }));
+ path.edges.forEach((e, j) => {
+ if (e.origin_page_id == null || e.origin_slug == null || path.ids.includes(e.origin_page_id)) return;
+ push({
+ source_id: a.source_id, slug: e.origin_slug, page_id: e.origin_page_id, role: 'origin', hop: j + 1,
+ path_count: 0, score: 0, best_path: { nodes: [e.stored_from_slug, e.stored_to_slug], edges: [evidence(e)] },
+ canonical_chunk_id: null,
+ });
});
- });
+ }
}
if (diagnostics.cap_hit) diagnostics.status = 'truncated';
return { rows, diagnostics };
@@ -351,3 +357,10 @@ export function validateChainHops(raw: unknown): { ok: true; hops: ChainHop[] }
}
export const MAX_CHAIN_HOPS = 3;
+
+/** Chain slots: an integer 0..10 (number or numeric string; `off` = 0); anything else → undefined (fall through). */
+export function normalizeChainSlots(v: unknown): number | undefined {
+ if (v === 'off' || v === false) return 0;
+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
+ return Number.isInteger(n) && n >= 0 && n <= 10 ? n : undefined;
+}
diff --git a/src/core/search/relational-plan.ts b/src/core/search/relational-plan.ts
new file mode 100644
index 0000000000..acc4f265fd
--- /dev/null
+++ b/src/core/search/relational-plan.ts
@@ -0,0 +1,316 @@
+/**
+ * Multi-relation query planner: turns a question that chains 2-3 typed
+ * relations ("Who founded the companies that Alice Example invested in?")
+ * into a chain plan over `links`. Pure: no DB, no LLM, deterministic.
+ *
+ * How it reads a question:
+ * 1. A bounded lexer splits the query into word tokens with spans (no regex
+ * runs over user text beyond a linear tokenizer).
+ * 2. Relation phrases are spotted longest-first from a fixed lexicon, each
+ * with its surface form: active verb ("invested in"), passive ("founded
+ * by"), agent noun ("investors of", "Acme's founders") or outgoing noun
+ * ("Alice's portfolio").
+ * 3. Fewer than two relations → `not_applicable` (single-relation questions
+ * stay on parseRelationalQuery, unchanged).
+ * 4. Everything that is not a relation, question word, auxiliary,
+ * determiner, relative pronoun, polite lead-in, head noun or marker must
+ * form exactly one contiguous span: the anchor entity. A pronoun right
+ * after a verb ("who founded THEM") points back at the previous step, so
+ * that verb reads with the chain on its right.
+ * 5. English nests the named entity innermost, so hops run from the
+ * relation nearest the anchor outward (noun forms bind tighter than verbs
+ * at equal distance). Each hop's direction follows from its form and the
+ * side the anchor is on: an active verb with the anchor on its left walks
+ * toward the object, on its right toward the subject; passive forms
+ * invert that; agent nouns walk toward the subject; outgoing nouns toward
+ * the object.
+ * 6. Consecutive hops must agree on the page type between them, and a
+ * "who"/"which companies" head must fit the last hop.
+ *
+ * Refused as `unsupported` (never answered with a one-hop guess): coordination
+ * or disjunction of relations (an "and" followed by a back-reference is a
+ * sequence, not coordination), negation, time constraints, comparatives,
+ * counting, quoted names, more than one candidate anchor, more than three
+ * hops, type-incoherent chains.
+ *
+ * Tested in test/relational-plan.test.ts.
+ */
+
+import { LINK_SIGNATURES, linkFamily, MAX_CHAIN_HOPS, type ChainHop } from './relational-chain.ts';
+import { parseRelationalQuery } from './relational-intent.ts';
+
+export interface RelationalPlan {
+ /** Raw anchor phrase, resolved to a page later (scope-aware). */
+ anchor: string;
+ /** Anchor-outward hops. */
+ hops: ChainHop[];
+ /** True for "other/else/also" questions and the co-relation shape. */
+ excludeAnchor: boolean;
+ /** Matched relation phrases in hop order, for explain. */
+ phrases: string[];
+}
+
+export type PlanResult =
+ | { kind: 'plan'; plan: RelationalPlan }
+ | { kind: 'not_applicable' }
+ | { kind: 'unsupported'; reason: string };
+
+type Form = 'verb' | 'passive' | 'agent' | 'out' | 'co';
+
+interface LexEntry {
+ words: string[];
+ rel: string;
+ form: Form;
+ /** Base-form verbs ("found", "back") count only after an auxiliary ("did X back"). */
+ needsAux?: boolean;
+}
+
+const w = (s: string) => s.split(' ');
+
+function entries(rel: string, form: Form, phrases: string[], needsAux = false): LexEntry[] {
+ return phrases.map(p => ({ words: w(p), rel, form, ...(needsAux ? { needsAux } : {}) }));
+}
+
+const LEXICON: LexEntry[] = [
+ // founded
+ ...entries('founded', 'verb', ['founded', 'co-founded', 'cofounded', 'started', 'founds', 'starts', 'established']),
+ ...entries('founded', 'verb', ['found', 'co-found', 'start'], true),
+ ...entries('founded', 'passive', ['founded by', 'co-founded by', 'cofounded by', 'started by', 'established by']),
+ ...entries('founded', 'out', ["'s startups", "'s startup", "'s ventures", "'s founded companies", "'s founded startups", "'s founded ventures",
+ "'s founded businesses", "'s founded firms"]),
+ ...entries('founded', 'agent', ['founder', 'founders', 'co-founder', 'co-founders', 'cofounder', 'cofounders', 'founding team']),
+ // invested_in
+ ...entries('invested_in', 'verb', ['invested in', 'invests in', 'has invested in', 'backed', 'backs', 'funded', 'funds', 'financed', 'finances', 'put money into', 'put money in']),
+ ...entries('invested_in', 'verb', ['invest in', 'invested', 'put money into', 'holds an investment in', 'holds investments in', 'hold an investment in',
+ 'holds a stake in', 'holds stakes in', 'hold stakes in', 'has money in', 'have money in', 'has a stake in', 'has stakes in', 'is an investor in',
+ 'are investors in', 'was an investor in', 'invested money in', 'provided investment to',
+ 'holds an investment', 'holds investments', 'holds a stake', 'holds stakes']),
+ ...entries('invested_in', 'verb', ['back', 'fund', 'finance'], true),
+ ...entries('invested_in', 'passive', ['backed by', 'funded by', 'financed by']),
+ ...entries('invested_in', 'agent', ['investor', 'investors', 'backer', 'backers', 'funder', 'funders', 'shareholders']),
+ ...entries('invested_in', 'out', ['portfolio', 'portfolio companies', 'portfolio company', 'investments']),
+ ...entries('invested_in', 'co', ['co-investor', 'co-investors', 'coinvestors']),
+ // advises
+ ...entries('advises', 'verb', ['advises', 'advised', 'advising']),
+ ...entries('advises', 'verb', ['advise', 'serves as an advisor', 'serves as advisor', 'serves as an advisor to', 'serves as an advisor for', 'serves as an advisor on', 'serves as advisor to',
+ 'serve as an advisor to', 'is an advisor to', 'is an adviser to', 'acts as an advisor to', 'is an advisor for']),
+ ...entries('advises', 'passive', ['advised by']),
+ ...entries('advises', 'agent', ['advisor', 'advisors', 'adviser', 'advisers', 'advisory board']),
+ // works_at
+ ...entries('works_at', 'verb', ['works at', 'worked at', 'works for', 'worked for', 'working at', 'working for', 'employed at', 'employed by', 'is on the team at']),
+ ...entries('works_at', 'verb', ['work at', 'work for']),
+ ...entries('works_at', 'agent', ['employee', 'employees', 'staff', 'team members']),
+ ...entries('works_at', 'out', ['employer', 'employers']),
+ // attended
+ ...entries('attended', 'verb', ['attended']),
+ ...entries('attended', 'verb', ['attend']),
+ ...entries('attended', 'passive', ['attended by']),
+ ...entries('attended', 'agent', ['attendees']),
+].sort((a, b) => b.words.length - a.words.length);
+
+const WH = new Set(['who', 'whom', 'which', 'what']);
+const AUX = new Set(['did', 'does', 'do', 'has', 'have', 'had', 'is', 'are', 'was', 'were']);
+const DO_AUX = new Set(['did', 'does', 'do', 'has', 'have', 'had']);
+const DETERMINERS = new Set(['the', 'a', 'an', 'all', 'any', 'their', 'its', 'his', 'her', 'each', 'every', 'some', 'those', 'these', 'same', 'them', 'they', 'it']);
+const RELATIVE = new Set(['that', 'which', 'who', 'whom']);
+const HEAD_LEAD = new Set(['among', 'of', 'our', 'my']);
+const PREPS = new Set(['of', 'in', 'at', 'behind', 'for', 'to', 'into', 'with']);
+const POLITE = new Set(['list', 'show', 'name', 'find', 'give', 'me', 'tell', 'please', 'us', 'could', 'can', 'would', 'you', 'i', 'know', 'want', 'like', 'wondering', 'curious', 'see']);
+/** Pronouns pointing back at the previous step's pages ("..., who founded THEM"). */
+const BACKREF = new Set(['them', 'those', 'these', 'they']);
+/** Head nouns that name no page type ("which other PARTIES invested ..."). */
+const GENERIC_HEADS = new Set(['parties', 'entities', 'ones', 'additional']);
+const OTHER_MARKERS = new Set(['other', 'others', 'else', 'also']);
+const HEAD_TYPES: Readonly<Record<string, string>> = {
+ people: 'person', person: 'person', persons: 'person', individuals: 'person', folks: 'person', angels: 'person',
+ companies: 'company', company: 'company', startups: 'company', startup: 'company', firms: 'company', firm: 'company',
+ businesses: 'company', organizations: 'company', funds: 'company', fund: 'company', vcs: 'company',
+ meetings: 'meeting', meeting: 'meeting', events: 'meeting',
+};
+const REFUSE: Readonly<Record<string, string>> = {
+ and: 'coordination', or: 'coordination', nor: 'coordination', but: 'coordination',
+ not: 'negation', never: 'negation', no: 'negation', without: 'negation', except: 'negation', "n't": 'negation',
+ before: 'time', after: 'time', since: 'time', during: 'time', until: 'time', ago: 'time', currently: 'time',
+ previously: 'time', recently: 'time', formerly: 'time', former: 'time', current: 'time', year: 'time', years: 'time',
+ most: 'comparative', more: 'comparative', least: 'comparative', fewest: 'comparative', top: 'comparative',
+ many: 'count', count: 'count', number: 'count',
+};
+
+interface Tok { text: string; lower: string; start: number; end: number }
+
+/** Linear tokenizer: words (letters, digits, hyphen, period inside names), possessive markers, punctuation dropped. */
+function tokenize(q: string): Tok[] {
+ const toks: Tok[] = [];
+ const re = /[\p{L}\p{N}][\p{L}\p{N}.&-]*|['’]s\b|['’]|["“”]/gu;
+ for (const m of q.matchAll(re)) {
+ let text = m[0];
+ let start = m.index!;
+ if (/^["“”]$/.test(text)) { toks.push({ text, lower: '"', start, end: start + 1 }); continue; }
+ if (text.endsWith('.')) text = text.replace(/\.+$/, '');
+ const lower = text.toLowerCase().replace('’', "'");
+ if (lower.endsWith("n't") && lower.length > 3) {
+ toks.push({ text: text.slice(0, -3), lower: lower.slice(0, -3), start, end: start + text.length - 3 });
+ start += text.length - 3;
+ toks.push({ text: "n't", lower: "n't", start, end: start + 3 });
+ continue;
+ }
+ toks.push({ text, lower: lower === "'s" || lower === "'" ? "'s" : lower, start, end: start + text.length });
+ }
+ return toks;
+}
+
+interface Rel { entry: LexEntry; from: number; to: number }
+
+/** Plan a multi-relation question, or say why not. */
+export function parseRelationalPlan(query: string): PlanResult {
+ if (!query || query.length > 512) return { kind: 'not_applicable' };
+ const toks = tokenize(query);
+ let lead = 0;
+ while (lead < toks.length && POLITE.has(toks[lead].lower)) lead++;
+ const hasAux = toks.some(t => AUX.has(t.lower));
+
+ const rels: Rel[] = [];
+ const used = new Array<boolean>(toks.length).fill(false);
+ for (let i = 0; i < toks.length; i++) {
+ if (used[i]) continue;
+ for (const e of LEXICON) {
+ if (i + e.words.length > toks.length) continue;
+ if (!e.words.every((word, j) => toks[i + j].lower === word)) continue;
+ if (e.needsAux && !hasAux) continue;
+ rels.push({ entry: e, from: i, to: i + e.words.length - 1 });
+ for (let j = i; j < i + e.words.length; j++) used[j] = true;
+ break;
+ }
+ }
+ // An agent noun right after the question word is the question's head, not a
+ // relation ("WHICH INVESTORS backed ...", "who among our FOUNDERS ...").
+ // "WHO are the founders of ..." asks for the relation, so a bare who/whom heads only with "among"/"of".
+ const headLead = toks.slice(lead, rels[0]?.from ?? lead);
+ if (rels.length > 0 && rels[0].entry.form === 'agent' && rels[0].from > lead && WH.has(toks[lead]?.lower)
+ && (!['who', 'whom'].includes(toks[lead].lower) || headLead.some(t => t.lower === 'among' || t.lower === 'of'))
+ && headLead.every(t => WH.has(t.lower) || DETERMINERS.has(t.lower) || OTHER_MARKERS.has(t.lower) || HEAD_LEAD.has(t.lower))) {
+ rels.shift();
+ }
+ // "the CO-INVESTORS in the companies X INVESTED IN": the co-relation already
+ // walks out and back over that relation, so its verb is not another hop.
+ const co = rels.find(r => r.entry.form === 'co');
+ if (co) for (let k = rels.length - 1; k >= 0; k--) if (rels[k] !== co && rels[k].entry.rel === co.entry.rel) rels.splice(k, 1);
+ const relCount = rels.reduce((n, r) => n + (r.entry.form === 'co' ? 2 : 1), 0);
+ if (relCount < 2) return { kind: 'not_applicable' };
+ if (toks.some(t => t.lower === '"')) return { kind: 'unsupported', reason: 'quoted names are not planned' };
+
+ for (const [i, t] of toks.entries()) {
+ if (t.lower === 'and' && toks.slice(i + 1).some(n => BACKREF.has(n.lower))) continue;
+ const why = REFUSE[t.lower] ?? (/^(1[89]|20)\d\d$/.test(t.lower) ? 'time' : undefined);
+ if (why) return { kind: 'unsupported', reason: `${why} constraints are not planned ("${t.text}")` };
+ }
+ if (toks.some((t, i) => t.lower === 'used' && toks[i + 1]?.lower === 'to')) return { kind: 'unsupported', reason: 'time constraints are not planned ("used to")' };
+ if (relCount > MAX_CHAIN_HOPS) return { kind: 'unsupported', reason: `more than ${MAX_CHAIN_HOPS} relations` };
+
+ // Classify every non-relation token; leftovers form the anchor.
+ let headType: string | null = null;
+ let excludeAnchor = false;
+ const leftover: number[] = [];
+ for (let i = 0; i < toks.length; i++) {
+ if (used[i]) continue;
+ const l = toks[i].lower;
+ if (OTHER_MARKERS.has(l)) { excludeAnchor = true; continue; }
+ if (l === "'s" || l === 'and' || GENERIC_HEADS.has(l)) continue;
+ if (WH.has(l) || AUX.has(l) || DETERMINERS.has(l) || RELATIVE.has(l) || PREPS.has(l) || POLITE.has(l) || l === 'by' || l === 'whose') {
+ if ((l === 'who' || l === 'whom') && headType === null && i === lead) headType = 'person';
+ continue;
+ }
+ if (HEAD_TYPES[l]) {
+ const leading = toks.slice(0, i).every(t => WH.has(t.lower) || POLITE.has(t.lower) || DETERMINERS.has(t.lower));
+ if (headType === null && leading) headType = HEAD_TYPES[l];
+ continue;
+ }
+ leftover.push(i);
+ }
+ if (leftover.length === 0) return { kind: 'unsupported', reason: 'no entity named' };
+ if (!leftover.every((idx, k) => k === 0 || idx === leftover[k - 1] + 1)) return { kind: 'unsupported', reason: 'more than one candidate entity' };
+ const aStart = leftover[0];
+ const aEnd = leftover[leftover.length - 1];
+ const anchor = query.slice(toks[aStart].start, toks[aEnd].end).trim();
+ if (anchor.length === 0 || anchor.length > 80) return { kind: 'unsupported', reason: 'entity name out of bounds' };
+ if (rels.some(r => r.from <= aEnd && r.to >= aStart)) return { kind: 'unsupported', reason: 'entity name overlaps a relation' };
+
+ // Order hops anchor-outward. The main-clause verb ("WHO founded ...",
+ // "which companies DID ... back") is always outermost; the rest order by
+ // how many content tokens separate them from the anchor, nouns binding
+ // tighter than verbs at equal distance.
+ const scaffold = (l: string) => WH.has(l) || AUX.has(l) || DETERMINERS.has(l) || POLITE.has(l) || OTHER_MARKERS.has(l) || GENERIC_HEADS.has(l) || HEAD_TYPES[l] !== undefined;
+ const isVerb = (r: Rel) => r.entry.form === 'verb' || r.entry.form === 'passive';
+ const startsWithWh = lead < toks.length && WH.has(toks[lead].lower);
+ // "which companies DID alice back": the auxiliary is followed by its subject,
+ // not by a relation ("which parties HAVE invested in" is perfect tense).
+ const auxInverted = startsWithWh && toks.slice(lead + 1, lead + 4).some((t, k) => DO_AUX.has(t.lower) && !used[lead + 2 + k]);
+ const lastRel = rels.reduce((a, b) => (b.from > a.from ? b : a));
+ const isMain = (r: Rel) => isVerb(r) && (
+ (startsWithWh && toks.slice(0, r.from).every(t => scaffold(t.lower))) ||
+ (auxInverted && r === lastRel && r.to === toks.length - 1)
+ );
+ const skip = (l: string) => DETERMINERS.has(l) || PREPS.has(l) || RELATIVE.has(l) || AUX.has(l) || OTHER_MARKERS.has(l) || l === "'s" || l === 'by' || l === 'whose';
+ const dist = (r: Rel) => {
+ const [a, b] = r.to < aStart ? [r.to + 1, aStart] : [aEnd + 1, r.from];
+ return toks.slice(a, b).filter((t, k) => !used[a + k] && !skip(t.lower)).length + toks.slice(a, b).filter((_, k) => used[a + k]).length;
+ };
+ const nounish = (r: Rel) => (isVerb(r) ? 1 : 0);
+ const possessive = (r: Rel) => (r.entry.words[0] === "'s" && r.from === aEnd + 1 ? 0 : 1);
+ const ordered = [...rels].sort((a, b) =>
+ Number(isMain(a)) - Number(isMain(b)) || possessive(a) - possessive(b) || dist(a) - dist(b) || nounish(a) - nounish(b) || a.from - b.from);
+
+ const hops: ChainHop[] = [];
+ const phrases: string[] = [];
+ for (const r of ordered) {
+ const anchorOnLeft = aEnd < r.from && !BACKREF.has(toks[r.to + 1]?.lower ?? '');
+ const lts = linkFamily(r.entry.rel);
+ const phrase = query.slice(toks[r.from].start, toks[r.to].end);
+ if (r.entry.form === 'co') {
+ hops.push({ linkTypes: lts, toward: 'object' }, { linkTypes: lts, toward: 'subject' });
+ excludeAnchor = true;
+ phrases.push(phrase, phrase);
+ continue;
+ }
+ let toward: 'object' | 'subject';
+ switch (r.entry.form) {
+ case 'verb': toward = anchorOnLeft ? 'object' : 'subject'; break;
+ case 'passive': toward = anchorOnLeft ? 'subject' : 'object'; break;
+ case 'agent': toward = 'subject'; break;
+ case 'out': toward = 'object'; break;
+ }
+ hops.push({ linkTypes: lts, toward });
+ phrases.push(phrase);
+ }
+ if (hops.length > MAX_CHAIN_HOPS) return { kind: 'unsupported', reason: `more than ${MAX_CHAIN_HOPS} relations` };
+
+ // Co-relation shape: the last hop walks back over the relation just walked.
+ const last = hops[hops.length - 1];
+ const prev = hops[hops.length - 2];
+ if (prev && last.linkTypes[0] === prev.linkTypes[0] && last.toward !== prev.toward) excludeAnchor = true;
+
+ // Type coherence along the chain, then the head noun on the last hop.
+ let types: Set<string> | null = null;
+ for (const h of hops) {
+ const sig = LINK_SIGNATURES[h.linkTypes[0]];
+ const entry = new Set(h.toward === 'object' ? sig.subject : sig.object);
+ if (types && ![...types].some(t => entry.has(t))) return { kind: 'unsupported', reason: 'the relations do not chain (page types disagree)' };
+ types = new Set(h.toward === 'object' ? sig.object : sig.subject);
+ }
+ if (headType) {
+ if (!types!.has(headType)) return { kind: 'unsupported', reason: `the question asks for ${headType} pages but the last relation returns ${[...types!].join('/')}` };
+ if (types!.size > 1) hops[hops.length - 1] = { ...last, nodeType: headType };
+ }
+ return { kind: 'plan', plan: { anchor, hops, excludeAnchor, phrases } };
+}
+
+
+/**
+ * Does this query count as relational for ranking decisions (keyword-arm
+ * confidence, intent weighting)? A planned multi-relation question counts only
+ * when the planner is on, so planner-off search is exactly today's.
+ */
+export function isRelationalQuery(query: string, plannerOn: boolean): boolean {
+ if (parseRelationalQuery(query) !== null) return true;
+ return plannerOn && parseRelationalPlan(query).kind === 'plan';
+}
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 4be84ed12b..4b8bd310f1 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -36,6 +36,9 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from './relational-intent.ts';
import { edgeValidityEnabled } from '../link-validity.ts';
import { stampEvidence, type EvidenceOpts } from './evidence.ts';
+import { parseRelationalPlan } from './relational-plan.ts';
+import { LINK_SIGNATURES, presentEdgeContext, resolveChainAnchors, runRelationalChain, type ChainAnchor, type ChainDiagnostics, type ChainStatus, type RelationalChainRow } from './relational-chain.ts';
+import { requiresSafeChunks } from './safe-chunks.ts';
export interface RelationalArmOpts extends PageReadPolicy {
sourceId?: string;
@@ -50,16 +53,33 @@ export interface RelationalArmOpts extends PageReadPolicy {
* without it a remote relational query leaked private titles + snippets.
*/
excludePrivate?: boolean;
+ /** Multi-relation questions walk typed hop chains (search.relational_planner). */
+ planner?: boolean;
+ /** Typed one-hop walks also read edges written on the other page (search.relational_orient_onehop). */
+ orientOneHop?: boolean;
onMeta?: (meta: RelationalArmMeta) => void;
}
export interface RelationalArmMeta {
fired: boolean;
- kind: RelationalQuery['kind'] | null;
+ kind: RelationalQuery['kind'] | 'chain' | null;
seeds_resolved: number;
candidates: number;
errored: boolean;
duration_ms: number;
+ /** Multi-relation plan outcome, when the planner ran on a 2-3 relation question. */
+ plan?: RelationalPlanMeta;
+}
+
+export interface RelationalPlanMeta {
+ status: ChainStatus | 'unsupported';
+ reason?: string;
+ anchor?: string;
+ anchor_slugs?: string[];
+ hops?: Array<{ link_types: string[]; toward: 'object' | 'subject'; frontier: number; edges: number }>;
+ answers?: number;
+ cap_hit?: ChainDiagnostics['cap_hit'];
+ empty_hop?: number;
}
interface RelationalFailureEvent {
@@ -223,7 +243,9 @@ export function answerRows(list: readonly SearchResult[]): SearchResult[] {
* consumers can audit why a low-fused-score row appears on the first page.
*/
export interface RelationalEvidenceSlotDecision {
- action: 'promoted' | 'injected';
+ action: 'promoted' | 'injected' | 'chain_pinned';
+ /** chain_pinned only: how many chain rows were placed at the top of page 1. */
+ count?: number;
slug: string;
source_id: string;
/** promoted only: the 0-based fused rank the row was lifted from. */
@@ -257,7 +279,12 @@ export function ensureRelationalEvidenceSlot(
limit: number,
offset: number,
evidenceOpts?: EvidenceOpts,
+ chainSlots = 0,
): { pool: SearchResult[]; decision?: RelationalEvidenceSlotDecision } {
+ if (chainSlots > 0 && offset === 0) {
+ const pinned = pinChainRows(pool, relationalList, Math.min(chainSlots, limit), evidenceOpts);
+ if (pinned) return pinned;
+ }
relationalList = answerRows(relationalList);
if (offset > 0 || limit <= 0 || relationalList.length === 0) return { pool };
const pageKey = (r: SearchResult) => `${r.source_id ?? 'default'}:${r.slug}`;
@@ -303,6 +330,41 @@ export function ensureRelationalEvidenceSlot(
};
}
+/**
+ * Chain slots: when a multi-hop chain fired, its rows (answers first, then the
+ * evidence pages of their paths, in arm order) take the top of page 1, up to
+ * `slots`. A chain answer is exact typed evidence for the question while the
+ * lexical rows of a relationship question mostly match names, so the chain
+ * leads; the rest of the pool follows in its own order. Returns null when no
+ * chain fired (the single evidence slot then applies).
+ */
+function pinChainRows(
+ pool: SearchResult[],
+ relationalList: SearchResult[],
+ slots: number,
+ evidenceOpts?: EvidenceOpts,
+): { pool: SearchResult[]; decision: RelationalEvidenceSlotDecision } | null {
+ const chain = relationalList.filter(r => r.relational !== undefined).slice(0, slots);
+ if (chain.length === 0) return null;
+ const pageKey = (r: SearchResult) => `${r.source_id ?? 'default'}:${r.slug}`;
+ const inPool = new Map<string, SearchResult>();
+ for (const r of pool) if (!inPool.has(pageKey(r))) inPool.set(pageKey(r), r);
+ const keys = new Set(chain.map(pageKey));
+ const top = chain.map(r => {
+ const fused = inPool.get(pageKey(r));
+ if (fused) return { ...fused, relational: fused.relational ?? r.relational };
+ const raw = { ...r };
+ stampEvidence([raw], evidenceOpts);
+ return raw;
+ });
+ const lead = pool[0]?.score ?? 0;
+ const ordered = top.map((r, i) => ({ ...r, score: Math.max(r.score, lead) + (top.length - i) * 1e-6 }));
+ return {
+ pool: [...ordered, ...pool.filter(r => !keys.has(pageKey(r)))],
+ decision: { action: 'chain_pinned', slug: chain[0].slug, source_id: chain[0].source_id ?? 'default', count: chain.length },
+ };
+}
+
/**
* Build the relational recall arm. Returns an empty list (pure no-op) when the
* query isn't relational or no seed resolves. Never throws.
@@ -323,6 +385,12 @@ export async function buildRelationalArm(
return list;
};
+ if (opts.planner) {
+ const planned = await planChain(engine, query, opts, meta);
+ if (planned === 'unsupported') return finish([]);
+ if (planned) return finish(planned);
+ }
+
const parsed = parseRelationalQuery(query, opts.vocab);
if (!parsed) return finish([]);
meta.kind = parsed.kind;
@@ -373,10 +441,14 @@ export async function buildRelationalArm(
if (resolved.length === 0) return finish([]);
meta.seeds_resolved = resolved.length;
const slugs = Array.from(new Set(resolved.map(r => r.slug)));
- const rows = await engine.relationalFanout(slugs, {
+ let rows = await engine.relationalFanout(slugs, {
...fanoutOpts,
seedRefs: resolved,
});
+ if (opts.orientOneHop && parsed.kind === 'who_rel' && parsed.direction !== 'both'
+ && parsed.linkTypes?.length && parsed.linkTypes.every(lt => LINK_SIGNATURES[lt])) {
+ rows = await withOrientedOneHop(engine, rows, resolved, parsed, opts);
+ }
const list = await hydrate(engine, rows, resolved[0].slug, opts);
meta.fired = list.length > 0;
return finish(list);
@@ -387,3 +459,108 @@ export async function buildRelationalArm(
return finish([]);
}
}
+
+/**
+ * Multi-relation questions: plan, resolve the anchor, walk the chain, hydrate.
+ * Returns the arm list when the chain found answers; `null` when the planner
+ * does not apply or the chain found nothing (the one-hop path then runs as
+ * before, so a plan can never remove a one-hop answer); `'unsupported'` when
+ * the question chains relations in a way the planner refuses (coordination,
+ * negation, time): no relational arm then, never a one-hop guess.
+ */
+async function planChain(
+ engine: BrainEngine,
+ query: string,
+ opts: RelationalArmOpts,
+ meta: RelationalArmMeta,
+): Promise<SearchResult[] | null | 'unsupported'> {
+ const result = parseRelationalPlan(query);
+ if (result.kind === 'not_applicable') return null;
+ meta.kind = 'chain';
+ if (result.kind === 'unsupported') {
+ meta.plan = { status: 'unsupported', reason: result.reason };
+ return 'unsupported';
+ }
+ const { plan } = result;
+ try {
+ const sources = await scopeSources(engine, opts);
+ const refs = await resolveSeedScoped(engine, sources, plan.anchor, opts);
+ const anchors: ChainAnchor[] = [];
+ for (const ref of refs) anchors.push(...await resolveChainAnchors(engine, ref.slug, { ...opts, sourceIds: undefined, sourceId: ref.source_id }));
+ meta.seeds_resolved = anchors.length;
+ const { rows, diagnostics } = await runRelationalChain(engine, anchors, { hops: plan.hops, excludeAnchor: plan.excludeAnchor }, opts);
+ meta.plan = {
+ status: diagnostics.status, anchor: plan.anchor, anchor_slugs: anchors.map(a => a.slug),
+ hops: diagnostics.per_hop, answers: rows.filter(r => r.role === 'answer').length,
+ ...(diagnostics.cap_hit ? { cap_hit: diagnostics.cap_hit } : {}),
+ ...(diagnostics.empty_hop ? { empty_hop: diagnostics.empty_hop } : {}),
+ };
+ if (rows.length === 0) return null;
+ const list = await hydrateChain(engine, rows, anchors, opts);
+ meta.fired = list.length > 0;
+ return list.length > 0 ? list : null;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ failureWriter.log({ error_summary: truncate(msg), query_kind: 'chain' });
+ meta.errored = true;
+ return null;
+ }
+}
+
+/** Answers first (up to the arm limit), then the evidence pages on their retained paths while room remains. */
+async function hydrateChain(
+ engine: BrainEngine,
+ rows: RelationalChainRow[],
+ anchors: ChainAnchor[],
+ opts: RelationalArmOpts,
+): Promise<SearchResult[]> {
+ const limit = Math.max(1, opts.limit ?? 50);
+ const picked = rows.slice(0, limit);
+ const fanoutShaped: RelationalFanoutRow[] = picked.map(r => ({
+ source_id: r.source_id, slug: r.slug, hop: r.hop, edge_count: r.path_count,
+ via_link_types: [...new Set(r.best_path.edges.map(e => e.link_type))], path: r.best_path.nodes,
+ canonical_chunk_id: r.canonical_chunk_id,
+ }));
+ const seed = anchors[0]?.slug ?? '';
+ const hydrated = await hydrate(engine, fanoutShaped, seed, opts);
+ const remote = requiresSafeChunks(opts);
+ const byKey = new Map(picked.map(r => [`${r.source_id}:${r.slug}`, r] as const));
+ return hydrated.map(h => {
+ const r = byKey.get(`${h.source_id}:${h.slug}`)!;
+ return {
+ ...h,
+ relational: {
+ role: r.role, seed, hop: r.hop, path_count: r.path_count,
+ edges: r.best_path.edges.slice(-3).map(e => ({ ...e, context: presentEdgeContext(e.context, remote) })),
+ },
+ };
+ });
+}
+
+/**
+ * Typed one-hop orientation: add the neighbors a relation reaches through
+ * edges written on the other page (a company page saying "founded by X"),
+ * after the stored-direction hop-1 rows and before deeper rows.
+ */
+async function withOrientedOneHop(
+ engine: BrainEngine,
+ rows: RelationalFanoutRow[],
+ seeds: Array<{ source_id: string; slug: string }>,
+ parsed: RelationalQuery,
+ opts: RelationalArmOpts,
+): Promise<RelationalFanoutRow[]> {
+ const anchors: ChainAnchor[] = [];
+ for (const s of seeds) anchors.push(...await resolveChainAnchors(engine, s.slug, { ...opts, sourceIds: undefined, sourceId: s.source_id }));
+ const toward = parsed.direction === 'in' ? 'subject' : 'object';
+ const { rows: chain } = await runRelationalChain(engine, anchors, { hops: [{ linkTypes: parsed.linkTypes!, toward }], excludeAnchor: true }, opts);
+ const have = new Set(rows.map(r => `${r.source_id}:${r.slug}`));
+ const extra: RelationalFanoutRow[] = chain
+ .filter(r => r.role === 'answer' && !have.has(`${r.source_id}:${r.slug}`))
+ .map(r => ({
+ source_id: r.source_id, slug: r.slug, hop: 1, edge_count: 1, via_link_types: [...parsed.linkTypes!],
+ path: r.best_path.nodes, canonical_chunk_id: r.canonical_chunk_id,
+ }));
+ if (extra.length === 0) return rows;
+ const hop1 = rows.filter(r => r.hop <= 1);
+ return [...hop1, ...extra, ...rows.filter(r => r.hop > 1)].slice(0, Math.max(rows.length, opts.limit ?? 50));
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index 0808ee26e4..8263800cfa 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1407,6 +1407,12 @@ export interface SearchOpts extends PageReadPolicy {
* Eval A/B gates drive it here.
*/
relationalRerankPin?: number;
+ /** Per-call override for `search.relational_planner` (multi-hop chains; eval A/B). */
+ relationalPlanner?: boolean;
+ /** Per-call override for `search.relational_orient_onehop` (typed one-hop orientation; eval A/B). */
+ relationalOrientOneHop?: boolean;
+ /** Per-call override for `search.relational_chain_slots` (0..10; eval A/B). */
+ relationalChainSlots?: number;
}
/**
@@ -2076,6 +2082,8 @@ export interface HybridSearchMeta {
* and every reranker fail-open path. Surfaced for `gbrain search --explain`.
*/
relational_rerank_pin?: import('./search/relational-rerank-pin.ts').RelationalRerankPinDecision;
+ /** Multi-hop planner outcome for a 2-3 relation question (status, anchor, per-hop counts, cap). */
+ relational_plan?: import('./search/relational-recall.ts').RelationalPlanMeta;
/**
* Ranker wave (Phase E2, Cat 13) — keyword-arm confidence decision:
* `margin_ratio` (scale-free `top / (top + second)` over the keyword arm's
diff --git a/test/fixtures/goldens/cli/thin-client-cases.json b/test/fixtures/goldens/cli/thin-client-cases.json
index f4dc787522..072ad4e83c 100644
--- a/test/fixtures/goldens/cli/thin-client-cases.json
+++ b/test/fixtures/goldens/cli/thin-client-cases.json
@@ -282,6 +282,16 @@
" source. An unknown source is a hard error. Local",
" installs only: a thin client rejects it (the server",
" scopes the walk to your grant).",
+ " --hop <type>:<toward> One hop of a typed chain; repeat for 2-3 hops. <toward>",
+ " is 'object' (subject -> object, e.g. investor -> company)",
+ " or 'subject' (object -> subject, e.g. company -> founder).",
+ " Follows the relation's meaning, whichever page the edge",
+ " was written on. Prints answers with the edges that prove",
+ " each one. Cannot be combined with --type, --depth or",
+ " --direction. MCP: traverse_graph {\"hops\":[{\"link_type\":",
+ " \"invested_in\",\"toward\":\"object\"}, ...]}. Chain link",
+ " types: founded, invested_in, led_round, advises, works_at, attended, yc_partner.",
+ " Guide: docs/guides/multi-hop.md",
" --include-foreign Include edges to pages in other sources (v0.37.7.0).",
" Off by default; the walk stays inside the resolved",
" source, and a footer reports the count of",
@@ -298,6 +308,8 @@
" -> Bob's direct connections",
" gbrain graph-query people/bob --include-foreign",
" -> include edges to pages in other sources",
+ " gbrain graph-query people/alice --hop invested_in:object --hop founded:subject",
+ " -> founders of the companies Alice invested in, with evidence",
""
]
},
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index fb4b430e37..bdab94abcd 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": 198595,
- "stdoutSha256": "7d2b43ea2fc64cd07907cc2fd1ecb1fae4812fe23091cd76629a7512ff57de98",
+ "stdoutBytes": 197373,
+ "stdoutSha256": "c24014bb9d4d2fcc6b6ec6af92fd77ae6d5aafa090dedda4d0fb9af651361b2f",
"toolNames": [
"remember",
"entity",
@@ -348,7 +348,6 @@
"mutating": false,
"name": "get_page",
"parameters": {
- "content_only": "boolean?",
"fuzzy": "boolean?",
"include_content": "boolean?",
"include_deleted": "boolean?",
@@ -359,10 +358,6 @@
"required_scopes": [],
"schema": {
"properties": {
- "content_only": {
- "description": "Round-trip fields only.",
- "type": "boolean"
- },
"fuzzy": {
"description": "Fuzzy slug match.",
"type": "boolean"
@@ -1484,9 +1479,7 @@
"from": "string",
"link_source": "string?",
"link_type": "string?",
- "to": "string",
- "valid_from": "string?",
- "valid_until": "string?"
+ "to": "string"
},
"required_scopes": [],
"schema": {
@@ -1510,14 +1503,6 @@
"to": {
"description": "Slug of the page the link points to, e.g. 'companies/acme-example'.",
"type": "string"
- },
- "valid_from": {
- "description": "When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in.",
- "type": "string"
- },
- "valid_until": {
- "description": "When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended.",
- "type": "string"
}
},
"required": [
@@ -1569,19 +1554,15 @@
"scope": "write"
},
{
- "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_links",
"parameters": {
"all_sources": "boolean?",
- "as_of": "string?",
- "during": "string?",
- "link_type": "string?",
"slug": "string",
- "source_id": "string?",
- "status": "string?"
+ "source_id": "string?"
},
"required_scopes": [],
"schema": {
@@ -1590,18 +1571,6 @@
"description": "Same as source_id __all__.",
"type": "boolean"
},
- "as_of": {
- "description": "YYYY-MM-DD.",
- "type": "string"
- },
- "during": {
- "description": "Period: 2022, 2022-03 or 2021..2023.",
- "type": "string"
- },
- "link_type": {
- "description": "Only this type.",
- "type": "string"
- },
"slug": {
"description": "Slug of the page whose outgoing links to list.",
"type": "string"
@@ -1609,15 +1578,6 @@
"source_id": {
"description": "One source, or '__all__'.",
"type": "string"
- },
- "status": {
- "description": "Default live (true now).",
- "enum": [
- "live",
- "ended",
- "all"
- ],
- "type": "string"
}
},
"required": [
@@ -1635,10 +1595,8 @@
"name": "get_backlinks",
"parameters": {
"all_sources": "boolean?",
- "as_of": "string?",
"slug": "string",
- "source_id": "string?",
- "status": "string?"
+ "source_id": "string?"
},
"required_scopes": [],
"schema": {
@@ -1647,10 +1605,6 @@
"description": "Same as source_id __all__.",
"type": "boolean"
},
- "as_of": {
- "description": "YYYY-MM-DD",
- "type": "string"
- },
"slug": {
"description": "Page slug.",
"type": "string"
@@ -1658,14 +1612,6 @@
"source_id": {
"description": "One source, or '__all__'.",
"type": "string"
- },
- "status": {
- "description": "Default live.",
- "enum": [
- "live",
- "all"
- ],
- "type": "string"
}
},
"required": [
@@ -1700,6 +1646,7 @@
"all_sources": "boolean?",
"depth": "number?",
"direction": "string?",
+ "hops": "array?",
"link_type": "string?",
"slug": "string",
"source_id": "string?"
@@ -1724,6 +1671,23 @@
],
"type": "string"
},
+ "hops": {
+ "description": "≤3 typed hops, e.g. [{\"link_type\":\"founded\",\"toward\":\"subject\"}]; toward: object|subject.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "link_type": {
+ "type": "string"
+ },
+ "toward": {
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "type": "array"
+ },
"link_type": {
"description": "Follow only this link type.",
"type": "string"
@@ -6321,9 +6285,7 @@
"backup_coverage",
"degraded_dedup",
"empty_retrieval",
- "facts_drain_first_run",
"features_auto_fix",
- "former_relationships_hidden",
"listing_truncated",
"local_transcripts",
"onboard_opportunities",
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 09b2b73585..d8f87ca056 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -137,6 +137,7 @@
"reconnect",
"refreshPageBody",
"registerBeforeDisconnect",
+ "relationalChainHop",
"relationalFanout",
"removeLink",
"removeLinksByPagesAndSource",
@@ -318,6 +319,7 @@
"reconnect",
"refreshPageBody",
"registerBeforeDisconnect",
+ "relationalChainHop",
"relationalFanout",
"removeLink",
"removeLinksByPagesAndSource",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index b1ab76da9b..dd3266dd7e 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -172,6 +172,7 @@
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
"refreshPageBody: (slug: string, sourceId: string, compiledTruth: string, timeline: string, contentHash: string) => Promise<void>",
"registerBeforeDisconnect: (stop: () => Promise<void>) => () => void",
+ "relationalChainHop: (frontierPageIds: number[], opts: ChainHopOpts) => Promise<ChainHopEdge[]>",
"relationalFanout: (seeds: string[], opts?: RelationalFanoutOpts) => Promise<RelationalFanoutRow[]>",
"removeLink: (from: string, to: string, linkType?: string, linkSource?: string, opts?: { fromSourceId?: string; toSourceId?: string; }) => Promise<number>",
"removeLinksByPagesAndSource: (pages: Array<{ slug: string; source_id: string; }>, opts: { linkSource: string; keepTypedNerPairs?: Array<{ from_slug: string; from_source_id: string; to_slug: string; to_source_id: string; }>; }) => Promise<number>",
@@ -274,6 +275,45 @@
"readonly [\"none\", \"title\", \"per_chunk_synopsis\"]"
]
},
+ {
+ "kind": "interface",
+ "members": [
+ "canonical_chunk_id: number | null",
+ "context: string | null",
+ "from_degree: number",
+ "from_page_id: number",
+ "link_ids: number[]",
+ "link_type: string",
+ "neighbor_cap_hit: boolean",
+ "orientation: \"canonical\" | \"stored\" | \"flipped\" | \"uncertain\"",
+ "origin_page_id: number | null",
+ "origin_slug: string | null",
+ "source_id: string",
+ "stored_from_slug: string",
+ "stored_to_slug: string",
+ "to_page_id: number",
+ "to_slug: string",
+ "to_type: string"
+ ],
+ "name": "ChainHopEdge"
+ },
+ {
+ "kind": "interface",
+ "members": [
+ "degreeLinkTypes: string[]",
+ "excludePrivate?: boolean | undefined",
+ "linkTypes: string[]",
+ "neighborCap: number",
+ "objectTypes: string[]",
+ "requireSafeChunks?: boolean | undefined",
+ "sourceId?: string | undefined",
+ "sourceIds?: string[] | undefined",
+ "subjectTypes: string[]",
+ "takesHoldersAllowList?: string[] | undefined",
+ "toward: \"object\" | \"subject\""
+ ],
+ "name": "ChainHopOpts"
+ },
{
"kind": "interface",
"members": [
@@ -676,6 +716,7 @@
"metadata_boost_gate?: MetadataBoostGateDecision | undefined",
"mode?: \"conservative\" | \"balanced\" | \"tokenmax\" | undefined",
"relational_evidence_slot?: RelationalEvidenceSlotDecision | undefined",
+ "relational_plan?: RelationalPlanMeta | undefined",
"relational_rerank_pin?: RelationalRerankPinDecision | undefined",
"relaxed_dropped?: number | undefined",
"rerank?: { model_resolved: string; } | undefined",
@@ -1111,6 +1152,7 @@
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
"refreshPageBody: (slug: string, sourceId: string, compiledTruth: string, timeline: string, contentHash: string) => Promise<void>",
"registerBeforeDisconnect: (stop: () => Promise<void>) => () => void",
+ "relationalChainHop: (frontierPageIds: number[], opts: ChainHopOpts) => Promise<ChainHopEdge[]>",
"relationalFanout: (seeds: string[], opts?: RelationalFanoutOpts) => Promise<RelationalFanoutRow[]>",
"removeLink: (from: string, to: string, linkType?: string, linkSource?: string, opts?: { fromSourceId?: string; toSourceId?: string; }) => Promise<number>",
"removeLinksByPagesAndSource: (pages: Array<{ slug: string; source_id: string; }>, opts: { linkSource: string; keepTypedNerPairs?: Array<{ from_slug: string; from_source_id: string; to_slug: string; to_source_id: string; }>; }) => Promise<number>",
@@ -1182,6 +1224,17 @@
],
"name": "RawData"
},
+ {
+ "kind": "interface",
+ "members": [
+ "edges: { link_type: string; stored_from: string; stored_to: string; orientation: \"canonical\" | \"stored\" | \"flipped\" | \"uncertain\"; context: string | null; origin: string | null; }[]",
+ "hop: number",
+ "path_count: number",
+ "role: \"answer\" | \"support\" | \"origin\"",
+ "seed: string"
+ ],
+ "name": "RelationalEvidence"
+ },
{
"kind": "interface",
"members": [
@@ -1280,6 +1333,9 @@
"orFallback?: boolean | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
+ "relationalChainSlots?: number | undefined",
+ "relationalOrientOneHop?: boolean | undefined",
+ "relationalPlanner?: boolean | undefined",
"relationalRerankPin?: number | undefined",
"relationalRetrieval?: boolean | undefined",
"relationalRetrievalDepth?: number | undefined",
@@ -1338,6 +1394,7 @@
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
"recency_boost?: number | undefined",
+ "relational?: RelationalEvidence | undefined",
"relational_hop?: number | undefined",
"relational_path?: string[] | undefined",
"relational_pinned?: boolean | undefined",
@@ -3162,6 +3219,7 @@
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
"refreshPageBody: (slug: string, sourceId: string, compiledTruth: string, timeline: string, contentHash: string) => Promise<void>",
"registerBeforeDisconnect: (stop: () => Promise<void>) => () => void",
+ "relationalChainHop: (frontierPageIds: number[], opts: ChainHopOpts) => Promise<ChainHopEdge[]>",
"relationalFanout: (seeds: string[], opts?: RelationalFanoutOpts) => Promise<RelationalFanoutRow[]>",
"removeLink: (from: string, to: string, linkType?: string, linkSource?: string, opts?: { fromSourceId?: string; toSourceId?: string; }) => Promise<number>",
"removeLinksByPagesAndSource: (pages: Array<{ slug: string; source_id: string; }>, opts: { linkSource: string; keepTypedNerPairs?: Array<{ from_slug: string; from_source_id: string; to_slug: string; to_source_id: string; }>; }) => Promise<number>",
@@ -4573,7 +4631,7 @@
"kind": "type",
"name": "LinkExtractionPack",
"signature": [
- "Pick<{ api_version: \"gbrain-schema-pack-v1\"; name: string; version: string; description: string; gbrain_min_version: string; extends: string | null; borrow_from: { pack: string; types?: string[] | undefined; link_types?: string[] | undefined; }[]; page_types: { name: string; primitive: \"entity\" | \"temporal\" | \"concept\" | \"media\" | \"annotation\"; path_prefixes: string[]; aliases: string[]; extractable: boolean | { eval_dimensions: string[]; prompt_template?: string | undefined; fixture_corpus?: string | undefined; benchmark_min_recall?: number | undefined; verifier_path?: string | undefined; }; expert_routing: boolean; subtypes?: { name: string; when: { path_pattern?: string | undefined; frontmatter_field?: string | undefined; frontmatter_value?: string | number | boolean | undefined; }; }[] | undefined; }[]; link_types: { name: string; inverse?: string | undefined; inference?: { regex?: string | undefined; page_type?: string | undefined; target_type?: string | undefined; ner_only?: boolean | undefined; } | undefined; temporal?: \"event\" | \"state\" | undefined; }[]; frontmatter_links: { page_type: string; fields: string[]; link_type: string; }[]; takes_kinds: string[]; enrichable_types: { type: string; rubric?: string | undefined; }[]; filing_rules: { kind: string; directory: string; examples: string[]; description?: string | undefined; }[]; author?: string | undefined; license?: string | undefined; homepage?: string | undefined; phases?: string[] | undefined; calibration_domains?: { name: string; aggregator: \"scalar_brier\" | \"weighted_brier\" | \"count_based\" | \"cluster_summary\"; page_types: string[]; }[] | undefined; migration_from?: { pack: string; version: string; } | undefined; mapping_rules?: ({ kind: \"retype\"; from_type: string; to_type: string; subtype_field: \"kind\" | \"format\" | \"subtype\" | \"legacy_type\" | \"origin\" | \"period\" | \"domain\"; subtype?: string | undefined; path_filter?: string | undefined; slug_filter?: string | undefined; } | { kind: \"page_to_link\"; from_type: string; link_type: string; source_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; target_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; inverse?: string | undefined; preserve_notes?: boolean | undefined; } | { kind: \"page_to_alias\"; from_type: string; canonical_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; alias_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; notes_from?: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; } | undefined; })[] | undefined; }, \"link_types\" | \"frontmatter_links\"> & Partial<Pick<{ api_version: \"gbrain-schema-pack-v1\"; name: string; version: string; description: string; gbrain_min_version: string; extends: string | null; borrow_from: { pack: string; types?: string[] | undefined; link_types?: string[] | undefined; }[]; page_types: { name: string; primitive: \"entity\" | \"temporal\" | \"concept\" | \"media\" | \"annotation\"; path_prefixes: string[]; aliases: string[]; extractable: boolean | { eval_dimensions: string[]; prompt_template?: string | undefined; fixture_corpus?: string | undefined; benchmark_min_recall?: number | undefined; verifier_path?: string | undefined; }; expert_routing: boolean; subtypes?: { name: string; when: { path_pattern?: string | undefined; frontmatter_field?: string | undefined; frontmatter_value?: string | number | boolean | undefined; }; }[] | undefined; }[]; link_types: { name: string; inverse?: string | undefined; inference?: { regex?: string | undefined; page_type?: string | undefined; target_type?: string | undefined; ner_only?: boolean | undefined; } | undefined; temporal?: \"event\" | \"state\" | undefined; }[]; frontmatter_links: { page_type: string; fields: string[]; link_type: string; }[]; takes_kinds: string[]; enrichable_types: { type: string; rubric?: string | undefined; }[]; filing_rules: { kind: string; directory: string; examples: string[]; description?: string | undefined; }[]; author?: string | undefined; license?: string | undefined; homepage?: string | undefined; phases?: string[] | undefined; calibration_domains?: { name: string; aggregator: \"scalar_brier\" | \"weighted_brier\" | \"count_based\" | \"cluster_summary\"; page_types: string[]; }[] | undefined; migration_from?: { pack: string; version: string; } | undefined; mapping_rules?: ({ kind: \"retype\"; from_type: string; to_type: string; subtype_field: \"kind\" | \"format\" | \"subtype\" | \"legacy_type\" | \"origin\" | \"period\" | \"domain\"; subtype?: string | undefined; path_filter?: string | undefined; slug_filter?: string | undefined; } | { kind: \"page_to_link\"; from_type: string; link_type: string; source_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; target_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; inverse?: string | undefined; preserve_notes?: boolean | undefined; } | { kind: \"page_to_alias\"; from_type: string; canonical_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; alias_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; notes_from?: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; } | undefined; })[] | undefined; }, \"page_types\">>"
+ "Pick<{ api_version: \"gbrain-schema-pack-v1\"; name: string; version: string; description: string; gbrain_min_version: string; extends: string | null; borrow_from: { pack: string; types?: string[] | undefined; link_types?: string[] | undefined; }[]; page_types: { name: string; primitive: \"entity\" | \"temporal\" | \"concept\" | \"media\" | \"annotation\"; path_prefixes: string[]; aliases: string[]; extractable: boolean | { eval_dimensions: string[]; prompt_template?: string | undefined; fixture_corpus?: string | undefined; benchmark_min_recall?: number | undefined; verifier_path?: string | undefined; }; expert_routing: boolean; subtypes?: { name: string; when: { path_pattern?: string | undefined; frontmatter_field?: string | undefined; frontmatter_value?: string | number | boolean | undefined; }; }[] | undefined; }[]; link_types: { name: string; inverse?: string | undefined; inference?: { regex?: string | undefined; page_type?: string | undefined; target_type?: string | undefined; ner_only?: boolean | undefined; } | undefined; temporal?: \"event\" | \"state\" | undefined; }[]; frontmatter_links: { page_type: string; fields: string[]; link_type: string; }[]; takes_kinds: string[]; enrichable_types: { type: string; rubric?: string | undefined; }[]; filing_rules: { kind: string; directory: string; examples: string[]; description?: string | undefined; }[]; author?: string | undefined; license?: string | undefined; homepage?: string | undefined; phases?: string[] | undefined; calibration_domains?: { name: string; aggregator: \"scalar_brier\" | \"weighted_brier\" | \"count_based\" | \"cluster_summary\"; page_types: string[]; }[] | undefined; migration_from?: { pack: string; version: string; } | undefined; mapping_rules?: ({ kind: \"retype\"; from_type: string; to_type: string; subtype_field: \"kind\" | \"origin\" | \"format\" | \"subtype\" | \"legacy_type\" | \"period\" | \"domain\"; subtype?: string | undefined; path_filter?: string | undefined; slug_filter?: string | undefined; } | { kind: \"page_to_link\"; from_type: string; link_type: string; source_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; target_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; inverse?: string | undefined; preserve_notes?: boolean | undefined; } | { kind: \"page_to_alias\"; from_type: string; canonical_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; alias_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; notes_from?: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; } | undefined; })[] | undefined; }, \"link_types\" | \"frontmatter_links\"> & Partial<Pick<{ api_version: \"gbrain-schema-pack-v1\"; name: string; version: string; description: string; gbrain_min_version: string; extends: string | null; borrow_from: { pack: string; types?: string[] | undefined; link_types?: string[] | undefined; }[]; page_types: { name: string; primitive: \"entity\" | \"temporal\" | \"concept\" | \"media\" | \"annotation\"; path_prefixes: string[]; aliases: string[]; extractable: boolean | { eval_dimensions: string[]; prompt_template?: string | undefined; fixture_corpus?: string | undefined; benchmark_min_recall?: number | undefined; verifier_path?: string | undefined; }; expert_routing: boolean; subtypes?: { name: string; when: { path_pattern?: string | undefined; frontmatter_field?: string | undefined; frontmatter_value?: string | number | boolean | undefined; }; }[] | undefined; }[]; link_types: { name: string; inverse?: string | undefined; inference?: { regex?: string | undefined; page_type?: string | undefined; target_type?: string | undefined; ner_only?: boolean | undefined; } | undefined; temporal?: \"event\" | \"state\" | undefined; }[]; frontmatter_links: { page_type: string; fields: string[]; link_type: string; }[]; takes_kinds: string[]; enrichable_types: { type: string; rubric?: string | undefined; }[]; filing_rules: { kind: string; directory: string; examples: string[]; description?: string | undefined; }[]; author?: string | undefined; license?: string | undefined; homepage?: string | undefined; phases?: string[] | undefined; calibration_domains?: { name: string; aggregator: \"scalar_brier\" | \"weighted_brier\" | \"count_based\" | \"cluster_summary\"; page_types: string[]; }[] | undefined; migration_from?: { pack: string; version: string; } | undefined; mapping_rules?: ({ kind: \"retype\"; from_type: string; to_type: string; subtype_field: \"kind\" | \"origin\" | \"format\" | \"subtype\" | \"legacy_type\" | \"period\" | \"domain\"; subtype?: string | undefined; path_filter?: string | undefined; slug_filter?: string | undefined; } | { kind: \"page_to_link\"; from_type: string; link_type: string; source_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; target_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; inverse?: string | undefined; preserve_notes?: boolean | undefined; } | { kind: \"page_to_alias\"; from_type: string; canonical_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; alias_slug_from: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; }; notes_from?: \"slug\" | \"frontmatter\" | \"body_first_link\" | \"body_excerpt\" | { frontmatter_field: string; } | undefined; })[] | undefined; }, \"page_types\">>"
]
},
{
@@ -5986,6 +6044,7 @@
"reconnect: (_ctx?: { error?: unknown; }) => Promise<void>",
"refreshPageBody: (slug: string, sourceId: string, compiledTruth: string, timeline: string, contentHash: string) => Promise<void>",
"registerBeforeDisconnect: (stop: () => Promise<void>) => () => void",
+ "relationalChainHop: (frontierPageIds: number[], opts: ChainHopOpts) => Promise<ChainHopEdge[]>",
"relationalFanout: (seeds: string[], opts?: RelationalFanoutOpts) => Promise<RelationalFanoutRow[]>",
"removeLink: (from: string, to: string, linkType?: string, linkSource?: string, opts?: { fromSourceId?: string; toSourceId?: string; }) => Promise<number>",
"removeLinksByPagesAndSource: (pages: Array<{ slug: string; source_id: string; }>, opts: { linkSource: string; keepTypedNerPairs?: Array<{ from_slug: string; from_source_id: string; to_slug: string; to_source_id: string; }>; }) => Promise<number>",
@@ -6789,6 +6848,9 @@
"queryEmbedFn?: ((text: string) => Float32Array | Promise<Float32Array>) | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
+ "relationalChainSlots?: number | undefined",
+ "relationalOrientOneHop?: boolean | undefined",
+ "relationalPlanner?: boolean | undefined",
"relationalRerankPin?: number | undefined",
"relationalRetrieval?: boolean | undefined",
"relationalRetrievalDepth?: number | undefined",
@@ -7398,6 +7460,45 @@
"readonly [\"none\", \"title\", \"per_chunk_synopsis\"]"
]
},
+ {
+ "kind": "interface",
+ "members": [
+ "canonical_chunk_id: number | null",
+ "context: string | null",
+ "from_degree: number",
+ "from_page_id: number",
+ "link_ids: number[]",
+ "link_type: string",
+ "neighbor_cap_hit: boolean",
+ "orientation: \"canonical\" | \"stored\" | \"flipped\" | \"uncertain\"",
+ "origin_page_id: number | null",
+ "origin_slug: string | null",
+ "source_id: string",
+ "stored_from_slug: string",
+ "stored_to_slug: string",
+ "to_page_id: number",
+ "to_slug: string",
+ "to_type: string"
+ ],
+ "name": "ChainHopEdge"
+ },
+ {
+ "kind": "interface",
+ "members": [
+ "degreeLinkTypes: string[]",
+ "excludePrivate?: boolean | undefined",
+ "linkTypes: string[]",
+ "neighborCap: number",
+ "objectTypes: string[]",
+ "requireSafeChunks?: boolean | undefined",
+ "sourceId?: string | undefined",
+ "sourceIds?: string[] | undefined",
+ "subjectTypes: string[]",
+ "takesHoldersAllowList?: string[] | undefined",
+ "toward: \"object\" | \"subject\""
+ ],
+ "name": "ChainHopOpts"
+ },
{
"kind": "interface",
"members": [
@@ -7800,6 +7901,7 @@
"metadata_boost_gate?: MetadataBoostGateDecision | undefined",
"mode?: \"conservative\" | \"balanced\" | \"tokenmax\" | undefined",
"relational_evidence_slot?: RelationalEvidenceSlotDecision | undefined",
+ "relational_plan?: RelationalPlanMeta | undefined",
"relational_rerank_pin?: RelationalRerankPinDecision | undefined",
"relaxed_dropped?: number | undefined",
"rerank?: { model_resolved: string; } | undefined",
@@ -8091,6 +8193,17 @@
],
"name": "RawData"
},
+ {
+ "kind": "interface",
+ "members": [
+ "edges: { link_type: string; stored_from: string; stored_to: string; orientation: \"canonical\" | \"stored\" | \"flipped\" | \"uncertain\"; context: string | null; origin: string | null; }[]",
+ "hop: number",
+ "path_count: number",
+ "role: \"answer\" | \"support\" | \"origin\"",
+ "seed: string"
+ ],
+ "name": "RelationalEvidence"
+ },
{
"kind": "interface",
"members": [
@@ -8189,6 +8302,9 @@
"orFallback?: boolean | undefined",
"recency?: \"on\" | \"off\" | \"strong\" | undefined",
"recencyBoost?: 0 | 1 | 2 | undefined",
+ "relationalChainSlots?: number | undefined",
+ "relationalOrientOneHop?: boolean | undefined",
+ "relationalPlanner?: boolean | undefined",
"relationalRerankPin?: number | undefined",
"relationalRetrieval?: boolean | undefined",
"relationalRetrievalDepth?: number | undefined",
@@ -8247,6 +8363,7 @@
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
"recency_boost?: number | undefined",
+ "relational?: RelationalEvidence | undefined",
"relational_hop?: number | undefined",
"relational_path?: string[] | undefined",
"relational_pinned?: boolean | undefined",
diff --git a/test/ops-relational-chain.test.ts b/test/ops-relational-chain.test.ts
new file mode 100644
index 0000000000..1497130803
--- /dev/null
+++ b/test/ops-relational-chain.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Multi-hop chains through the public ops (keyless brain, planner on).
+ *
+ * Protects: `search` returns chain answers with their `relational` evidence
+ * (also in remote lean rows) and a `relational_plan` summary; a planned
+ * question whose anchor is not found carries a `relational_chain` notice with
+ * the next call; keyless `recall` routes a chain question through the
+ * relational arm and keeps the evidence; planner off leaves both ops as
+ * before. Regression it catches: evidence stripped by the op projections,
+ * keyless recall bypassing the relational arm, a silent no-answer.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+
+let engine: PGLiteEngine;
+const Q = 'Who founded the companies that Alice Example invested in?';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const page = async (slug: string, type: string, title: string, body: string) => {
+ await engine.putPage(slug, { type: type as 'person', title, compiled_truth: body, timeline: '' });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: body }]);
+ };
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice is a seed investor.');
+ await page('companies/widget-co', 'company', 'Widget Co', 'A payments company.');
+ await page('people/frank-example', 'person', 'Frank Example', 'Frank builds payment rails.');
+ await engine.addLink('people/alice-example', 'companies/widget-co', 'alice backed widget', 'invested_in', 'markdown');
+ await engine.addLink('companies/widget-co', 'people/frank-example', 'founded by Frank', 'founded', 'markdown');
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+function call(remote: boolean) {
+ const notices: Notice[] = [];
+ const meta: Record<string, unknown> = {};
+ const ctx = {
+ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,
+ sourceId: 'default', emitNotice: (n: Notice) => { notices.push(n); }, emitResponseMeta: (k: string, v: unknown) => { meta[k] = v; },
+ } as unknown as OperationContext;
+ return { ctx, notices, meta };
+}
+
+async function withPlanner<T>(on: boolean, fn: () => Promise<T>): Promise<T> {
+ await engine.setConfig('search.relational_planner', on ? 'true' : 'false');
+ try { return await fn(); } finally { await engine.setConfig('search.relational_planner', 'false'); }
+}
+
+describe('search', () => {
+ test('planner on: the founder arrives with chain evidence and a relational_plan summary', async () => {
+ const c = call(false);
+ const rows = await withPlanner(true, () => operationsByName.search.handler(c.ctx, { query: Q })) as any[];
+ const frank = rows.find(r => r.slug === 'people/frank-example');
+ expect(frank?.relational).toMatchObject({ role: 'answer', seed: 'people/alice-example' });
+ expect(JSON.stringify(c.meta)).toContain('"relational_plan"');
+ });
+
+ test('remote lean rows keep the evidence field', async () => {
+ const c = call(true);
+ const rows = await withPlanner(true, () => operationsByName.search.handler(c.ctx, { query: Q })) as any[];
+ expect(rows.find(r => r.slug === 'people/frank-example')?.relational?.role).toBe('answer');
+ });
+
+ test('an unknown anchor carries a relational_chain notice naming the next call', async () => {
+ const c = call(false);
+ await withPlanner(true, () => operationsByName.search.handler(c.ctx, { query: 'Who founded the companies that Nobody Example invested in?' }));
+ expect(c.notices.find(n => n.code === 'relational_chain')).toMatchObject({ fix: { mcp: { tool: 'search' } } });
+ });
+
+ test('planner off: no chain evidence', async () => {
+ const c = call(false);
+ const rows = await withPlanner(false, () => operationsByName.search.handler(c.ctx, { query: Q })) as any[];
+ expect(rows.some(r => r.relational !== undefined)).toBe(false);
+ });
+});
+
+describe('recall (keyless)', () => {
+ test('a chain question routes through the relational arm and keeps the evidence', async () => {
+ const c = call(false);
+ const res = await withPlanner(true, () => operationsByName.recall.handler(c.ctx, { query: Q })) as any;
+ expect(res.results.find((r: any) => r.slug === 'people/frank-example')?.relational?.role).toBe('answer');
+ });
+
+ test('planner off: keyless recall is the plain keyword path', async () => {
+ const c = call(false);
+ const res = await withPlanner(false, () => operationsByName.recall.handler(c.ctx, { query: Q })) as any;
+ expect((res.results ?? []).some((r: any) => r.relational !== undefined)).toBe(false);
+ });
+});
diff --git a/test/relational-plan.test.ts b/test/relational-plan.test.ts
new file mode 100644
index 0000000000..b77ce6f255
--- /dev/null
+++ b/test/relational-plan.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Multi-relation planner (pure). Development frames written for this test;
+ * the held-out composed-question wording in gbrain-evals is deliberately not
+ * mirrored.
+ *
+ * Protects: 2-3 relation questions become anchor-outward hop chains with the
+ * right direction per surface form; coordination, negation, time and
+ * multi-entity questions are refused (never guessed); single-relation queries
+ * stay `not_applicable` so the one-hop parser keeps them.
+ */
+import { describe, test, expect } from 'bun:test';
+import { parseRelationalPlan, isRelationalQuery } from '../src/core/search/relational-plan.ts';
+
+type Hop = [string, 'object' | 'subject'];
+const shape = (q: string) => {
+ const r = parseRelationalPlan(q);
+ if (r.kind !== 'plan') return r.kind;
+ return { anchor: r.plan.anchor, hops: r.plan.hops.map(h => [h.linkTypes[0], h.toward] as Hop), exclude: r.plan.excludeAnchor };
+};
+
+const PLANS: Array<[string, string, Hop[], boolean]> = [
+ ['Who founded the companies that Alice Example invested in?', 'Alice Example', [['invested_in', 'object'], ['founded', 'subject']], false],
+ ['Who invested in companies founded by Alice Example?', 'Alice Example', [['founded', 'object'], ['invested_in', 'subject']], false],
+ ['founders of companies Bob Example invested in', 'Bob Example', [['invested_in', 'object'], ['founded', 'subject']], false],
+ ['Who are the founders of the companies Alice Example advises?', 'Alice Example', [['advises', 'object'], ['founded', 'subject']], false],
+ ['investors in the companies founded by Carol Example', 'Carol Example', [['founded', 'object'], ['invested_in', 'subject']], false],
+ ['Which companies did the investors of acme-example also back?', 'acme-example', [['invested_in', 'subject'], ['invested_in', 'object']], true],
+ ['Which companies were founded by the investors of acme-example?', 'acme-example', [['invested_in', 'subject'], ['founded', 'object']], false],
+ ['Which meetings did the founders of acme-example attend?', 'acme-example', [['founded', 'subject'], ['attended', 'object']], false],
+ ['Who else invested in the companies Bob Example invested in?', 'Bob Example', [['invested_in', 'object'], ['invested_in', 'subject']], true],
+ ["Who are Alice Example's co-investors?", 'Alice Example', [['invested_in', 'object'], ['invested_in', 'subject']], true],
+ ['Who works at the companies backed by fund-a?', 'fund-a', [['invested_in', 'object'], ['works_at', 'subject']], false],
+ ['Who advises the companies that Dave Example founded?', 'Dave Example', [['founded', 'object'], ['advises', 'subject']], false],
+ ['Which investors backed the companies Alice Example founded?', 'Alice Example', [['founded', 'object'], ['invested_in', 'subject']], false],
+ ['Which other investors backed the companies Alice Example backed?', 'Alice Example', [['invested_in', 'object'], ['invested_in', 'subject']], true],
+ ['Which other companies did the investors in companies founded by Carol Example back?', 'Carol Example',
+ [['founded', 'object'], ['invested_in', 'subject'], ['invested_in', 'object']], true],
+ // Polite lead-ins, relative "in which"/"for which", and phrasal relations.
+ ['Could you tell me who the founders are of the companies in which Alice Example has invested?', 'Alice Example',
+ [['invested_in', 'object'], ['founded', 'subject']], false],
+ ['Could you tell me which investors backed the businesses established by Bob Example?', 'Bob Example',
+ [['founded', 'object'], ['invested_in', 'subject']], false],
+ ['Please list the founders of the startups for which Carol Example serves as an advisor', 'Carol Example',
+ [['advises', 'object'], ['founded', 'subject']], false],
+ ['Which individuals founded the companies in which Dave Example holds an investment?', 'Dave Example',
+ [['invested_in', 'object'], ['founded', 'subject']], false],
+ ['Which other parties have invested in the companies that Erin Example has funded?', 'Erin Example',
+ [['invested_in', 'object'], ['invested_in', 'subject']], true],
+ // Possessive founded forms bind to the entity first.
+ ["who put money into Alice Example's startups", 'Alice Example', [['founded', 'object'], ['invested_in', 'subject']], false],
+ ["Which other companies did the backers of Bob Example's founded companies also invest in?", 'Bob Example',
+ [['founded', 'object'], ['invested_in', 'subject'], ['invested_in', 'object']], true],
+ // A back-reference continues the chain instead of coordinating it.
+ ['Carol Example advises some companies, who founded them?', 'Carol Example', [['advises', 'object'], ['founded', 'subject']], false],
+ ['Dave Example invested in which companies, and who founded them?', 'Dave Example', [['invested_in', 'object'], ['founded', 'subject']], false],
+ // The co-relation already walks out and back; its verb is not another hop.
+ ['Who are the co-investors in the companies that Erin Example has invested in?', 'Erin Example',
+ [['invested_in', 'object'], ['invested_in', 'subject']], true],
+];
+
+describe('parseRelationalPlan: plans', () => {
+ for (const [q, anchor, hops, exclude] of PLANS) {
+ test(q, () => {
+ expect(shape(q)).toEqual({ anchor, hops, exclude });
+ });
+ }
+
+ test('a "who"/"which companies" head constrains a last hop whose relation allows several page types', () => {
+ const r = parseRelationalPlan('Who invested in companies founded by Alice Example?');
+ expect(r.kind === 'plan' && r.plan.hops[1].nodeType).toBe('person');
+ });
+});
+
+describe('parseRelationalPlan: refusals', () => {
+ for (const [q, reason] of [
+ ['Which companies did Alice Example found and invest in?', 'coordination'],
+ ['Who advised the companies that Bob Example funded in 2021?', 'time'],
+ ['Who founded companies that Alice Example did not invest in?', 'negation'],
+ ['Who used to work at companies backed by fund-a?', 'time'],
+ ['How many founders of companies backed by fund-a are there?', 'count'],
+ ['Who founded the companies "Alice" invested in?', 'quoted'],
+ ] as const) {
+ test(q, () => {
+ const r = parseRelationalPlan(q);
+ expect(r.kind).toBe('unsupported');
+ expect(r.kind === 'unsupported' && r.reason).toContain(reason);
+ });
+ }
+
+ test('a chain whose page types disagree is refused', () => {
+ expect(parseRelationalPlan("Who invested in acme-example's founders' companies?").kind).toBe('unsupported');
+ });
+});
+
+describe('single-relation and non-relational queries stay with the one-hop parser', () => {
+ for (const q of [
+ 'who invested in widget-co', "widget-co's investors", 'investors in acme-co', 'list the funders of novapay',
+ 'who backs quanta?', 'who is the founder of mindbridge', "helio's co-founders", 'founders of quanta',
+ "novapay's employees", 'who is employed by helio', 'people who work for acme-co', "mindbridge's advisors",
+ 'which companies has alice-example backed?', "fund-a's portfolio companies", 'who does bob-example work for',
+ "carol-example's employer", 'what companies did dave-example found?', 'which startups does erin-example advise',
+ 'relationship between fund-a and fund-b', 'how do bob-example and carol-example know each other',
+ 'who can introduce me to alice-example?', 'Who attended the Q3 board meeting?', 'notes from the offsite',
+ 'summarize the q3 board deck', 'who invested time in learning Rust', 'what is the capital structure of a seed round',
+ 'who invested in "Acme Example"?', 'Who has a "40 under 40" mention?',
+ 'Who among our founders worked at acme-example?', 'Which of my investors advise widget-co?',
+ ]) {
+ test(q, () => {
+ expect(parseRelationalPlan(q).kind).toBe('not_applicable');
+ });
+ }
+
+ test('linear time on a long adversarial input', () => {
+ const q = `${'founders of investors of '.repeat(20)}x`.slice(0, 512);
+ const started = performance.now();
+ parseRelationalPlan(q);
+ expect(performance.now() - started).toBeLessThan(50);
+ });
+});
+
+describe('isRelationalQuery', () => {
+ test('a planned chain counts as relational only when the planner is on', () => {
+ const q = 'Who founded the companies that Alice Example invested in?';
+ expect(isRelationalQuery(q, true)).toBe(true);
+ expect(isRelationalQuery(q, false)).toBe(false);
+ expect(isRelationalQuery('who invested in widget-co', false)).toBe(true);
+ });
+});
diff --git a/test/relational-recall.test.ts b/test/relational-recall.test.ts
index 120b22fd8a..59cf7c9b03 100644
--- a/test/relational-recall.test.ts
+++ b/test/relational-recall.test.ts
@@ -10,7 +10,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
-import { buildRelationalArm, ensureRelationalEvidenceSlot } from '../src/core/search/relational-recall.ts';
+import { buildRelationalArm, ensureRelationalEvidenceSlot, readRecentRelationalFailures } from '../src/core/search/relational-recall.ts';
import { hybridSearch } from '../src/core/search/hybrid.ts';
import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { probeEmbeddingDim } from './fixtures/retrieval-quality/relational/corpus.ts';
@@ -290,3 +290,75 @@ describe('hybridSearch guarantees page-1 relational evidence (#3995)', () => {
expect(meta?.relational_evidence_slot).toBeUndefined();
}, 60_000);
});
+
+describe('buildRelationalArm: multi-hop planner and one-hop orientation', () => {
+ beforeAll(async () => {
+ await eng.putPage('people/frank-example', { type: 'person', title: 'Frank Example', compiled_truth: 'Frank builds payment rails.', timeline: '' });
+ await installFixtureChunks(eng, 'people/frank-example', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Frank builds payment rails.' }]);
+ await installFixtureChunks(eng, 'companies/widget-co', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'A payments company.' }]);
+ // Written on the company page: stored company → person.
+ await eng.addLink('companies/widget-co', 'people/frank-example', 'founded by Frank', 'founded', 'markdown');
+ });
+ const CHAIN_Q = 'Who founded the companies that Alice Example invested in?';
+
+ test('a two-relation question walks the chain: answer plus the support page, with evidence', async () => {
+ let meta: any;
+ const list = await buildRelationalArm(eng, CHAIN_Q, { planner: true, onMeta: m => { meta = m; } });
+ const frank = list.find(r => r.slug === 'people/frank-example')!;
+ expect(frank.relational).toMatchObject({ role: 'answer', seed: 'people/alice-example', hop: 2 });
+ expect(frank.relational!.edges.map(e => e.link_type)).toEqual(['invested_in', 'founded']);
+ expect(list.find(r => r.slug === 'companies/widget-co')?.relational?.role).toBe('support');
+ expect(meta).toMatchObject({ kind: 'chain', fired: true, plan: { status: 'fired', anchor: 'Alice Example', answers: 1 } });
+ });
+
+ test('planner off: the arm output for the same question is exactly the pre-planner output', async () => {
+ const off = await buildRelationalArm(eng, CHAIN_Q, {});
+ const explicitOff = await buildRelationalArm(eng, CHAIN_Q, { planner: false });
+ expect(JSON.stringify(explicitOff)).toBe(JSON.stringify(off));
+ expect(off.some(r => r.relational !== undefined)).toBe(false);
+ });
+
+ test('an unsupported chain (coordination) runs no relational arm instead of a one-hop guess', async () => {
+ let meta: any;
+ const list = await buildRelationalArm(eng, 'Which companies did Alice Example found and invest in?', { planner: true, onMeta: m => { meta = m; } });
+ expect(list).toEqual([]);
+ expect(meta.plan).toMatchObject({ status: 'unsupported' });
+ });
+
+ test('an unresolved anchor reports anchor_not_found and returns the one-hop path\'s output', async () => {
+ let meta: any;
+ const q = 'Who founded the companies that Nobody Example invested in?';
+ const planned = await buildRelationalArm(eng, q, { planner: true, onMeta: m => { meta = m; } });
+ expect(meta.plan).toMatchObject({ status: 'anchor_not_found' });
+ expect(JSON.stringify(planned)).toBe(JSON.stringify(await buildRelationalArm(eng, q, {})));
+ });
+
+ test('a chain error is audited and the one-hop path answers instead', async () => {
+ const original = eng.relationalChainHop;
+ let meta: any;
+ eng.relationalChainHop = async () => { throw new Error('chain boom'); };
+ try {
+ const planned = await buildRelationalArm(eng, CHAIN_Q, { planner: true, onMeta: m => { meta = m; } });
+ expect(meta.errored).toBe(true);
+ eng.relationalChainHop = original;
+ expect(JSON.stringify(planned)).toBe(JSON.stringify(await buildRelationalArm(eng, CHAIN_Q, {})));
+ expect(readRecentRelationalFailures().some(f => f.query_kind === 'chain' && f.error_summary.includes('chain boom'))).toBe(true);
+ } finally {
+ eng.relationalChainHop = original;
+ }
+ });
+
+ test('the literal all-sources scope stays fail-closed for chains', async () => {
+ let meta: any;
+ const list = await buildRelationalArm(eng, CHAIN_Q, { planner: true, sourceId: '__all__', onMeta: m => { meta = m; } });
+ expect(list.some(r => r.relational !== undefined)).toBe(false);
+ expect(meta.plan).toMatchObject({ status: 'anchor_not_found' });
+ });
+
+ test('one-hop orientation finds a founder written on the company page', async () => {
+ const plain = await buildRelationalArm(eng, 'who founded widget-co', {});
+ const oriented = await buildRelationalArm(eng, 'who founded widget-co', { orientOneHop: true });
+ expect(plain.map(r => r.slug)).not.toContain('people/frank-example');
+ expect(oriented.map(r => r.slug)).toContain('people/frank-example');
+ });
+});
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index a3cb3f3c97..a92019c0e5 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -88,6 +88,9 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
relational_retrieval_depth: 2,
// ranker wave (R1) — relational rerank pin, 3 in every bundle (0 = off).
relational_rerank_pin: 3,
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.
keyword_arm_confidence_floor: null,
// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).
@@ -131,6 +134,9 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
relational_retrieval_depth: 2,
// ranker wave (R1) — relational rerank pin, 3 in every bundle (0 = off).
relational_rerank_pin: 3,
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.
keyword_arm_confidence_floor: null,
// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).
@@ -172,6 +178,9 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {
relational_retrieval_depth: 2,
// ranker wave (R1) — relational rerank pin, 3 in every bundle (0 = off).
relational_rerank_pin: 3,
+ relational_planner: false,
+ relational_orient_onehop: null,
+ relational_chain_slots: 10,
// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.
keyword_arm_confidence_floor: null,
// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).
@@ -1096,3 +1105,32 @@ describe('ranker wave (R1) — relational_rerank_pin knob (relational rows bypas
expect(KNOBS_HASH_VERSION).toBe(30);
});
});
+
+describe('multi-hop planner knobs (relational_planner, relational_orient_onehop)', () => {
+ test('bundles ship the planner off and orientation following it', () => {
+ for (const m of ['conservative', 'balanced', 'tokenmax'] as const) {
+ expect(MODE_BUNDLES[m].relational_planner).toBe(false);
+ expect(MODE_BUNDLES[m].relational_orient_onehop).toBeNull();
+ }
+ });
+
+ test('config booleans parse; garbage falls through', () => {
+ expect(loadOverridesFromConfig({ 'search.relational_planner': 'true' }).relational_planner).toBe(true);
+ expect(loadOverridesFromConfig({ 'search.relational_planner': 'off' }).relational_planner).toBe(false);
+ expect(loadOverridesFromConfig({ 'search.relational_planner': 'maybe' }).relational_planner).toBeUndefined();
+ expect(loadOverridesFromConfig({ 'search.relational_orient_onehop': '0' }).relational_orient_onehop).toBe(false);
+ expect(loadOverridesFromConfig({ 'search.relational_chain_slots': '3' }).relational_chain_slots).toBe(3);
+ expect(loadOverridesFromConfig({ 'search.relational_chain_slots': '11' }).relational_chain_slots).toBeUndefined();
+ });
+
+ test('knobsHash: planner off (default or explicit) hashes like the pre-planner build; on, orientation and slots fold in', () => {
+ const dflt = knobsHash(resolveSearchMode({ mode: 'balanced' }));
+ const off = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { relational_planner: false, relational_chain_slots: 3 } }));
+ const on = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { relational_planner: true } }));
+ const onSlots = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { relational_planner: true }, perCall: { relational_chain_slots: 0 } }));
+ const onNoOrient = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { relational_planner: true, relational_orient_onehop: false } }));
+ const orientOnly = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { relational_orient_onehop: true } }));
+ expect(off).toBe(dflt);
+ expect(new Set([dflt, on, onSlots, onNoOrient, orientOnly]).size).toBe(5);
+ });
+});
diff --git a/test/search/relational-chain-delivery.test.ts b/test/search/relational-chain-delivery.test.ts
index 444d2c71e0..49918723e6 100644
--- a/test/search/relational-chain-delivery.test.ts
+++ b/test/search/relational-chain-delivery.test.ts
@@ -76,3 +76,28 @@ describe('budget and lean rows', () => {
expect(lean.relational).toBeDefined();
});
});
+
+describe('chain slots', () => {
+ const answer = row('people/bob-example', 1, { relational: evidence('answer') });
+ const support = row('companies/acme-example', 2, { relational: evidence('support') });
+
+ test('a fired chain leads page 1 in arm order (answers, then evidence pages); the rest follows', () => {
+ const pool = [row('a', 10, { score: 0.9 }), row('b', 11, { score: 0.8 }), { ...support, score: 0.1 }];
+ const r = ensureRelationalEvidenceSlot(pool, [answer, support], 3, 0, undefined, 10);
+ expect(r.pool.map(x => x.slug)).toEqual(['people/bob-example', 'companies/acme-example', 'a', 'b']);
+ expect(r.decision).toMatchObject({ action: 'chain_pinned', count: 2 });
+ expect(r.pool[0].score).toBeGreaterThan(r.pool[1].score);
+ expect(r.pool[1].score).toBeGreaterThanOrEqual(r.pool[2].score);
+ });
+
+ test('no chain rows (one-hop arm): the single evidence slot applies as before', () => {
+ const oneHop = row('people/carol-example', 3, { relational_seed: 'companies/acme-example' });
+ const r = ensureRelationalEvidenceSlot([row('a', 10), row('b', 11)], [oneHop], 2, 0, undefined, 10);
+ expect(r.decision?.action).toBe('injected');
+ });
+
+ test('later pages are untouched', () => {
+ const pool = [row('a', 10)];
+ expect(ensureRelationalEvidenceSlot(pool, [answer], 1, 1, undefined, 10).pool).toBe(pool);
+ });
+});