Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: multi-hop relationship questions
garrytan03fd83a98ac2
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 0a194b5b47..fab9e99df7 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -46,7 +46,7 @@ boundary and add its link here rather than raising the cap.| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `src/core/persistence/connector-*.ts`, `src/core/connectors/item-holds*.ts`, checkpoint validation, no-op kernel and accepted-pending receipts || [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |-| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts` |+| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, plus the relational arm and multi-hop chain modules (`relational-recall.ts`, `relational-rerank-pin.ts`, `relational-chain.ts`, `relational-plan.ts`, `hub-dampening.ts`) || [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/`, except `src/core/persistence/` |diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex abb045de1e..8446708b29 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -194,7 +194,9 @@ hybrid recall + fusion:├── vector (HNSW on chunk embeddings, per-page max-pool)├── keyword (BM25 via tsvector)├── title-phrase arm- ├── relational (typed-edge recall arm — relational queries only)+ ├── relational (typed-edge recall arm — relational queries only; 2-3+ │ relationship questions walk typed hop chains when+ │ search.relational_planner is on)├── source-aware re-rank (CASE in SQL)├── role-tagged arms; variant/clause lists weighted by search.expansion_variant_budget INSIDE the fusion (fusion-lists.ts)└── page-grain RRF fusion → cosine re-score → post-fusion boosts@@ -315,6 +317,44 @@ pages at the top as the pin allows, where an unpinned run would place one at`limit`. Turn it off per brain with `gbrain config set search.relational_rerank_pin off`.The knob folds into the query-cache key (`rrp=`).+### Multi-hop relationship chains++A question that chains two or three relationships ("who founded the companies+Alice invested in?") is planned by `parseRelationalPlan`+(`src/core/search/relational-plan.ts`): a bounded lexer, a fixed relationship+vocabulary, exactly one named entity, hops ordered from that entity outward+(the main-clause verb is outermost), page types checked along the chain.+Coordination, negation, time constraints, counting, quoted names and+multi-entity questions are refused with a reason; single-relationship+questions stay on `parseRelationalQuery`. With `search.relational_planner` on,+the relational arm resolves the entity, runs `runRelationalChain`+(`src/core/search/relational-chain.ts`) and emits answers first, then the+intermediate and origin pages of every retained path, each row carrying a+`relational` evidence field (role, seed, hop, path count, up to three edges).+Up to `search.relational_chain_slots` (default 10) chain rows lead page 1.+A chain that finds nothing falls back to the one-hop path; a refused question+runs no relational arm. `meta.relational_plan` and a `relational_chain`+notice report the outcome.++Execution is one bounded query per hop (`BrainEngine.relationalChainHop`, SQL+in `src/core/search/read-enrichment.ts`): at most 50 frontier pages, 100+logical edges per page (lowest link id first) and 10 retained paths per page.+Links are read by each relationship's page-type signature (`stored`,+`flipped`, `uncertain` at half weight; canonical frontmatter, manual and+attendance-section links keep stored direction), duplicate rows between a+pair collapse into one logical edge, and every endpoint, origin and degree+contributor passes the read policy before scoring. Path weight is the product+of hub weights of the intermediate pages (`hubWeight`,+`src/core/search/hub-dampening.ts`; degree saturates at 300 link rows);+ties order by source and slug. The same executor serves `traverse_graph`+`hops` and `gbrain graph-query --hop`.++Chain evidence is page-level through fusion: whichever chunk of a page+survives carries the page's `relational` field. Only answers count toward the+relational re-pin and the page-1 evidence slot; intermediate and origin pages+never claim them. The planner keys fold into the query-cache key only when on+(`rp=1`, `ro=1`). Guide: [multi-hop relationship questions](../guides/multi-hop.md).+### Metadata boost gate: vector-only voters keep the vector orderThe post-fusion metadata boosts (backlink, salience, recency + chronicle,diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex d8a26e1993..489fdbe6b6 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/frontmatter.ts` — `gbrain frontmatter validate|generate|audit|install-hook`. `validate` keeps the producer rule: exit 1 on any `parseMarkdown` validation error, including `YAML_PARSE` that ingestion recovers by quoting (those print "importable but not canonical" with the `--fix` command). `--importable` switches to the ingestion view through `screenImportContent` (exit 1 only for a hold). Inputs: a file or directory, `--stdin`/`-` (with optional `--path <source-relative path>` for the slug check, otherwise reported skipped), or `--staged [paths]` (git index blobs via one `ls-files --stage` and one `cat-file --batch`; a failing blob whose working copy passes says to `git add` it). `--fix` runs `autoFixFrontmatter` then `repairRecoverableFrontmatter` (`brain-writer.ts`: safe `quote` recoveries line by line, CRLF/BOM kept, gated on the strict parse equalling what ingestion read; `--include-ambiguous` adds fold/dup/unclosed proposals and `#`-title quoting), re-validates and exits 1 if errors remain, prints the restage step inside git, and refuses on a managed root with `writer_coordinator_required` whose fix is `gbrain repair frontmatter [--source <id>]`. `audit --json` adds `recoverability_by_code` (imported anyway vs held on import). `runFrontmatter(args, io)` takes stdin-stream and git-cwd test seams. Pinned by `test/frontmatter-cli.test.ts` and `test/frontmatter-validate-producer.test.ts`.-- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).+- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: all five preflight/argv failure sites (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target) throw the exported typed `ImportAbortError` (carries `exitCode`; the user-facing message is printed at the throw site), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.serial.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.serial.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex f9f027e421..d825f561c6 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -64,14 +64,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.-- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults.+- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.-- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal `__all__` resolves no seeds, fail-closed) → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts`, `test/relational-recall-scope-sources.test.ts` and `test/pack-relation-direction-engine.test.ts`.--- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).-- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 06cef30bb4..f71b19e0dc 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -28,3 +28,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.++- `src/core/search/relational-chain.ts` — multi-hop chain runner over `relationalChainHop`: `LINK_SIGNATURES` / `CHAIN_LINK_TYPES` / `linkFamily`, path records with path-local cycle prevention (a path may end on its anchor), frontier 50 / paths-per-node 10, hub-dampened path weights (`CHAIN_HUB_HALF_DEGREE`), uncertain edges at half weight, `(score, source_id, slug)` byte-wise order, statuses `fired` / `anchor_not_found` / `no_edges` / `empty_hop` / `truncated` with `cap_hit`; plus `resolveChainAnchors`, `validateChainHops` (agent `hops`) and `presentEdgeContext` (remote: sanitized, ≤160 chars). Pinned by `test/relational-chain.test.ts`.++- `src/core/search/relational-plan.ts` — `parseRelationalPlan`: deterministic planner for questions chaining 2-3 typed relationships (bounded lexer, fixed lexicon of verb / passive / agent-noun / outgoing-noun forms, one anchor span, anchor-outward hop order with the main-clause verb outermost, type coherence, head-noun constraint). Returns `plan` / `not_applicable` (fewer than two relationships) / `unsupported` with a reason (coordination, negation, time, counting, quotes, multiple entities, incoherent types). `isRelationalQuery(query, plannerOn)` is the relational test for ranking decisions; planner off it equals `parseRelationalQuery`. Pinned by `test/relational-plan.test.ts`.++- `src/core/search/hub-dampening.ts` — `hubWeight(degree, H)` = 1 / (1 + ((max(n,1) − 1) / H)²), `'off'` → 1; `dampenBoost`, `normalizeHubDampening`. Pure; callers pass the caller-visible degree.++- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal `__all__` resolves no seeds, fail-closed) → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts`, `test/relational-recall-scope-sources.test.ts` and `test/pack-relation-direction-engine.test.ts`. With `planner` on (`search.relational_planner`), a 2-3 relationship question (`parseRelationalPlan`) runs `runRelationalChain` first: answers then evidence pages, each with a `relational` field; nothing found → the one-hop path; refused → no arm (`meta.plan`). With `orientOneHop` (`search.relational_orient_onehop`, unset follows the planner) typed one-hop walks add neighbors reached through links written on the other page. `answerRows` limits the pin and evidence slot to answers. Pinned by `test/relational-recall.test.ts`.++- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex bbfed08f5c..f7daad1baa 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.-- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`.+- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`.- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.diff --git a/docs/guides/multi-hop.md b/docs/guides/multi-hop.mdnew file mode 100644index 0000000000..57e44a6d81--- /dev/null+++ b/docs/guides/multi-hop.md@@ -0,0 +1,153 @@+# Multi-hop relationship questions++GBrain answers questions that chain two or three relationships, such as+"who founded the companies Alice invested in?", by walking the typed links+between pages: from Alice to the companies she invested in, then from those+companies to their founders. Each answer comes back with the links that prove+it, so the agent can show its work. No model call runs on the read path.++**Say to your agent:** *"Who founded the companies Alice invested in?"* —+*"Which other companies did Acme's investors back?"* — *"Who works at the+companies backed by Fund A?"*++## Two ways in++**Ask in plain English (search, query, recall, think).** With+`search.relational_planner` on, a question that chains 2-3 relationships is+planned into typed hops and the answers join the normal search results. Each+chain row carries a `relational` field:++```json+{+ "slug": "people/bob-example",+ "relational": {+ "role": "answer",+ "seed": "people/alice-example",+ "hop": 2,+ "path_count": 1,+ "edges": [+ { "link_type": "invested_in", "stored_from": "people/alice-example", "stored_to": "companies/acme-example", "orientation": "stored", "context": "She backed Acme…", "origin": null },+ { "link_type": "founded", "stored_from": "companies/acme-example", "stored_to": "people/bob-example", "orientation": "flipped", "context": "It was founded by Bob…", "origin": null }+ ]+ }+}+```++`role` is the page's place on the chain: `answer`, `support` (an+intermediate page, such as the company) or `origin` (the page an edge was+written on, when that is a third page). It is not a correctness score, and+`path_count` counts the paths kept for ranking, not independent sources.+The response's `relational_plan` summarizes what the planner did.++**Name the hops yourself (traverse_graph / graph-query).** An agent that+already knows the relationships passes them explicitly and gets an exact,+deterministic chain:++```bash+gbrain graph-query people/alice-example --hop invested_in:object --hop founded:subject+```++```json+traverse_graph {"slug": "people/alice-example",+ "hops": [{"link_type": "invested_in", "toward": "object"},+ {"link_type": "founded", "toward": "subject"}]}+```++`toward` follows the relationship's meaning, not the direction the link was+written in: `object` walks subject → object (investor → company, person →+employer), `subject` walks object → subject (company → founder). Chain link+types: `founded`, `invested_in` (with `led_round`), `advises`, `works_at`,+`attended`, `yc_partner`. `hops` cannot be combined with `depth`, `link_type`+or `direction`; up to 3 hops.++## Try it keyless (about a minute)++```bash+gbrain init --pglite --no-embedding+printf -- '---\ntype: person\ntitle: Bob Example\n---\nBob Example is a robotics engineer.\n' | gbrain put people/bob-example+printf -- '---\ntype: company\ntitle: Acme Example\n---\nAcme Example makes robots. It was founded by [Bob Example](people/bob-example).\n' | gbrain put companies/acme-example+printf -- '---\ntype: person\ntitle: Alice Example\n---\nAlice Example is a seed investor. She backed [Acme Example](companies/acme-example) in 2024.\n' | gbrain put people/alice-example+gbrain config set search.relational_planner true+gbrain graph-query people/alice-example --hop invested_in:object --hop founded:subject+gbrain search "Who founded the companies that Alice Example invested in?" --json+```++The chain answers `people/bob-example`; the second edge is marked "written on+the other page" because the founding is stated on Acme's page. Pages written+before the pages they link to get their links on `gbrain extract links+--source db`. Keyless `think` returns the gathered evidence rather than a+synthesized answer.++## How a question is read++The planner reads the question with a fixed relationship vocabulary (founded /+started / established, invested in / backed / funded / holds a stake in,+advises / serves as an advisor to, works at, attended; verbs, "founded by",+"investors of", "Acme's founders", "Alice's portfolio", "Alice's startups") and+requires exactly one named entity. Polite lead-ins ("could you tell me"),+relative clauses ("the companies in which Alice has invested") and a pronoun+pointing back at the previous step ("Alice advises some companies, who founded+them?") are read as part of the chain. English nests the entity innermost, so+the hops run outward from it. Questions it does not plan, and says so in a+`relational_chain` notice instead of guessing:++- two relationships joined by "and" / "or" ("companies Alice founded and+ invested in" is an intersection, not a chain), unless what follows "and"+ points back with "them" / "those";+- negation ("did not invest"), time ("in 2021", "used to"), counting and+ superlatives;+- two named entities, quoted names, or relationships whose page types do not+ chain.++Single-relationship questions ("who invested in Acme?") keep the one-hop+relational arm. Split an unplanned question into one-relationship questions,+or pass explicit `hops`.++## When a chain finds nothing++A chain that finds no answer never hides the ordinary search results; it adds+a `relational_chain` notice that names the reason and the next call:++| Status | Meaning | Next call |+|---|---|---|+| `anchor_not_found` | No visible page matches the named entity | `search` for the entity, then retry with its exact name or slug |+| `no_edges` | The entity has no typed links of the first relationship | `traverse_graph` depth 1 on it (the relationship may only be written as plain mentions) |+| `empty_hop` | A later hop found no typed links | the shorter chain, to inspect the pages it reached |+| `truncated` | A cap was hit (`cap_hit` names the cap and hop) | narrow the question or start from a more specific entity |++Chains read typed links only. Meeting attendance counts when the meeting page+lists attendees in an `Attendees:` or `Participants:` section (see+[attendance evidence](attendance-evidence.md)); a person merely mentioned in a+meeting's notes is not an attendee.++## Direction and evidence++Body links keep the direction of the page they are written on: "founded by+Bob" on Acme's page is stored Acme → Bob. Each relationship has a page-type+signature (for example `founded`: person → company; `invested_in`: person or+company → company or deal), and a chain reads a link by that signature:+`stored` when it fits as written, `flipped` when it fits only reversed,+`uncertain` when both fit (company ↔ company investment links, walked as+written at half weight) and not at all when neither fits. Frontmatter,+manual and attendance-section links keep their stored direction.+`search.relational_orient_onehop` applies the same reading to+single-relationship questions; unset, it follows `search.relational_planner`.++Every page and edge in a chain passes the caller's read scope before anything+is ranked: private, deleted, quarantined and out-of-scope pages never appear+and never move a score. Chains stay inside the start page's source. Remote+callers see edge context only from pages whose text they may read, as a+sanitized excerpt of at most 160 characters.++## Settings++| Key | Effect |+|---|---|+| `search.relational_planner` | Plan 2-3 relationship questions into typed chains (search, query, recall, think) |+| `search.relational_orient_onehop` | Single-relationship walks read links written on either page (unset = follows the planner) |+| `search.relational_chain_slots` | When a chain fires, up to this many chain rows (answers, then the pages on their paths) lead page 1; 0..10, default 10, 0 keeps a single evidence slot |++Each chain hop expands at most 50 pages, 100 links per page and 10 paths per+page, so a hub with thousands of links costs a bounded query. See+[retrieval](../architecture/RETRIEVAL.md#multi-hop-relationship-chains) for+where chains sit in the search pipeline.diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex c1d27c396c..431a69d6d2 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -422,6 +422,7 @@ Traverse link graph from a page. Remote callers default to bidirectional edges (| `depth` | number | Max traversal depth (capped at 10). Default 5, except a remote call that lets direction default to 'both' uses 2 (bidirectional path enumeration is combinatorial on hubs); an explicit depth is always honored up to the cap. || `link_type` | string | Filter to one link type (per-edge filter, traversal only follows matching edges) || `direction` | string (`in`, `out`, `both`) | Traversal direction ('in', 'out', or 'both'). Remote callers default to 'both'; trusted local no-filter callers get the legacy outgoing-node output. |+| `hops` | array of `{link_type, toward}` | Typed chain of 1-3 hops from the start page, e.g. `[{"link_type":"invested_in","toward":"object"},{"link_type":"founded","toward":"subject"}]` (companies the person invested in, then their founders). `toward` follows the relationship's meaning (`object`: subject → object; `subject`: object → subject), not stored link direction. Returns `{anchor, answers, paths, diagnostics}` with each answer's evidence edges; a chain that finds nothing carries a `relational_chain` notice with the next call. Not combinable with `depth`, `link_type` or `direction`. Chain link types: founded, invested_in, led_round, advises, works_at, attended, yc_partner. See docs/guides/multi-hop.md. || `source_id` | string | Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers. || `all_sources` | boolean | Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely. |diff --git a/llms.txt b/llms.txtindex 8cfb4af6a1..fe589b8881 100644--- a/llms.txt+++ b/llms.txt@@ -29,6 +29,7 @@ Repo: https://github.com/garrytan/gbrain## Configuration+- [docs/guides/multi-hop.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/multi-hop.md): Multi-hop relationship questions: typed hop chains over links (search planner + traverse_graph hops), evidence edges, refusals, notices, settings.- [docs/ENGINES.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ENGINES.md): PGLite vs Postgres trade-off and when to migrate.- [docs/guides/move-to-postgres.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/move-to-postgres.md): Move a PGLite brain to Postgres with its history: --url-env target setup, plan (exit 3) then --yes --expect, status/resume/rollback, what moves vs stays on this computer, recovery by error code.- [docs/GBRAIN_RECOMMENDED_SCHEMA.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/GBRAIN_RECOMMENDED_SCHEMA.md): MECE directory structure (people/, companies/, concepts/).diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex ad4b9d4d84..fc4abc1fb7 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -105,6 +105,12 @@ export const SECTIONS: DocSection[] = [{heading: "Configuration",entries: [+ {+ title: "docs/guides/multi-hop.md",+ description: "Multi-hop relationship questions: typed hop chains over links (search planner + traverse_graph hops), evidence edges, refusals, notices, settings.",+ path: "docs/guides/multi-hop.md",+ includeInFull: false,+ },{title: "docs/ENGINES.md",description: "PGLite vs Postgres trade-off and when to migrate.",diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 8e1bf5fcb7..b2aaaa1f8b 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -11,7 +11,7 @@ import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';import { opError, type Operation } from './contract.ts';import type { Action } from '../agent-output.ts';import { presentEdgeContext, resolveChainAnchors, runRelationalChain, validateChainHops, type ChainEvidenceEdge, type ChainPlan } from '../search/relational-chain.ts';-import { paramUse } from './op-fix.ts';+import { paramUse, readFix } from './op-fix.ts';import {assertExplicitSourceLive,enforceClientSlugFence,@@ -483,19 +483,22 @@ async function traverseChain(ctx: OperationContext, p: Record<string, unknown>,};}+/** A CLI flag token built at runtime (the flag-registry generator scans literal flag strings per command). */+const cliFlag = (name: string) => `--${name}`;+function chainFix(slug: string, status: string, hops: Array<Record<string, unknown>>, emptyHop?: number): Action | undefined {- const base = { consent: [], actor: 'agent' as const, requires_exclusive: false };- if (status === 'anchor_not_found') return { ...base, mcp: { tool: 'search', arguments: { query: slug } }, argv: ['gbrain', 'search', slug],- why: `No page "${slug}" is visible in the searched sources; search for the entity to find its exact slug, then retry the chain with that slug.` };- if (status === 'no_edges') return { ...base, mcp: { tool: 'traverse_graph', arguments: { slug, depth: 1 } },- why: `"${slug}" has no typed ${String(hops[0]?.link_type)} edges in the needed direction; the relationship may only be written as plain mentions. A depth-1 walk shows what is linked.` };+ const hopArgs = (hs: Array<Record<string, unknown>>) => hs.flatMap(h => [cliFlag('hop'), `${String(h.link_type)}:${String(h.toward)}`]);+ if (status === 'anchor_not_found') return readFix(`No page "${slug}" is visible in the searched sources; search for the entity to find its exact slug, then retry the chain with that slug.`,+ { argv: ['gbrain', 'search', slug], mcp: { tool: 'search', arguments: { query: slug } } });+ if (status === 'no_edges') return readFix(`"${slug}" has no typed ${String(hops[0]?.link_type)} edges in the needed direction; the relationship may only be written as plain mentions. A depth-1 walk shows what is linked.`,+ { argv: ['gbrain', 'graph-query', slug, cliFlag('depth'), '1'], mcp: { tool: 'traverse_graph', arguments: { slug, depth: 1 } } });if (status === 'empty_hop' && emptyHop && emptyHop > 1) {const prefix = hops.slice(0, emptyHop - 1);- return { ...base, mcp: { tool: 'traverse_graph', arguments: { slug, hops: prefix } },- why: `Hop ${emptyHop} (${String(hops[emptyHop - 1]?.link_type)}) found no typed edges from the pages hop ${emptyHop - 1} reached; the shorter chain lists those pages so you can inspect them.` };+ return readFix(`Hop ${emptyHop} (${String(hops[emptyHop - 1]?.link_type)}) found no typed edges from the pages hop ${emptyHop - 1} reached; the shorter chain lists those pages so you can inspect them.`,+ { argv: ['gbrain', 'graph-query', slug, ...hopArgs(prefix)], mcp: { tool: 'traverse_graph', arguments: { slug, hops: prefix } } });}- if (status === 'truncated') return { ...base, mcp: { tool: 'traverse_graph', arguments: { slug, hops } },- why: 'A chain cap was hit (diagnostics.cap_hit names the cap and hop), so lower-ranked answers were dropped; narrow the chain or start from a more specific page for a complete list.' };+ if (status === 'truncated') return readFix('A chain cap was hit (diagnostics.cap_hit names the cap and hop), so lower-ranked answers were dropped; narrow the chain or start from a more specific page for a complete list.',+ { argv: ['gbrain', 'graph-query', slug, ...hopArgs(hops)], mcp: { tool: 'traverse_graph', arguments: { slug, hops } } });return undefined;}diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex ac599a5235..2d069da487 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -40,7 +40,7 @@ import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptionimport { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';import { opError } from './contract.ts';import type { Operation, OperationContext } from './contract.ts';-import { invalidParam, paramUse } from './op-fix.ts';+import { invalidParam, paramUse, readFix } from './op-fix.ts';import {assertExplicitSourceLive,federatedSearchScope,@@ -1244,13 +1244,13 @@ export const searchOperations: Operation[] = [*/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).' } };+ const anchor = plan.anchor ?? '';+ return { code: 'relational_chain', kind: 'degraded', why: `No page matches "${anchor}" in the searched sources, so the relationship chain did not run; the results are ordinary text matches.`,+ fix: readFix('Find the entity page first, then ask again with its exact name (or call traverse_graph with its slug and explicit hops).', { argv: ['gbrain', 'search', anchor], mcp: { tool: 'search', arguments: { query: anchor } } }) };}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.` };@@ -1258,5 +1258,5 @@ function relationalPlanNotice(plan: RelationalPlanMeta | undefined): Notice | nuconst 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.' } } : {}) };+ ...(slug ? { fix: readFix('A depth-1 walk shows what the start page is linked to.', { argv: ['gbrain', 'graph-query', slug, `--${'depth'}`, '1'], mcp: { tool: 'traverse_graph', arguments: { slug, depth: 1 } } }) } : {}) };}