Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

search: typed multi-hop chain executor and traverse_graph hops

garrytanaae1ed5b61e1
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 12f477448e..acf203827e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,14 +16,14 @@ src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3250 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts)
src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
-src/core/engine.ts 2679 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract
+src/core/engine.ts 2689 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
-src/core/pglite-engine.ts 2982 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)
-src/core/postgres-engine.ts 2919 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)
+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 2125 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
+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/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)
diff --git a/src/commands/graph-query.ts b/src/commands/graph-query.ts
index b78ef31554..a764f50ce6 100644
--- a/src/commands/graph-query.ts
+++ b/src/commands/graph-query.ts
@@ -18,12 +18,17 @@ import type { BrainEngine } from '../core/engine.ts';
import type { GraphPath } from '../core/types.ts';
import { TRAVERSE_PATH_ROW_CAP } from '../core/engine-constants.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
-import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
+import { callRemoteTool, unpackToolResult, ignoredRemoteParams } from '../core/mcp-client.ts';
+import { CHAIN_LINK_TYPES, resolveChainAnchors, runRelationalChain, validateChainHops, type ChainDiagnostics, type ChainEvidenceEdge } from '../core/search/relational-chain.ts';
import { resolveSourceId, resolveSourceIdEngineFree, ALL_SOURCES } from '../core/source-resolver.ts';
interface Args {
slug?: string;
linkType?: string;
+ /** --hop <link_type>:<object|subject>, repeatable (a typed chain). */
+ hops: string[];
+ /** Flags the user passed explicitly (to reject combinations with --hop). */
+ explicit: Set<'type' | 'depth' | 'direction'>;
depth: number;
direction: 'in' | 'out' | 'both';
showHelp: boolean;
@@ -32,12 +37,14 @@ interface Args {
}
function parseArgs(args: string[]): Args {
- const out: Args = { depth: 5, direction: 'out', showHelp: false, includeForeign: false };
+ const out: Args = { depth: 5, direction: 'out', showHelp: false, includeForeign: false, hops: [], explicit: new Set() };
for (let i = 0; i < args.length; i++) {
const a = args[i];
- if (a === '--type' && i + 1 < args.length) out.linkType = args[++i];
- else if (a === '--depth' && i + 1 < args.length) out.depth = Number(args[++i]);
+ if (a === '--type' && i + 1 < args.length) { out.linkType = args[++i]; out.explicit.add('type'); }
+ else if (a === '--depth' && i + 1 < args.length) { out.depth = Number(args[++i]); out.explicit.add('depth'); }
+ else if (a === '--hop' && i + 1 < args.length) out.hops.push(args[++i]);
else if (a === '--direction' && i + 1 < args.length) {
+ out.explicit.add('direction');
const d = args[++i];
if (d === 'in' || d === 'out' || d === 'both') out.direction = d;
}
@@ -70,6 +77,16 @@ Options:
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: ${CHAIN_LINK_TYPES.join(', ')}.
+ 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
@@ -86,6 +103,8 @@ Examples:
-> 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
`);
}
@@ -173,6 +192,7 @@ export async function runGraphQuery(engine: BrainEngine, argv: string[]) {
process.exit(1);
}
const cfg = loadConfig();
+ if (args.hops.length > 0) return runChainQuery(engine, args, cfg);
if (isThinClient(cfg)) {
// The remote traverse_graph op has no source_id param: the server scopes
// the walk to the caller's grant. --source used to be dropped silently
@@ -283,3 +303,82 @@ function printTree(rootSlug: string, paths: GraphPath[], direction: 'in' | 'out'
walk(rootSlug, 0, new Set());
}
+
+type ChainResponse = {
+ anchor: string;
+ answers: Array<{ slug: string; source_id: string; path_count: number; score: number }>;
+ paths: Array<{ nodes: string[]; edges: ChainEvidenceEdge[] }>;
+ diagnostics: ChainDiagnostics;
+};
+
+/** `--hop` chains: local runs the shared executor, a thin client calls traverse_graph with `hops`. */
+async function runChainQuery(engine: BrainEngine, args: Args, cfg: ReturnType<typeof loadConfig>) {
+ const conflicts = [...args.explicit].map(f => `--${f}`);
+ if (conflicts.length) {
+ console.error(`--hop cannot be combined with ${conflicts.join(', ')}: each hop names its link type and direction, and the chain length is the number of hops.`);
+ process.exit(1);
+ }
+ const rawHops = args.hops.map(h => {
+ const [link_type, toward] = h.split(':');
+ return { link_type, toward };
+ });
+ const parsed = validateChainHops(rawHops);
+ if (!parsed.ok) {
+ const at = /^hops\[(\d+)\]\.(\w+)$/.exec(parsed.path);
+ const where = at ? `--hop ${args.hops[Number(at[1])]} (${at[2] === 'toward' ? '<toward>' : '<link_type>'})` : '--hop';
+ console.error(`${where}: ${parsed.problem}. Write each hop as <link_type>:<toward>, e.g. --hop invested_in:object --hop founded:subject`);
+ process.exit(1);
+ }
+ let res: ChainResponse;
+ if (isThinClient(cfg)) {
+ if (args.source !== undefined || args.includeForeign) {
+ console.error('gbrain graph-query does not accept --source or --include-foreign on a thin-client install (the server scopes the chain to your grant).');
+ process.exit(1);
+ }
+ const raw = await callRemoteTool(cfg!, 'traverse_graph', { slug: args.slug, hops: rawHops }, { timeoutMs: 30_000 });
+ const body = unpackToolResult<unknown>(raw);
+ const isChain = !!body && typeof body === 'object' && !Array.isArray(body) && Array.isArray((body as ChainResponse).answers);
+ if (ignoredRemoteParams(raw).includes('hops') || !isChain) {
+ console.error('The brain host runs an older gbrain without typed chains (traverse_graph ignored "hops"). Upgrade it (`gbrain upgrade` on the host) to use --hop.');
+ process.exit(1);
+ }
+ res = body as ChainResponse;
+ } else {
+ const sourceId = await resolveSourceId(engine, args.source ?? null);
+ const policy = args.includeForeign || sourceId === ALL_SOURCES ? {} : { sourceId };
+ const anchors = await resolveChainAnchors(engine, args.slug!, policy);
+ const { rows, diagnostics } = await runRelationalChain(engine, anchors, { hops: parsed.hops, excludeAnchor: false }, policy);
+ const answers = rows.filter(r => r.role === 'answer');
+ res = {
+ anchor: args.slug!,
+ answers: answers.map(r => ({ slug: r.slug, source_id: r.source_id, path_count: r.path_count, score: r.score })),
+ paths: answers.map(r => r.best_path),
+ diagnostics,
+ };
+ }
+ printChain(res, args.hops);
+}
+
+function printChain(res: ChainResponse, hops: string[]) {
+ const status = res.diagnostics.status;
+ if (status === 'anchor_not_found') {
+ console.log(`No page "${res.anchor}" in the searched sources. Find its exact slug with: gbrain search "${res.anchor}"`);
+ return;
+ }
+ if (res.answers.length === 0) {
+ const hop = res.diagnostics.empty_hop ?? 1;
+ console.log(`No answers: hop ${hop} (${hops[hop - 1]}) found no typed edges. The relationship may only be written as plain mentions; inspect with: gbrain graph-query ${res.anchor} --depth 1`);
+ return;
+ }
+ console.log(`${res.answers.length} answer${res.answers.length === 1 ? '' : 's'} for ${res.anchor} ${hops.map(h => `--hop ${h}`).join(' ')}:`);
+ res.answers.forEach((a, i) => {
+ console.log(`\n${a.slug} (paths ${a.path_count}, score ${a.score.toFixed(3)})`);
+ for (const e of res.paths[i]?.edges ?? []) {
+ const note = e.orientation === 'flipped' ? ' (written on the other page)' : e.orientation === 'uncertain' ? ' (direction uncertain)' : '';
+ console.log(` ${e.stored_from} -${e.link_type}-> ${e.stored_to}${note}${e.context ? `: "${e.context}"` : ''}`);
+ }
+ });
+ if (res.diagnostics.cap_hit) {
+ console.error(`\n(chain ${res.diagnostics.cap_hit.cap} cap hit at hop ${res.diagnostics.cap_hit.hop}; lower-ranked answers were dropped. Narrow the chain or start from a more specific page.)`);
+ }
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index bdc7a2ff53..15185ce3a9 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -67,7 +67,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
- 'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
+ 'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 19ed698f3e..494f78a123 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -7,7 +7,7 @@ import type {
Page, PageInput, PageFilters, GetPageOpts, PageReadScope, PageReadPolicy,
Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,
SearchResult, SearchOpts, ResolvedColumn,
- Link, GraphNode, GraphPath, RelationalFanoutRow, RelationalFanoutOpts,
+ Link, GraphNode, GraphPath, RelationalFanoutRow, RelationalFanoutOpts, ChainHopOpts, ChainHopEdge,
TimelineEntry, TimelineInput, TimelineOpts,
ChronicleTimelineRow, ChronicleTimelineOpts, LastSeenResult,
OntologyObservationInput, OntologyMergeResult, OntologyValue, OntologyDimensionStat,
@@ -1568,6 +1568,16 @@ export interface BrainEngine {
seeds: string[],
opts?: RelationalFanoutOpts,
): Promise<RelationalFanoutRow[]>;
+ /**
+ * One oriented expansion step of a multi-hop relational chain from up to a
+ * few dozen frontier page ids. Returns logical edges whose frontier side is
+ * the relation's subject (`toward: 'object'`) or object (`toward:
+ * 'subject'`), with every endpoint and origin authorized by the read policy
+ * BEFORE the caller scores anything, at most `neighborCap` edges per frontier
+ * node, same-source edges only, mentions excluded. Deterministic order:
+ * frontier id, lowest link id. Pinned by test/e2e/engine-parity.test.ts.
+ */
+ relationalChainHop(frontierPageIds: number[], opts: ChainHopOpts): Promise<ChainHopEdge[]>;
/**
* For a list of page ids, return how many inbound links each has.
* Used by hybrid search backlink boost. Single SQL query, not N+1.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 7382207ed5..a3b661fb89 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -349,6 +349,7 @@ export const NOTICE_CODES = {
post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },
facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },
+ relational_chain: { kind: 'degraded', summary: 'A typed relationship chain found no complete answer (start page not visible, no typed edges, an empty hop) or hit a cap; the notice names the hop and the next call.' },
held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },
recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index ce252b670e..b6788dc9d4 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -21,7 +21,7 @@ const MAX_KEYS = 10_000;
const TTL_MS = 24 * 60 * 60 * 1000;
export const COACHING_BUDGET_PER_SESSION = 2;
/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */
-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files']);
+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain']);
export interface NoticeAudience {
transport: Transport;
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 49f303bae7..8e1bf5fcb7 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -9,6 +9,8 @@ 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 {
assertExplicitSourceLive,
@@ -445,6 +447,58 @@ const TRAVERSE_DEPTH_CAP = 10;
const REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH = 2;
const DEFAULT_TRAVERSE_DEPTH = 5;
+/**
+ * traverse_graph with `hops`: an agent-structured typed chain over the same
+ * executor the search planner uses. Returns answers with the evidence edges of
+ * each best path and per-hop diagnostics; a chain that finds nothing is a
+ * successful result carrying a `relational_chain` notice with the next call.
+ */
+async function traverseChain(ctx: OperationContext, p: Record<string, unknown>, slug: string) {
+ const conflicts = (['depth', 'link_type', 'direction'] as const).filter(k => p[k] !== undefined);
+ if (conflicts.length) {
+ throw opError('invalid_params', `traverse_graph: hops cannot be combined with ${conflicts.join(', ')}.`,
+ `Drop ${conflicts.map(k => paramUse(ctx, k)).join(' and ')}: each hop already names its link type and direction (toward), and the chain length is the number of hops.`);
+ }
+ const parsed = validateChainHops(p.hops);
+ if (!parsed.ok) {
+ throw opError('invalid_params', `traverse_graph: ${parsed.path}: ${parsed.problem}.`,
+ `Fix ${parsed.path} and retry; omit hops to walk the graph without a chain.`);
+ }
+ const { policy } = await resolveLinkReadScope(ctx, p, 'traverse_graph');
+ const anchors = await resolveChainAnchors(ctx.engine, slug, policy);
+ const plan: ChainPlan = { hops: parsed.hops, excludeAnchor: false };
+ const { rows, diagnostics } = await runRelationalChain(ctx.engine, anchors, plan, policy);
+ const remote = ctx.remote !== false;
+ const edge = (e: ChainEvidenceEdge) => ({ ...e, context: presentEdgeContext(e.context, remote) });
+ const answers = rows.filter(r => r.role === 'answer');
+ const rawHops = p.hops as Array<Record<string, unknown>>;
+ const status = diagnostics.status;
+ const fix = chainFix(slug, status, rawHops, diagnostics.empty_hop);
+ if (status !== 'fired' && fix) ctx.emitNotice?.({ code: 'relational_chain', kind: 'degraded', why: fix.why, fix });
+ return {
+ anchor: slug,
+ answers: answers.map(r => ({ slug: r.slug, source_id: r.source_id, path_count: r.path_count, score: r.score })),
+ paths: answers.map(r => ({ nodes: r.best_path.nodes, edges: r.best_path.edges.map(edge) })),
+ diagnostics,
+ };
+}
+
+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.` };
+ 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.` };
+ }
+ 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.' };
+ return undefined;
+}
+
const traverse_graph: Operation = {
name: 'traverse_graph',
mutating: false,
@@ -456,11 +510,17 @@ const traverse_graph: Operation = {
depth: { type: 'number', description: `Max depth (cap ${TRAVERSE_DEPTH_CAP}).` },
link_type: { type: 'string', description: 'Follow only this link type.' },
direction: { type: 'string', description: 'Remote default both.', enum: ['in', 'out', 'both'] },
+ hops: {
+ type: 'array',
+ description: '≤3 typed hops, e.g. [{"link_type":"founded","toward":"subject"}]; toward: object|subject.',
+ items: { type: 'object', properties: { link_type: { type: 'string' }, toward: { type: 'string' } } },
+ },
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
handler: async (ctx, p) => {
const slug = p.slug as string;
+ if (p.hops !== undefined) return traverseChain(ctx, p, slug);
const linkType = p.link_type as string | undefined;
// #4666: remote callers (ctx.remote !== false — fail-closed) default to
// direction=both, so a node with only INBOUND typed edges stops reading
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index c0ffd32e22..31ff89c889 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -13,7 +13,7 @@ import { dropRowTypeArrayParsers, PgliteStatementCache } from './pglite-statemen
import { snapshotSchemaInputs } from './snapshot-schema-inputs.ts';
import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
-import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
+import { readRelationalFanout, readChainHop, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
import { PGlite } from '@electric-sql/pglite';
import type { Transaction } from '@electric-sql/pglite';
// Engine-live path: static top-level imports (scratch probe, #2674) — the
@@ -1959,6 +1959,10 @@ export class PGLiteEngine implements BrainEngine {
return readRelationalFanout(this.executeRaw.bind(this), seeds, opts);
}
+ async relationalChainHop(frontierPageIds: number[], opts: import('./types.ts').ChainHopOpts): Promise<import('./types.ts').ChainHopEdge[]> {
+ return readChainHop(this.executeRaw.bind(this), frontierPageIds, opts);
+ }
+
async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {
return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 5c84749d92..4c3a0b55eb 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -10,7 +10,7 @@ import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.t
import { composablePostgresTransaction } from './page-state/transactions.ts';
import type { PageReadScope } from './types.ts';
import type { PageReadPolicy } from './types.ts';
-import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
+import { readRelationalFanout, readChainHop, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';
import postgres from '#postgres'
import { traceSqlOptions } from './sql-trace.ts';
import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';
@@ -1649,6 +1649,10 @@ export class PostgresEngine implements BrainEngine {
return readRelationalFanout(this.executeRaw.bind(this), seeds, opts);
}
+ async relationalChainHop(frontierPageIds: number[], opts: import('./types.ts').ChainHopOpts): Promise<import('./types.ts').ChainHopEdge[]> {
+ return readChainHop(this.executeRaw.bind(this), frontierPageIds, opts);
+ }
+
async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {
return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);
}
diff --git a/src/core/search/hub-dampening.ts b/src/core/search/hub-dampening.ts
new file mode 100644
index 0000000000..cc77c4d559
--- /dev/null
+++ b/src/core/search/hub-dampening.ts
@@ -0,0 +1,27 @@
+/**
+ * Hub dampening: a node linked to many others carries less signal per link.
+ *
+ * `hubWeight(n, H) = 1 / (1 + ((max(n, 1) - 1) / H)^2)`, where H is the degree
+ * at which a boost is halved. Feed it the caller-visible degree (what the
+ * caller may read), never a global count. `'off'` or an unset H means no
+ * dampening (weight 1).
+ */
+export type HubDampening = 'off' | number;
+
+export function hubWeight(degree: number, h: HubDampening | undefined): number {
+ if (h === undefined || h === 'off' || !(h > 0) || !Number.isFinite(degree)) return 1;
+ const x = (Math.max(degree, 1) - 1) / h;
+ return 1 / (1 + x * x);
+}
+
+/** Shrink a multiplicative boost toward 1 by the hub weight of its node. */
+export function dampenBoost(factor: number, degree: number, h: HubDampening | undefined): number {
+ return 1 + (factor - 1) * hubWeight(degree, h);
+}
+
+/** `'off'`/false/null → 'off'; a positive number (or numeric string) → H; anything else → undefined (fall through). */
+export function normalizeHubDampening(v: unknown): HubDampening | undefined {
+ if (v === 'off' || v === false || v === null) return 'off';
+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
+ return Number.isFinite(n) && n > 0 ? n : undefined;
+}
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index eb8621fa34..45601fd105 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -1,6 +1,6 @@
-import type { PageReadScope, PageReadPolicy, AdjacencyRow, RelationalFanoutOpts, RelationalFanoutRow } from '../types.ts';
+import type { PageReadScope, PageReadPolicy, AdjacencyRow, RelationalFanoutOpts, RelationalFanoutRow, ChainHopOpts, ChainHopEdge } from '../types.ts';
import { unverifiedExtractionFragment } from '../extraction-review.ts';
-import { currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';
+import { currentTextProjectionFilter, protectedBodyFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
import { relationshipFilterSql } from '../link-validity.ts';
@@ -76,6 +76,158 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
}));
}
+/**
+ * Degree used for hub weighting saturates here: a node with at least this many
+ * readable typed link rows counts as this degree (its hub weight is already
+ * ~0.01). Below saturation the degree is the number of distinct neighbors the
+ * caller may read. Rows to unreadable neighbors, or written on unreadable
+ * origin pages, never count.
+ */
+export const CHAIN_DEGREE_SATURATION = 300;
+
+/** Integer ids inlined into SQL (never bound): see readAdjacencyBoosts for the generic-plan reason. */
+function inlineIds(ids: number[], label: string): string {
+ return `ARRAY[${ids.map(id => {
+ if (!Number.isSafeInteger(id)) throw new TypeError(`${label}: page id ${String(id)} is not an integer`);
+ return id;
+ }).join(',')}]::int[]`;
+}
+
+/**
+ * One oriented, authorized, bounded expansion step of a relational chain.
+ *
+ * Orientation: canonical provenance rows (frontmatter, manual, oriented
+ * attendance) keep stored direction; body-extracted rows are read by the
+ * relation's type signature: forward fit = stored, reverse fit = flipped,
+ * both = uncertain (stored direction), neither = not a hop. Every endpoint,
+ * origin and degree contributor passes the read policy before anything is
+ * returned; edge context is returned only when the evidence page's text is
+ * readable under the policy.
+ */
+export async function readChainHop(query: ReadQuery, frontier: number[], opts: ChainHopOpts): Promise<ChainHopEdge[]> {
+ if (!frontier.length || !opts.linkTypes.length) return [];
+ const ids = inlineIds([...new Set(frontier)], 'readChainHop');
+ // Pages are fetched by primary key behind an optimization fence: the read
+ // policy's archived-source EXISTS otherwise lets a statistics-less planner
+ // (PGLite) scan every page of a source per link row.
+ const byId = (idExpr: string) => `(SELECT * FROM pages WHERE id = ${idExpr} OFFSET 0)`;
+ const policy: PageReadPolicy = opts;
+ const params: unknown[] = [opts.linkTypes, opts.subjectTypes, opts.objectTypes, opts.degreeLinkTypes, Math.max(1, Math.min(opts.neighborCap, 1000))];
+ const branch = (frontierCol: 'from_page_id' | 'to_page_id', a: string) => {
+ const pf = pageReadFilter(`${a}f`, policy, params, true);
+ const pt = pageReadFilter(`${a}t`, policy, params, true);
+ const og = pageReadFilter(`${a}g`, policy, params, true);
+ const origin = `(${a}l.origin_page_id IS NULL OR EXISTS (SELECT 1 FROM ${byId(`${a}l.origin_page_id`)} ${a}g WHERE ${og}))`;
+ return `SELECT f.id AS fid, ${a}l.id AS lid, ${a}l.link_type, ${a}l.from_page_id, ${a}l.to_page_id, ${a}l.origin_page_id,
+ ${a}l.link_source, ${a}f.type AS from_type, ${a}t.type AS to_type, ${a}f.source_id
+ FROM f CROSS JOIN LATERAL (
+ SELECT x.* FROM links x WHERE x.${frontierCol} = f.id AND x.link_type = ANY($1::text[])
+ AND x.from_page_id <> x.to_page_id AND x.link_source IS DISTINCT FROM 'mentions'
+ OFFSET 0
+ ) ${a}l
+ CROSS JOIN LATERAL ${byId(`${a}l.from_page_id`)} ${a}f
+ CROSS JOIN LATERAL ${byId(`${a}l.to_page_id`)} ${a}t
+ WHERE ${a}f.source_id = ${a}t.source_id AND ${pf} AND ${pt} AND ${origin}`;
+ };
+ // The LATERAL link scan is fenced the same way, so the walk always starts
+ // from the frontier's links.
+ const outBranch = branch('from_page_id', 'o');
+ const inBranch = branch('to_page_id', 'i');
+ const nb = pageReadFilter('nb', policy, params, true);
+ const dg = pageReadFilter('dg', policy, params, true);
+ const ev = pageReadFilter('ev', policy, params, true);
+ const textGate = requiresSafeChunks(policy) ? `AND ${safeChunksFilter('ev')} AND NOT ${protectedBodyFilter('ev')}` : '';
+ params.push(opts.toward);
+ const toward = `$${params.length}`;
+ const rows = await query<Record<string, unknown>>(`
+ WITH f AS (SELECT DISTINCT unnest(${ids}) AS id),
+ cand AS (${outBranch} UNION ${inBranch}),
+ classified AS (
+ SELECT c.*, CASE
+ WHEN c.link_source IN ('frontmatter', 'manual') OR (c.link_type = 'attended' AND c.origin_page_id IS NOT NULL)
+ THEN CASE WHEN c.from_type = ANY($2::text[]) AND c.to_type = ANY($3::text[]) THEN 'canonical' END
+ WHEN c.from_type = ANY($2::text[]) AND c.to_type = ANY($3::text[])
+ AND c.to_type = ANY($2::text[]) AND c.from_type = ANY($3::text[]) THEN 'uncertain'
+ WHEN c.from_type = ANY($2::text[]) AND c.to_type = ANY($3::text[]) THEN 'stored'
+ WHEN c.to_type = ANY($2::text[]) AND c.from_type = ANY($3::text[]) THEN 'flipped'
+ END AS orientation
+ FROM cand c
+ ),
+ semantic AS (
+ SELECT k.*,
+ CASE WHEN k.orientation = 'flipped' THEN k.to_page_id ELSE k.from_page_id END AS subject_id,
+ CASE WHEN k.orientation = 'flipped' THEN k.from_page_id ELSE k.to_page_id END AS object_id
+ FROM classified k WHERE k.orientation IS NOT NULL
+ ),
+ stepped AS (
+ SELECT s.*, CASE WHEN ${toward} = 'object' THEN s.object_id ELSE s.subject_id END AS next_id,
+ CASE s.orientation WHEN 'canonical' THEN 0 WHEN 'stored' THEN 1 WHEN 'flipped' THEN 2 ELSE 3 END AS orient_rank
+ FROM semantic s
+ WHERE (CASE WHEN ${toward} = 'object' THEN s.subject_id ELSE s.object_id END) = s.fid
+ ),
+ logical AS (
+ SELECT fid, next_id, MIN(source_id) AS source_id, MIN(lid) AS min_lid,
+ array_agg(lid ORDER BY lid) AS link_ids,
+ (array_agg(lid ORDER BY orient_rank, lid))[1] AS evidence_lid,
+ (array_agg(orientation ORDER BY orient_rank, lid))[1] AS orientation
+ FROM stepped GROUP BY fid, next_id
+ ),
+ ranked AS (
+ SELECT g.*, ROW_NUMBER() OVER (PARTITION BY g.fid ORDER BY g.min_lid) AS rn,
+ COUNT(*) OVER (PARTITION BY g.fid) AS per_frontier
+ FROM logical g
+ ),
+ deg_rows AS (
+ SELECT f.id AS fid, d.nb_id FROM f CROSS JOIN LATERAL (
+ SELECT dn.nb_id FROM (
+ SELECT CASE WHEN dl.from_page_id = f.id THEN dl.to_page_id ELSE dl.from_page_id END AS nb_id, dl.id AS lid, dl.origin_page_id
+ FROM links dl
+ WHERE (dl.from_page_id = f.id OR dl.to_page_id = f.id) AND dl.from_page_id <> dl.to_page_id
+ AND dl.link_type = ANY($4::text[]) AND dl.link_source IS DISTINCT FROM 'mentions'
+ OFFSET 0
+ ) dn
+ CROSS JOIN LATERAL ${byId('dn.nb_id')} nb
+ WHERE ${nb} AND (dn.origin_page_id IS NULL OR EXISTS (SELECT 1 FROM ${byId('dn.origin_page_id')} dg WHERE ${dg}))
+ ORDER BY dn.lid LIMIT ${CHAIN_DEGREE_SATURATION}
+ ) d
+ ),
+ deg AS (
+ SELECT f.id AS fid, CASE
+ WHEN (SELECT COUNT(*) FROM deg_rows r WHERE r.fid = f.id) >= ${CHAIN_DEGREE_SATURATION} THEN ${CHAIN_DEGREE_SATURATION}
+ ELSE (SELECT COUNT(DISTINCT r.nb_id) FROM deg_rows r WHERE r.fid = f.id)
+ END AS degree FROM f
+ )
+ SELECT r.fid, r.next_id, np.slug AS next_slug, np.type AS next_type, r.source_id, el.link_type, r.orientation,
+ r.link_ids, sf.slug AS stored_from_slug, st.slug AS stored_to_slug,
+ CASE WHEN ev.id IS NOT NULL ${textGate} THEN el.context END AS context,
+ el.origin_page_id, op.slug AS origin_slug, deg.degree AS from_degree, (r.per_frontier > $5) AS cap_hit,
+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = r.next_id
+ ${requiresSafeChunks(policy) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = r.next_id AND ${safeChunksFilter('cp')})` : ''}
+ ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id
+ FROM ranked r
+ JOIN pages np ON np.id = r.next_id
+ JOIN links el ON el.id = r.evidence_lid
+ JOIN pages sf ON sf.id = el.from_page_id
+ JOIN pages st ON st.id = el.to_page_id
+ LEFT JOIN pages op ON op.id = el.origin_page_id
+ LEFT JOIN LATERAL (SELECT ev0.* FROM ${byId('COALESCE(el.origin_page_id, el.from_page_id)')} ev0) ev ON ${ev}
+ JOIN deg ON deg.fid = r.fid
+ WHERE r.rn <= $5
+ ORDER BY r.fid ASC, r.min_lid ASC`, params);
+ return rows.map(row => ({
+ from_page_id: Number(row.fid), to_page_id: Number(row.next_id), to_slug: row.next_slug as string,
+ to_type: row.next_type as string, source_id: row.source_id as string, link_type: row.link_type as string,
+ orientation: row.orientation as ChainHopEdge['orientation'],
+ link_ids: (Array.isArray(row.link_ids) ? row.link_ids : []).map(Number),
+ stored_from_slug: row.stored_from_slug as string, stored_to_slug: row.stored_to_slug as string,
+ context: row.context == null ? null : String(row.context),
+ origin_page_id: row.origin_page_id == null ? null : Number(row.origin_page_id),
+ origin_slug: row.origin_slug == null ? null : String(row.origin_slug),
+ canonical_chunk_id: row.canonical_chunk_id == null ? null : Number(row.canonical_chunk_id),
+ from_degree: Number(row.from_degree ?? 0), neighbor_cap_hit: row.cap_hit === true,
+ }));
+}
+
export async function readBacklinkCounts(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, number>> {
const result = new Map(ids.map(id => [id, 0]));
if (!ids.length) return result;
diff --git a/src/core/search/relational-chain.ts b/src/core/search/relational-chain.ts
new file mode 100644
index 0000000000..bbb815faf4
--- /dev/null
+++ b/src/core/search/relational-chain.ts
@@ -0,0 +1,353 @@
+/**
+ * Multi-hop relational chains: walk 1-3 typed hops ("Alice → companies she
+ * invested in → their founders") over `links`, one bounded engine query per
+ * hop, with path state, scoring and tie breaking in TypeScript.
+ *
+ * Determinism: frontier selection, path retention and answer order use
+ * `(score DESC, source_id ASC, slug ASC)` with byte-wise string comparison;
+ * scores are summed in a pinned path order, so both engines produce identical
+ * output for identical rows.
+ *
+ * Path state: each retained path keeps its own node list; cycle prevention is
+ * path-local, and a path may end on its own anchor ("who invested in the
+ * companies Alice founded?" can answer Alice). A node reached as another
+ * path's intermediate can still be an answer. The anchor is dropped from answers only when the plan says so
+ * (`excludeAnchor`: "other/else/also" questions and the co-relation shape).
+ *
+ * Bounds: at most `frontierCap` nodes expand per hop, each with at most
+ * `neighborCap` logical edges, and at most `pathsPerNode` paths are retained
+ * per node, so the work per hop is bounded regardless of hub size.
+ *
+ * Tested in test/relational-chain.test.ts.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { ChainHopEdge, PageReadPolicy } from '../types.ts';
+import { hubWeight } from './hub-dampening.ts';
+import { pageReadFilter } from './read-policy-sql.ts';
+import { sanitizeRemoteBody } from '../remote-body.ts';
+
+/** Page-type signature of each chain relation: subject types → object types. */
+export const LINK_SIGNATURES: Readonly<Record<string, { subject: readonly string[]; object: readonly string[] }>> = {
+ founded: { subject: ['person'], object: ['company'] },
+ invested_in: { subject: ['person', 'company'], object: ['company', 'deal'] },
+ led_round: { subject: ['person', 'company'], object: ['company', 'deal'] },
+ advises: { subject: ['person'], object: ['company'] },
+ works_at: { subject: ['person'], object: ['company'] },
+ attended: { subject: ['person'], object: ['meeting'] },
+ yc_partner: { subject: ['person'], object: ['company'] },
+};
+
+/** Link types a chain hop may walk (the ones with a signature). */
+export const CHAIN_LINK_TYPES: readonly string[] = Object.keys(LINK_SIGNATURES);
+
+/** Relations that share one meaning for chain purposes. */
+const LINK_FAMILIES: Readonly<Record<string, readonly string[]>> = {
+ invested_in: ['invested_in', 'led_round'],
+ led_round: ['invested_in', 'led_round'],
+};
+
+export function linkFamily(linkType: string): string[] {
+ return [...(LINK_FAMILIES[linkType] ?? [linkType])];
+}
+
+export interface ChainHop {
+ /** One relation family; every member must be in CHAIN_LINK_TYPES. */
+ linkTypes: string[];
+ /** Walk from the current node to the relation's object or subject. */
+ toward: 'object' | 'subject';
+ /** Page type the landing node must have, when the question names one. */
+ nodeType?: string | null;
+}
+
+export interface ChainPlan {
+ hops: ChainHop[];
+ excludeAnchor: boolean;
+}
+
+export interface ChainAnchor {
+ page_id: number;
+ slug: string;
+ source_id: string;
+}
+
+export interface ChainEvidenceEdge {
+ link_type: string;
+ stored_from: string;
+ stored_to: string;
+ orientation: ChainHopEdge['orientation'];
+ context: string | null;
+ origin: string | null;
+}
+
+export interface RelationalChainRow {
+ source_id: string;
+ slug: string;
+ page_id: number;
+ role: 'answer' | 'support' | 'origin';
+ /** Hop at which the node is reached on its best path (origin rows: the edge's hop). */
+ hop: number;
+ path_count: number;
+ score: number;
+ best_path: { nodes: string[]; edges: ChainEvidenceEdge[] };
+ canonical_chunk_id: number | null;
+}
+
+export type ChainStatus = 'fired' | 'anchor_not_found' | 'no_edges' | 'empty_hop' | 'truncated';
+
+export interface ChainDiagnostics {
+ status: ChainStatus;
+ per_hop: Array<{ link_types: string[]; toward: 'object' | 'subject'; frontier: number; edges: number }>;
+ cap_hit: null | { cap: 'neighbor' | 'frontier' | 'paths'; hop: number };
+ /** 1-based hop that came back empty, for `empty_hop`. */
+ empty_hop?: number;
+}
+
+export interface ChainLimits {
+ frontierCap: number;
+ neighborCap: number;
+ pathsPerNode: number;
+ /** Multiply path weight by hubWeight(degree) of each intermediate node. */
+ hubWeighting: boolean;
+}
+
+export const DEFAULT_CHAIN_LIMITS: Readonly<ChainLimits> = {
+ frontierCap: 50, neighborCap: 100, pathsPerNode: 10, hubWeighting: true,
+};
+
+/**
+ * Degree at which a chain path's weight through an intermediate node halves
+ * (hub dampening; ~1/(1+0.001·(n−1)²)). Chain ranking uses it when
+ * `hubWeighting` is on, independent of the search-wide hub setting.
+ */
+export const CHAIN_HUB_HALF_DEGREE = 32;
+
+/** Weight applied to an edge whose direction could not be established from types. */
+export const UNCERTAIN_EDGE_WEIGHT = 0.5;
+
+interface PathRec {
+ source_id: string;
+ ids: number[];
+ slugs: string[];
+ edges: ChainHopEdge[];
+ weight: number;
+ key: string;
+}
+
+const byteCmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
+
+function nodeKey(source: string, id: number): string {
+ return `${source}\u0000${id}`;
+}
+
+/** Order paths: weight DESC, then the path key (byte-wise). */
+function comparePaths(a: PathRec, b: PathRec): number {
+ return b.weight - a.weight || byteCmp(a.key, b.key);
+}
+
+interface NodeAgg {
+ source_id: string;
+ id: number;
+ slug: string;
+ score: number;
+ paths: PathRec[];
+}
+
+function aggregate(paths: PathRec[]): NodeAgg[] {
+ const byNode = new Map<string, NodeAgg>();
+ for (const p of [...paths].sort((a, b) => byteCmp(a.key, b.key))) {
+ const id = p.ids[p.ids.length - 1];
+ const key = nodeKey(p.source_id, id);
+ let agg = byNode.get(key);
+ if (!agg) {
+ agg = { source_id: p.source_id, id, slug: p.slugs[p.slugs.length - 1], score: 0, paths: [] };
+ byNode.set(key, agg);
+ }
+ agg.score += p.weight;
+ agg.paths.push(p);
+ }
+ for (const agg of byNode.values()) agg.paths.sort(comparePaths);
+ return [...byNode.values()].sort((a, b) =>
+ b.score - a.score || byteCmp(a.source_id, b.source_id) || byteCmp(a.slug, b.slug));
+}
+
+function evidence(e: ChainHopEdge): ChainEvidenceEdge {
+ return {
+ link_type: e.link_type, stored_from: e.stored_from_slug, stored_to: e.stored_to_slug,
+ orientation: e.orientation, context: e.context, origin: e.origin_slug,
+ };
+}
+
+/**
+ * Run a chain plan from resolved anchors. Never throws for an empty graph:
+ * an empty first hop is `no_edges`, a later one `empty_hop`.
+ */
+export async function runRelationalChain(
+ engine: Pick<BrainEngine, 'relationalChainHop'>,
+ anchors: ChainAnchor[],
+ plan: ChainPlan,
+ policy: PageReadPolicy,
+ limits: ChainLimits = DEFAULT_CHAIN_LIMITS,
+): Promise<{ rows: RelationalChainRow[]; diagnostics: ChainDiagnostics }> {
+ const diagnostics: ChainDiagnostics = { status: 'fired', per_hop: [], cap_hit: null };
+ if (anchors.length === 0) return { rows: [], diagnostics: { ...diagnostics, status: 'anchor_not_found' } };
+ const degreeLinkTypes = [...CHAIN_LINK_TYPES];
+ let paths: PathRec[] = anchors.map(a => ({
+ source_id: a.source_id, ids: [a.page_id], slugs: [a.slug], edges: [], weight: 1, key: a.slug,
+ }));
+ const chunkIds = new Map<string, number | null>();
+
+ for (let i = 0; i < plan.hops.length; i++) {
+ const hop = plan.hops[i];
+ let nodes = aggregate(paths);
+ if (nodes.length > limits.frontierCap) {
+ diagnostics.cap_hit ??= { cap: 'frontier', hop: i + 1 };
+ nodes = nodes.slice(0, limits.frontierCap);
+ }
+ paths = [];
+ for (const n of nodes) {
+ if (n.paths.length > limits.pathsPerNode) diagnostics.cap_hit ??= { cap: 'paths', hop: i + 1 };
+ paths.push(...n.paths.slice(0, limits.pathsPerNode));
+ }
+ const sig = signatureFor(hop.linkTypes);
+ const edges = await engine.relationalChainHop(nodes.map(n => n.id), {
+ ...policy,
+ linkTypes: hop.linkTypes, toward: hop.toward,
+ subjectTypes: [...sig.subject], objectTypes: [...sig.object],
+ degreeLinkTypes, neighborCap: limits.neighborCap,
+ });
+ const byFrom = new Map<number, ChainHopEdge[]>();
+ const degree = new Map<number, number>();
+ for (const e of edges) {
+ if (hop.nodeType && e.to_type !== hop.nodeType) continue;
+ if (e.neighbor_cap_hit) diagnostics.cap_hit ??= { cap: 'neighbor', hop: i + 1 };
+ degree.set(e.from_page_id, e.from_degree);
+ const list = byFrom.get(e.from_page_id) ?? [];
+ list.push(e);
+ byFrom.set(e.from_page_id, list);
+ chunkIds.set(nodeKey(e.source_id, e.to_page_id), e.canonical_chunk_id);
+ }
+ const next: PathRec[] = [];
+ for (const p of paths) {
+ const last = p.ids[p.ids.length - 1];
+ const hubFactor = i > 0 && limits.hubWeighting ? hubWeight(degree.get(last) ?? 1, CHAIN_HUB_HALF_DEGREE) : 1;
+ for (const e of byFrom.get(last) ?? []) {
+ if (e.source_id !== p.source_id) continue;
+ const returnsToAnchor = e.to_page_id === p.ids[0] && i === plan.hops.length - 1;
+ if (p.ids.includes(e.to_page_id) && !returnsToAnchor) continue;
+ const w = p.weight * hubFactor * (e.orientation === 'uncertain' ? UNCERTAIN_EDGE_WEIGHT : 1);
+ next.push({
+ source_id: p.source_id, ids: [...p.ids, e.to_page_id], slugs: [...p.slugs, e.to_slug],
+ edges: [...p.edges, e], weight: w, key: `${p.key}\u0001${e.to_slug}`,
+ });
+ }
+ }
+ diagnostics.per_hop.push({ link_types: [...hop.linkTypes], toward: hop.toward, frontier: nodes.length, edges: next.length });
+ if (next.length === 0) {
+ return {
+ rows: [],
+ diagnostics: { ...diagnostics, status: i === 0 ? 'no_edges' : 'empty_hop', empty_hop: i + 1 },
+ };
+ }
+ paths = next;
+ }
+
+ const anchorKeys = new Set(anchors.map(a => nodeKey(a.source_id, a.page_id)));
+ const answers = aggregate(paths).filter(n => !(plan.excludeAnchor && anchorKeys.has(nodeKey(n.source_id, n.id))));
+ if (answers.length === 0) return { rows: [], diagnostics: { ...diagnostics, status: 'empty_hop', empty_hop: plan.hops.length } };
+
+ const rows: RelationalChainRow[] = [];
+ const emitted = new Set<string>();
+ const push = (row: RelationalChainRow) => {
+ const k = nodeKey(row.source_id, row.page_id);
+ if (emitted.has(k)) return;
+ emitted.add(k);
+ rows.push(row);
+ };
+ for (const a of answers) {
+ const best = a.paths[0];
+ push({
+ source_id: a.source_id, slug: a.slug, page_id: a.id, role: 'answer', hop: best.edges.length,
+ path_count: a.paths.length, score: a.score,
+ best_path: { nodes: best.slugs, edges: best.edges.map(evidence) },
+ 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,
+ });
+ });
+ }
+ if (diagnostics.cap_hit) diagnostics.status = 'truncated';
+ return { rows, diagnostics };
+}
+
+function signatureFor(linkTypes: string[]): { subject: string[]; object: string[] } {
+ const subject = new Set<string>();
+ const object = new Set<string>();
+ for (const lt of linkTypes) {
+ const sig = LINK_SIGNATURES[lt];
+ if (!sig) throw new Error(`relational chain: link type "${lt}" has no signature; chain link types are ${CHAIN_LINK_TYPES.join(', ')}`);
+ sig.subject.forEach(t => subject.add(t));
+ sig.object.forEach(t => object.add(t));
+ }
+ return { subject: [...subject].sort(), object: [...object].sort() };
+}
+
+/** Resolve an exact slug to chain anchors in every source the policy admits (live pages only). */
+export async function resolveChainAnchors(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ slug: string,
+ policy: PageReadPolicy,
+): Promise<ChainAnchor[]> {
+ const params: unknown[] = [slug];
+ const filter = pageReadFilter('p', policy, params, true);
+ const rows = await engine.executeRaw<{ id: number; source_id: string }>(
+ `SELECT p.id, p.source_id FROM pages p WHERE p.slug = $1 AND ${filter} ORDER BY p.source_id`, params);
+ return rows.map(r => ({ page_id: Number(r.id), slug, source_id: r.source_id }));
+}
+
+/** Longest edge context shown to an untrusted caller. */
+export const REMOTE_EDGE_CONTEXT_CHARS = 160;
+
+/** Edge context as a caller may see it: remote callers get a sanitized, bounded excerpt. */
+export function presentEdgeContext(context: string | null, remote: boolean): string | null {
+ if (context == null) return null;
+ if (!remote) return context;
+ const clean = sanitizeRemoteBody(context).replace(/\s+/g, ' ').trim();
+ return clean.length > REMOTE_EDGE_CONTEXT_CHARS ? `${clean.slice(0, REMOTE_EDGE_CONTEXT_CHARS - 1)}…` : clean;
+}
+
+/** Validate an agent-supplied chain: 1-3 hops over chain link types. Returns the problem or the plan. */
+export function validateChainHops(raw: unknown): { ok: true; hops: ChainHop[] } | { ok: false; path: string; problem: string } {
+ if (!Array.isArray(raw) || raw.length === 0) return { ok: false, path: 'hops', problem: 'hops must be a non-empty array of {link_type, toward}' };
+ if (raw.length > MAX_CHAIN_HOPS) return { ok: false, path: 'hops', problem: `at most ${MAX_CHAIN_HOPS} hops are supported (got ${raw.length})` };
+ const hops: ChainHop[] = [];
+ for (let i = 0; i < raw.length; i++) {
+ const h = raw[i] as Record<string, unknown> | null;
+ const lt = h && typeof h === 'object' ? h.link_type : undefined;
+ const toward = h && typeof h === 'object' ? h.toward : undefined;
+ if (typeof lt !== 'string' || !LINK_SIGNATURES[lt]) {
+ return { ok: false, path: `hops[${i}].link_type`, problem: `${JSON.stringify(lt ?? null)} is not a chain link type; use one of ${CHAIN_LINK_TYPES.join(', ')}` };
+ }
+ if (toward !== 'object' && toward !== 'subject') {
+ return { ok: false, path: `hops[${i}].toward`, problem: `${JSON.stringify(toward ?? null)} must be "object" (subject → object, e.g. investor → company) or "subject" (object → subject, e.g. company → founder)` };
+ }
+ hops.push({ linkTypes: linkFamily(lt), toward });
+ }
+ return { ok: true, hops };
+}
+
+export const MAX_CHAIN_HOPS = 3;
diff --git a/src/core/types.ts b/src/core/types.ts
index a944875090..dafb5f8e78 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1537,6 +1537,50 @@ export interface RelationalFanoutOpts extends PageReadPolicy {
limit?: number;
}
+/**
+ * Options for BrainEngine.relationalChainHop: one bounded, oriented expansion
+ * step of a multi-hop relational chain. `subjectTypes`/`objectTypes` are the
+ * hop relation's page-type signature; `degreeLinkTypes` names the typed edges
+ * counted for a frontier node's degree (hub weighting).
+ */
+export interface ChainHopOpts extends PageReadPolicy {
+ linkTypes: string[];
+ toward: 'object' | 'subject';
+ subjectTypes: string[];
+ objectTypes: string[];
+ degreeLinkTypes: string[];
+ /** Max logical edges returned per frontier node (deterministic: lowest link id first). */
+ neighborCap: number;
+}
+
+/**
+ * One LOGICAL edge from a frontier node, oriented by the relation's type
+ * signature and already authorized (both endpoints and any origin page pass
+ * the read policy). Stored rows between the same pair that resolve to the same
+ * subject/object collapse into one edge (`link_ids`).
+ */
+export interface ChainHopEdge {
+ from_page_id: number;
+ to_page_id: number;
+ to_slug: string;
+ to_type: string;
+ source_id: string;
+ link_type: string;
+ orientation: 'canonical' | 'stored' | 'flipped' | 'uncertain';
+ link_ids: number[];
+ stored_from_slug: string;
+ stored_to_slug: string;
+ /** Edge context from the evidence row; null when the caller may not read the evidence page's text. */
+ context: string | null;
+ origin_page_id: number | null;
+ origin_slug: string | null;
+ canonical_chunk_id: number | null;
+ /** Distinct typed neighbors of the frontier node the caller may read; saturates at 300 readable link rows. */
+ from_degree: number;
+ /** True when the frontier node had more logical edges than `neighborCap`. */
+ neighbor_cap_hit: boolean;
+}
+
// Timeline
export interface TimelineEntry {
id: number;
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index b207c5baa6..72d4d5b3f2 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -18,6 +18,7 @@ import { createHash } from 'node:crypto';
import { installFixtureChunks } from '../helpers/page-projection.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { linkFamily, resolveChainAnchors, runRelationalChain } from '../../src/core/search/relational-chain.ts';
import type { ChunkInput, SearchResult } from '../../src/core/types.ts';
import type { BrainEngine } from '../../src/core/engine.ts';
import { getSessionContextState, upsertSessionContextState } from '../../src/core/context/session-state.ts';
@@ -1404,6 +1405,21 @@ describeBoth('Engine parity — relationalFanout', () => {
const pglite = await pgliteEngine.relationalFanout(seeds, { direction: 'both' });
expect(shape(pg)).toEqual(shape(pglite));
});
+
+ test('multi-hop chain (relationalChainHop + runRelationalChain) identical across engines', async () => {
+ await pgEngine.addLink('companies/ep-widget', 'people/ep-emp-c', 'founded by c', 'founded', 'markdown');
+ await pgliteEngine.addLink('companies/ep-widget', 'people/ep-emp-c', 'founded by c', 'founded', 'markdown');
+ const plan = { hops: [{ linkTypes: linkFamily('invested_in'), toward: 'object' as const }, { linkTypes: ['founded'], toward: 'subject' as const }], excludeAnchor: false };
+ const run = async (eng: BrainEngine) => {
+ const anchors = await resolveChainAnchors(eng, 'people/ep-inv-a', {});
+ const { rows, diagnostics } = await runRelationalChain(eng, anchors, plan, {});
+ return { rows: rows.map(r => ({ ...r, page_id: 0, canonical_chunk_id: r.canonical_chunk_id != null })), diagnostics };
+ };
+ const pg = await run(pgEngine);
+ const pglite = await run(pgliteEngine);
+ expect(pg).toEqual(pglite);
+ expect(pg.rows.filter(r => r.role === 'answer').map(r => r.slug)).toEqual(['people/ep-emp-c']);
+ });
});
// #2200 — federated sourceIds[] on the secondary-fetch reads must behave
diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.ts
index ec53c793d5..ac6776aaa1 100644
--- a/test/engine-surface-coverage.test.ts
+++ b/test/engine-surface-coverage.test.ts
@@ -63,7 +63,7 @@ const INTERFACE_METHODS: readonly string[] = [
'countStalePagesForExtraction', 'listStalePagesForExtraction', 'markPagesExtractedBatch', 'markPagesAttendanceBlocked',
// Links + graph
'addLink', 'addLinksBatch', 'replaceDerivedLinks', 'removeLink', 'getLinks', 'getBacklinks', 'listLinkSources',
- 'findByTitleFuzzy', 'traverseGraph', 'traversePaths', 'traversePathsDetailed', 'relationalFanout', 'getBacklinkCounts',
+ 'findByTitleFuzzy', 'traverseGraph', 'traversePaths', 'traversePathsDetailed', 'relationalFanout', 'relationalChainHop', 'getBacklinkCounts',
'getAdjacencyBoosts', 'getContentFlagsByPageIds', 'getUnverifiedExtractionPageIds',
'getPageTimestamps', 'getEffectiveDates', 'getSalienceScores', 'findOrphanPages',
// Tags
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index 6f052f595c..44c025d732 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -3432,6 +3432,7 @@
"reconnect": "none",
"refreshPageBody": "none",
"registerBeforeDisconnect": "none",
+ "relationalChainHop": "none",
"relationalFanout": "none",
"removeLink": "none",
"removeLinksByPagesAndSource": "none",
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index bab25105b6..9e9f019349 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -16,7 +16,7 @@
"out-of-scope:no-sql-stub": 1,
"out-of-scope:raw-data": 2,
"out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 3,
- "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 8,
+ "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 9,
"out-of-scope:stats-health (brain-wide aggregates)": 2,
"pages": 33,
"salience": 5,
@@ -159,6 +159,7 @@
"reconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
"refreshPageBody": "pages",
"registerBeforeDisconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
+ "relationalChainHop": "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)",
"relationalFanout": "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)",
"removeLink": "links",
"removeLinksByPagesAndSource": "links",
diff --git a/test/graph-query-thin-client-source-flag.serial.test.ts b/test/graph-query-thin-client-source-flag.serial.test.ts
index bc9b304348..765ff6be91 100644
--- a/test/graph-query-thin-client-source-flag.serial.test.ts
+++ b/test/graph-query-thin-client-source-flag.serial.test.ts
@@ -18,6 +18,7 @@ import { withEnv } from './helpers/with-env.ts';
type Call = { name: string; params: Record<string, unknown> };
const calls: Call[] = [];
+let reply: unknown = [];
const realConfig = await import('../src/core/config.ts');
mock.module('../src/core/config.ts', () => ({
@@ -31,7 +32,7 @@ mock.module('../src/core/mcp-client.ts', () => ({
...realMcpClient,
callRemoteTool: async (_cfg: unknown, name: string, params: Record<string, unknown>) => {
calls.push({ name, params });
- return { content: [{ type: 'text', text: JSON.stringify([]) }] };
+ return { content: [{ type: 'text', text: JSON.stringify(reply) }] };
},
}));
@@ -68,7 +69,7 @@ async function run(args: string[]): Promise<{ code: number; out: string[]; err:
}
}
-beforeEach(() => { calls.length = 0; });
+beforeEach(() => { calls.length = 0; reply = []; });
describe('graph-query --source on a thin-client install', () => {
test('--source is rejected with exit 1 and never reaches the wire', async () => {
@@ -125,3 +126,22 @@ describe('graph-query --source on a thin-client install', () => {
expect(Object.keys(calls[0].params).sort()).toEqual(['depth', 'direction', 'link_type', 'slug']);
});
});
+
+describe('graph-query --hop on a thin-client install', () => {
+ test('sends only slug + hops, and refuses a host that ignored hops (older gbrain)', async () => {
+ const r = await run(['people/alice-example', '--hop', 'invested_in:object', '--hop', 'founded:subject']);
+ expect(calls[0]).toEqual({ name: 'traverse_graph', params: { slug: 'people/alice-example', hops: [
+ { link_type: 'invested_in', toward: 'object' }, { link_type: 'founded', toward: 'subject' }] } });
+ expect(r.code).toBe(1);
+ expect(r.err.join('\n')).toContain('older gbrain without typed chains');
+ });
+
+ test('renders a chain response from a current host', async () => {
+ reply = { anchor: 'people/alice-example', answers: [{ slug: 'people/bob-example', source_id: 'default', path_count: 1, score: 1 }],
+ paths: [{ nodes: ['people/alice-example', 'companies/acme-example', 'people/bob-example'], edges: [] }],
+ diagnostics: { status: 'fired', per_hop: [], cap_hit: null } };
+ const r = await run(['people/alice-example', '--hop', 'invested_in:object', '--hop', 'founded:subject']);
+ expect(r.code).toBe(0);
+ expect(r.out.join('\n')).toContain('people/bob-example');
+ });
+});
diff --git a/test/graph-query.test.ts b/test/graph-query.test.ts
index d740eee645..6906d3a730 100644
--- a/test/graph-query.test.ts
+++ b/test/graph-query.test.ts
@@ -296,3 +296,37 @@ describe('graph-query foreign-edge footer (#1153)', () => {
expect(joined).toMatch(/2 edges to foreign-source pages hidden/);
});
});
+
+describe('graph-query --hop (typed chains)', () => {
+ beforeEach(async () => {
+ await truncateAll();
+ for (const [slug, type] of [['people/alice', 'person'], ['people/bob', 'person'], ['companies/acme', 'company']] as const) {
+ await engine.putPage(slug, { type, title: slug, compiled_truth: '', timeline: '' });
+ }
+ await engine.addLink('people/alice', 'companies/acme', 'alice backed acme', 'invested_in', 'markdown');
+ await engine.addLink('companies/acme', 'people/bob', 'founded by bob', 'founded', 'markdown');
+ });
+
+ test('prints each answer with the edges that prove it', async () => {
+ const r = await runWithExit(['people/alice', '--hop', 'invested_in:object', '--hop', 'founded:subject']);
+ expect(r.code).toBe(0);
+ const out = r.out.join('\n');
+ expect(out).toContain('1 answer for people/alice');
+ expect(out).toContain('people/bob');
+ expect(out).toContain('companies/acme -founded-> people/bob (written on the other page): "founded by bob"');
+ });
+
+ test('--hop with --type/--depth is refused; a malformed hop names the fix', async () => {
+ const conflict = await runWithExit(['people/alice', '--hop', 'invested_in:object', '--depth', '2']);
+ expect(conflict.code).toBe(1);
+ expect(conflict.err.join('\n')).toContain('--hop cannot be combined with --depth');
+ const bad = await runWithExit(['people/alice', '--hop', 'invested_in']);
+ expect(bad.code).toBe(1);
+ expect(bad.err.join('\n')).toContain('toward');
+ });
+
+ test('no answers names the empty hop and the inspection command', async () => {
+ const r = await runWithExit(['people/alice', '--hop', 'invested_in:object', '--hop', 'advises:subject']);
+ expect(r.out.join('\n')).toContain('hop 2 (advises:subject) found no typed edges');
+ });
+});
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index 87d253628a..119aa6a6e4 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -134,7 +134,7 @@ export const DOMAIN_OF: Record<string, string> = {
// out of scope
'searchTitles': OOS.search, 'searchVector': OOS.search, 'explainVectorSearch': OOS.search,
- 'relationalFanout': OOS.enrichment, 'getBacklinkCounts': OOS.enrichment, 'getAdjacencyBoosts': OOS.enrichment,
+ 'relationalFanout': OOS.enrichment, 'relationalChainHop': OOS.enrichment, 'getBacklinkCounts': OOS.enrichment, 'getAdjacencyBoosts': OOS.enrichment,
'getContentFlagsByPageIds': OOS.enrichment, 'getUnverifiedExtractionPageIds': OOS.enrichment,
'getEffectiveDates': OOS.enrichment, 'getSalienceScores': OOS.enrichment, 'resolveAliases': OOS.enrichment,
'getStats': OOS.stats, 'getHealth': OOS.stats,
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 42052648b0..e43999f2ae 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -40,8 +40,8 @@ import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-esti
const SERVED_STARTER_MAX_CHARS = 25_000;
const SERVED_STARTER_MAX_TOKENS = 5_700;
-/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0). */
-const SERVED_STARTER_MAX_JSON_CHARS = 26_000;
+/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; +279 for traverse_graph's optional `hops` typed-chain parameter). */
+const SERVED_STARTER_MAX_JSON_CHARS = 26_050;
/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
const INSTRUCTIONS_MAX_CHARS = 4_628;
const DESCRIPTION_HARD_CAP = 1_200;
@@ -55,7 +55,7 @@ const TOOL_BUDGETS: Record<string, number> = {
get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,
put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,
- submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 810, whoami: 230,
+ submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 1090, whoami: 230,
};
/** DX-14: phrases each tool's description must keep. */
diff --git a/test/relational-chain-hub.slow.test.ts b/test/relational-chain-hub.slow.test.ts
new file mode 100644
index 0000000000..bdc46b82ab
--- /dev/null
+++ b/test/relational-chain-hub.slow.test.ts
@@ -0,0 +1,43 @@
+/**
+ * Bounded work on a dense hub (PGLite): a chain hop from a company with 10,000
+ * investors returns at most neighborCap edges and finishes well under the 2 s
+ * budget. Regression it catches: a planner that joins pages on source_id per
+ * link row (quadratic) or a degree count that fetches every neighbor page.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRelationalChain, linkFamily } from '../src/core/search/relational-chain.ts';
+
+let eng: PGLiteEngine;
+
+beforeAll(async () => {
+ eng = new PGLiteEngine();
+ await eng.connect({});
+ await eng.initSchema();
+ await eng.putPage('people/carol-example', { type: 'person', title: 'carol', compiled_truth: '', timeline: '' });
+ await eng.putPage('companies/hub-example', { type: 'company', title: 'hub', compiled_truth: '', timeline: '' });
+ await eng.addLink('people/carol-example', 'companies/hub-example', '', 'founded', 'markdown');
+ await eng.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth, timeline, source_id)
+ SELECT 'people/hub-investor-' || g, 'person', 'hub investor ' || g, '', '', 'default' FROM generate_series(1, 10000) g`);
+ await eng.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT p.id, c.id, 'invested_in', '', 'markdown' FROM pages p, pages c
+ WHERE p.slug LIKE 'people/hub-investor-%' AND c.slug = 'companies/hub-example'`);
+}, 120_000);
+
+afterAll(async () => {
+ await eng.disconnect();
+});
+
+describe('relational chain on a 10,000-neighbor hub', () => {
+ test('capped, reported, under 2 s', async () => {
+ const carol = await eng.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = 'people/carol-example'`);
+ const started = Date.now();
+ const { rows, diagnostics } = await runRelationalChain(eng, [{ page_id: Number(carol[0].id), slug: 'people/carol-example', source_id: 'default' }], {
+ hops: [{ linkTypes: ['founded'], toward: 'object' }, { linkTypes: linkFamily('invested_in'), toward: 'subject' }], excludeAnchor: false,
+ }, {});
+ expect(Date.now() - started).toBeLessThan(2000);
+ expect(rows.filter(r => r.role === 'answer').length).toBe(100);
+ expect(diagnostics.cap_hit).toEqual({ cap: 'neighbor', hop: 2 });
+ }, 30_000);
+});
diff --git a/test/relational-chain.test.ts b/test/relational-chain.test.ts
new file mode 100644
index 0000000000..bf554ef603
--- /dev/null
+++ b/test/relational-chain.test.ts
@@ -0,0 +1,324 @@
+/**
+ * Multi-hop relational chains (PGLite): readChainHop orientation + policy and
+ * runRelationalChain path semantics.
+ *
+ * Protects: a two-relation question ("who founded the companies Alice invested
+ * in?") walks typed edges stored from either page's side; private, deleted and
+ * non-entity pages never become hops or move scores; the anchor is an answer
+ * unless the plan excludes it; caps bound work and are reported.
+ * Regression it catches: walking stored direction only (misses company-page
+ * edges), global earlier-hop exclusion, ranking through hidden nodes,
+ * unbounded hub expansion.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRelationalChain, linkFamily, type ChainAnchor, type ChainPlan } from '../src/core/search/relational-chain.ts';
+import { QUARANTINE_KEY } from '../src/core/quarantine.ts';
+
+let eng: PGLiteEngine;
+
+async function anchor(slug: string): Promise<ChainAnchor> {
+ const rows = await eng.executeRaw<{ id: number; source_id: string }>(`SELECT id, source_id FROM pages WHERE slug = $1`, [slug]);
+ return { page_id: Number(rows[0].id), slug, source_id: rows[0].source_id };
+}
+
+const investedThenFounders: ChainPlan = {
+ hops: [{ linkTypes: linkFamily('invested_in'), toward: 'object' }, { linkTypes: ['founded'], toward: 'subject' }],
+ excludeAnchor: false,
+};
+
+beforeAll(async () => {
+ eng = new PGLiteEngine();
+ await eng.connect({});
+ await eng.initSchema();
+ const pages: Array<[string, string, Record<string, unknown>?]> = [
+ ['people/alice-example', 'person'], ['people/bob-example', 'person'], ['people/carol-example', 'person'],
+ ['people/dave-example', 'person'], ['people/priv-example', 'person', { visibility: 'private' }],
+ ['people/gone-example', 'person'], ['companies/acme-example', 'company'], ['companies/beta-example', 'company'],
+ ['companies/gamma-example', 'company'], ['companies/fund-x-example', 'company'], ['notes/memo-example', 'note'],
+ ['companies/empty-example', 'company'],
+ ];
+ for (const [slug, type, frontmatter] of pages) {
+ await eng.putPage(slug, { type: type as 'person', title: slug.split('/')[1], compiled_truth: `${slug} body`, timeline: '', ...(frontmatter ? { frontmatter } : {}) });
+ }
+ const md = async (from: string, to: string, type: string, context = '') => eng.addLink(from, to, context, type, 'markdown');
+ await md('people/alice-example', 'companies/acme-example', 'invested_in', 'alice backed acme');
+ await md('companies/acme-example', 'people/alice-example', 'invested_in', 'investors include alice');
+ await md('companies/beta-example', 'people/alice-example', 'invested_in', 'beta investors: alice');
+ await md('companies/acme-example', 'people/bob-example', 'founded', 'founded by bob');
+ await md('people/carol-example', 'companies/beta-example', 'founded', 'carol founded beta');
+ await md('people/dave-example', 'companies/acme-example', 'invested_in');
+ await md('people/dave-example', 'companies/beta-example', 'led_round');
+ await md('companies/fund-x-example', 'companies/acme-example', 'invested_in', 'fund x backed acme');
+ await md('notes/memo-example', 'people/alice-example', 'invested_in');
+ await md('people/priv-example', 'companies/acme-example', 'founded');
+ await md('people/gone-example', 'companies/acme-example', 'founded');
+ await md('people/alice-example', 'companies/gamma-example', 'founded');
+ await md('people/alice-example', 'companies/gamma-example', 'invested_in');
+ await eng.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'people/gone-example'`);
+}, 60_000);
+
+afterAll(async () => {
+ await eng.disconnect();
+});
+
+describe('readChainHop', () => {
+ test('orients rows stored from either side and collapses duplicates into one logical edge', async () => {
+ const a = await anchor('people/alice-example');
+ const edges = await eng.relationalChainHop([a.page_id], {
+ linkTypes: linkFamily('invested_in'), toward: 'object', subjectTypes: ['company', 'person'],
+ objectTypes: ['company', 'deal'], degreeLinkTypes: ['invested_in', 'founded'], neighborCap: 100,
+ });
+ const bySlug = Object.fromEntries(edges.map(e => [e.to_slug, e]));
+ expect(Object.keys(bySlug).sort()).toEqual(['companies/acme-example', 'companies/beta-example', 'companies/gamma-example']);
+ expect(bySlug['companies/acme-example'].link_ids.length).toBe(2);
+ expect(bySlug['companies/acme-example'].orientation).toBe('stored');
+ expect(bySlug['companies/beta-example'].orientation).toBe('flipped');
+ expect(bySlug['companies/beta-example'].stored_from_slug).toBe('companies/beta-example');
+ });
+
+ test('company↔company edges are uncertain and walk stored direction only; non-entity pages are not hops', async () => {
+ const acme = await anchor('companies/acme-example');
+ const edges = await eng.relationalChainHop([acme.page_id], {
+ linkTypes: linkFamily('invested_in'), toward: 'subject', subjectTypes: ['company', 'person'],
+ objectTypes: ['company', 'deal'], degreeLinkTypes: ['invested_in'], neighborCap: 100,
+ });
+ const fund = edges.find(e => e.to_slug === 'companies/fund-x-example');
+ expect(fund?.orientation).toBe('uncertain');
+ const alice = await anchor('people/alice-example');
+ const fromAlice = await eng.relationalChainHop([alice.page_id], {
+ linkTypes: linkFamily('invested_in'), toward: 'subject', subjectTypes: ['company', 'person'],
+ objectTypes: ['company', 'deal'], degreeLinkTypes: ['invested_in'], neighborCap: 100,
+ });
+ expect(fromAlice.map(e => e.to_slug)).not.toContain('notes/memo-example');
+ });
+});
+
+describe('runRelationalChain', () => {
+ test('who founded the companies alice invested in', async () => {
+ const { rows, diagnostics } = await runRelationalChain(eng, [await anchor('people/alice-example')], investedThenFounders, {});
+ const answers = rows.filter(r => r.role === 'answer').map(r => r.slug);
+ expect(answers.sort()).toEqual(['people/alice-example', 'people/bob-example', 'people/carol-example', 'people/priv-example']);
+ expect(rows.filter(r => r.role === 'support').map(r => r.slug).sort())
+ .toEqual(['companies/acme-example', 'companies/beta-example', 'companies/gamma-example']);
+ expect(diagnostics.status).toBe('fired');
+ const bob = rows.find(r => r.slug === 'people/bob-example')!;
+ expect(bob.best_path.nodes).toEqual(['people/alice-example', 'companies/acme-example', 'people/bob-example']);
+ expect(bob.best_path.edges[1]).toMatchObject({ link_type: 'founded', orientation: 'flipped', context: 'founded by bob' });
+ });
+
+ test('deleted pages never answer; private pages are hidden under excludePrivate without moving scores', async () => {
+ const a = await anchor('people/alice-example');
+ const open = await runRelationalChain(eng, [a], investedThenFounders, {});
+ expect(open.rows.map(r => r.slug)).not.toContain('people/gone-example');
+ expect(open.rows.map(r => r.slug)).toContain('people/priv-example');
+ const scoped = await runRelationalChain(eng, [a], investedThenFounders, { excludePrivate: true });
+ expect(scoped.rows.map(r => r.slug)).not.toContain('people/priv-example');
+ const bob = (rs: typeof open.rows) => rs.find(r => r.slug === 'people/bob-example')!.score;
+ await eng.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'people/priv-example'`);
+ const without = await runRelationalChain(eng, [a], investedThenFounders, { excludePrivate: true });
+ await eng.executeRaw(`UPDATE pages SET deleted_at = NULL WHERE slug = 'people/priv-example'`);
+ expect(bob(scoped.rows)).toBe(bob(without.rows));
+ });
+
+ test('co-investors exclude the anchor; a relation family merges led_round', async () => {
+ const plan: ChainPlan = {
+ hops: [{ linkTypes: linkFamily('invested_in'), toward: 'object' }, { linkTypes: linkFamily('invested_in'), toward: 'subject' }],
+ excludeAnchor: true,
+ };
+ const { rows } = await runRelationalChain(eng, [await anchor('people/alice-example')], plan, {});
+ const answers = rows.filter(r => r.role === 'answer');
+ expect(answers.map(r => r.slug)).not.toContain('people/alice-example');
+ const dave = answers.find(r => r.slug === 'people/dave-example')!;
+ expect(dave.path_count).toBe(2);
+ expect(answers[0].slug).toBe('people/dave-example');
+ const fund = answers.find(r => r.slug === 'companies/fund-x-example')!;
+ expect(fund.score).toBeLessThan(dave.score);
+ });
+
+ test('the anchor can be an answer when the plan does not exclude it', async () => {
+ const plan: ChainPlan = {
+ hops: [{ linkTypes: ['founded'], toward: 'object' }, { linkTypes: linkFamily('invested_in'), toward: 'subject' }],
+ excludeAnchor: false,
+ };
+ const { rows } = await runRelationalChain(eng, [await anchor('people/alice-example')], plan, {});
+ expect(rows.filter(r => r.role === 'answer').map(r => r.slug)).toContain('people/alice-example');
+ });
+
+ test('empty first hop is no_edges; empty later hop is empty_hop with its index', async () => {
+ const empty = await runRelationalChain(eng, [await anchor('companies/empty-example')], {
+ hops: [{ linkTypes: ['founded'], toward: 'subject' }, { linkTypes: linkFamily('invested_in'), toward: 'object' }], excludeAnchor: false,
+ }, {});
+ expect(empty.diagnostics.status).toBe('no_edges');
+ const later = await runRelationalChain(eng, [await anchor('people/bob-example')], {
+ hops: [{ linkTypes: ['founded'], toward: 'object' }, { linkTypes: ['advises'], toward: 'subject' }], excludeAnchor: false,
+ }, {});
+ expect(later.diagnostics).toMatchObject({ status: 'empty_hop', empty_hop: 2 });
+ const none = await runRelationalChain(eng, [], investedThenFounders, {});
+ expect(none.diagnostics.status).toBe('anchor_not_found');
+ });
+
+ test('identical inputs give identical output (order, scores, paths)', async () => {
+ const a = await anchor('people/alice-example');
+ const one = await runRelationalChain(eng, [a], investedThenFounders, {});
+ const two = await runRelationalChain(eng, [a], investedThenFounders, {});
+ expect(JSON.stringify(two)).toBe(JSON.stringify(one));
+ });
+});
+
+describe('path-local cycles and self-links', () => {
+ let c: PGLiteEngine;
+
+ beforeAll(async () => {
+ c = new PGLiteEngine();
+ await c.connect({});
+ await c.initSchema();
+ for (const [slug, type] of [['people/a-example', 'person'], ['companies/b-example', 'company'], ['people/c-example', 'person'],
+ ['companies/d-example', 'company']] as const) {
+ await c.putPage(slug, { type, title: slug, compiled_truth: slug, timeline: '' });
+ }
+ const md = (f: string, t: string, lt: string) => c.addLink(f, t, '', lt, 'markdown');
+ await md('people/a-example', 'companies/b-example', 'invested_in');
+ await md('people/c-example', 'companies/b-example', 'invested_in');
+ await md('people/a-example', 'companies/d-example', 'invested_in');
+ await md('people/c-example', 'companies/d-example', 'invested_in');
+ await md('people/a-example', 'people/a-example', 'invested_in');
+ }, 60_000);
+
+ afterAll(async () => {
+ await c.disconnect();
+ });
+
+ test('a path never revisits its own node; another path may reach it', async () => {
+ const id = Number((await c.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = 'people/a-example'`))[0].id);
+ const plan: ChainPlan = {
+ hops: [{ linkTypes: ['invested_in'], toward: 'object' }, { linkTypes: ['invested_in'], toward: 'subject' }, { linkTypes: ['invested_in'], toward: 'object' }],
+ excludeAnchor: true,
+ };
+ const { rows } = await runRelationalChain(c, [{ page_id: id, slug: 'people/a-example', source_id: 'default' }], plan, {});
+ // A→B→C→B revisits B on its own path and is dropped; A→D→C→B is a fresh path and keeps B.
+ const b = rows.find(r => r.role === 'answer' && r.slug === 'companies/b-example')!;
+ expect(b.best_path.nodes).toEqual(['people/a-example', 'companies/d-example', 'people/c-example', 'companies/b-example']);
+ expect(b.path_count).toBe(1);
+ for (const r of rows) {
+ expect(new Set(r.best_path.nodes).size).toBe(r.best_path.nodes.length);
+ expect(r.best_path.edges.every(e => e.stored_from !== e.stored_to)).toBe(true);
+ }
+ });
+});
+
+describe('bounds', () => {
+ test('a hub with more neighbors than neighborCap is capped and reported', async () => {
+ await eng.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth, timeline, source_id)
+ SELECT 'people/hub-investor-' || g, 'person', 'hub investor ' || g, '', '', 'default' FROM generate_series(1, 400) g`);
+ await eng.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT p.id, c.id, 'invested_in', '', 'markdown' FROM pages p, pages c
+ WHERE p.slug LIKE 'people/hub-investor-%' AND c.slug = 'companies/beta-example'`);
+ const { rows, diagnostics } = await runRelationalChain(eng, [await anchor('people/carol-example')], {
+ hops: [{ linkTypes: ['founded'], toward: 'object' }, { linkTypes: linkFamily('invested_in'), toward: 'subject' }], excludeAnchor: false,
+ }, {}, { frontierCap: 50, neighborCap: 100, pathsPerNode: 10, hubWeighting: true });
+ expect(rows.filter(r => r.role === 'answer').length).toBeLessThanOrEqual(100);
+ expect(diagnostics.cap_hit).toEqual({ cap: 'neighbor', hop: 2 });
+ expect(diagnostics.status).toBe('truncated');
+ });
+});
+
+/**
+ * Release gate: a node the caller may not read changes nothing it could
+ * observe. Each case compares a chain over a graph holding one hidden element
+ * (private, quarantined or other-source intermediate; hidden
+ * degree contributor; link written on a hidden origin page) against the same
+ * chain after that element is physically removed: answers, scores, path
+ * counts, best paths and diagnostics must be identical.
+ */
+describe('hidden-node invariance', () => {
+ let h: PGLiteEngine;
+ const plan: ChainPlan = {
+ hops: [{ linkTypes: linkFamily('invested_in'), toward: 'object' }, { linkTypes: ['founded'], toward: 'subject' }],
+ excludeAnchor: false,
+ };
+ const policy = { excludePrivate: true, sourceId: 'default' };
+
+ async function chain(scope: { excludePrivate?: boolean; sourceId?: string } = policy) {
+ const rows = await h.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = 'people/ann-example' AND source_id = 'default'`);
+ const out = await runRelationalChain(h, [{ page_id: Number(rows[0].id), slug: 'people/ann-example', source_id: 'default' }], plan, scope);
+ return JSON.stringify({
+ rows: out.rows.map(r => ({ slug: r.slug, role: r.role, score: r.score, path_count: r.path_count, nodes: r.best_path.nodes })),
+ diagnostics: out.diagnostics,
+ });
+ }
+
+ beforeAll(async () => {
+ h = new PGLiteEngine();
+ await h.connect({});
+ await h.initSchema();
+ await h.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT (id) DO NOTHING`);
+ for (const [slug, type] of [['people/ann-example', 'person'], ['people/ben-example', 'person'], ['people/cy-example', 'person'],
+ ['companies/open-example', 'company'], ['companies/two-example', 'company']] as const) {
+ await h.putPage(slug, { type, title: slug, compiled_truth: slug, timeline: '' });
+ }
+ await h.addLink('people/ann-example', 'companies/open-example', '', 'invested_in', 'markdown');
+ await h.addLink('people/ann-example', 'companies/two-example', '', 'invested_in', 'markdown');
+ await h.addLink('companies/open-example', 'people/ben-example', 'founded by ben', 'founded', 'markdown');
+ await h.addLink('people/cy-example', 'companies/two-example', '', 'founded', 'markdown');
+ await h.addLink('people/cy-example', 'companies/open-example', '', 'invested_in', 'markdown');
+ }, 60_000);
+
+ afterAll(async () => {
+ await h.disconnect();
+ });
+
+ const hiddenCompany = async (slug: string, frontmatter: Record<string, unknown>, sourceId = 'default') => {
+ await h.putPage(slug, { type: 'company', title: slug, compiled_truth: slug, timeline: '', frontmatter }, { sourceId } as never);
+ await h.putPage('people/zed-example', { type: 'person', title: 'zed', compiled_truth: 'zed', timeline: '' }, { sourceId } as never);
+ await h.addLink('people/ann-example', slug, '', 'invested_in', 'markdown', undefined, undefined, { toSourceId: sourceId });
+ await h.addLink(slug, 'people/zed-example', '', 'founded', 'markdown', undefined, undefined, { fromSourceId: sourceId, toSourceId: sourceId });
+ };
+ const purge = async (...slugs: string[]) => {
+ await h.executeRaw(`DELETE FROM links WHERE from_page_id IN (SELECT id FROM pages WHERE slug = ANY($1::text[]))
+ OR to_page_id IN (SELECT id FROM pages WHERE slug = ANY($1::text[]))`, [slugs]);
+ await h.executeRaw(`DELETE FROM pages WHERE slug = ANY($1::text[])`, [slugs]);
+ };
+
+ test('private, quarantined and archived-source intermediates', async () => {
+ const clean = await chain();
+ await hiddenCompany('companies/priv-example', { visibility: 'private' });
+ expect(await chain({ sourceId: 'default' })).toContain('people/zed-example');
+ expect(await chain()).toBe(clean);
+ await purge('companies/priv-example', 'people/zed-example');
+ await hiddenCompany('companies/quar-example', { [QUARANTINE_KEY]: { reason: 'test' } });
+ expect(await chain()).toBe(clean);
+ await purge('companies/quar-example', 'people/zed-example');
+ expect(await chain()).toBe(clean);
+ });
+
+ test('a hidden degree contributor does not move scores', async () => {
+ const clean = await chain();
+ for (let i = 0; i < 5; i++) {
+ await h.putPage(`people/shadow-${i}-example`, { type: 'person', title: 's', compiled_truth: 's', timeline: '', frontmatter: { visibility: 'private' } });
+ await h.addLink(`people/shadow-${i}-example`, 'companies/open-example', '', 'invested_in', 'markdown');
+ }
+ expect(await chain({ sourceId: 'default' })).not.toBe(clean);
+ expect(await chain()).toBe(clean);
+ await purge(...Array.from({ length: 5 }, (_, i) => `people/shadow-${i}-example`));
+ });
+
+ test('a link written on a hidden origin page is not walked and does not count toward degree', async () => {
+ const clean = await chain();
+ await h.putPage('meetings/secret-example', { type: 'meeting', title: 'm', compiled_truth: 'm', timeline: '', frontmatter: { visibility: 'private' } });
+ await h.putPage('people/dee-example', { type: 'person', title: 'dee', compiled_truth: 'dee', timeline: '' });
+ await h.addLink('companies/two-example', 'people/dee-example', '', 'founded', 'markdown', 'meetings/secret-example', 'body');
+ await h.addLink('people/dee-example', 'companies/open-example', '', 'invested_in', 'markdown', 'meetings/secret-example', 'body');
+ expect(await chain()).toBe(clean);
+ await purge('meetings/secret-example', 'people/dee-example');
+ });
+
+ test('a cross-source edge is not followed', async () => {
+ const clean = await chain();
+ await hiddenCompany('companies/far-example', {}, 'other');
+ expect((await h.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = 'companies/far-example'`))[0].source_id).toBe('other');
+ expect(await chain({})).toBe(clean);
+ await purge('companies/far-example', 'people/zed-example');
+ });
+});
diff --git a/test/traverse-graph-hops.test.ts b/test/traverse-graph-hops.test.ts
new file mode 100644
index 0000000000..ab6ded2d9b
--- /dev/null
+++ b/test/traverse-graph-hops.test.ts
@@ -0,0 +1,111 @@
+/**
+ * traverse_graph `hops` (agent-structured typed chains), through the real MCP
+ * dispatcher for remote callers and the op handler for trusted local callers.
+ *
+ * Protects: a 1-3 hop chain returns answers with evidence edges; bad hops and
+ * conflicting params are `invalid_params`, never silently ignored; a chain that
+ * finds nothing distinguishes an invisible start page from missing edges and
+ * names the next call; remote callers never see private pages or raw context
+ * beyond the sanitized excerpt; a granted token cannot reach another source.
+ * Regression it catches: hops ignored (plain traversal returned), depth/type
+ * silently dropped, private evidence leaking to remote callers.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type AuthInfo, type OperationContext } from '../src/core/operations.ts';
+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+
+let engine: PGLiteEngine;
+
+const HOPS = [{ link_type: 'invested_in', toward: 'object' }, { link_type: 'founded', toward: 'subject' }];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const page = (slug: string, type: string, frontmatter?: Record<string, unknown>) =>
+ engine.putPage(slug, { type: type as 'person', title: slug.split('/')[1], compiled_truth: `${slug} body`, timeline: '', ...(frontmatter ? { frontmatter } : {}) });
+ await page('people/alice-example', 'person');
+ await page('people/bob-example', 'person');
+ await page('people/priv-example', 'person', { visibility: 'private' });
+ await page('companies/acme-example', 'company');
+ await page('companies/lonely-example', 'company');
+ await engine.addLink('people/alice-example', 'companies/acme-example', 'alice backed acme', 'invested_in', 'markdown');
+ await engine.addLink('companies/acme-example', 'people/bob-example', `founded by bob ${'x'.repeat(400)}`, 'founded', 'markdown');
+ await engine.addLink('people/priv-example', 'companies/acme-example', 'priv cofounded acme', 'founded', 'markdown');
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+function localCtx(notices: Notice[] = []): OperationContext {
+ return {
+ engine: engine as never, config: {} as never, dryRun: false, remote: false, sourceId: 'default',
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ emitNotice: (n: Notice) => { notices.push(n); },
+ };
+}
+
+function remoteOpts(): DispatchOpts {
+ const auth = { token: '', clientId: 'client-a', scopes: ['read'], sourceId: 'default', allowedSources: ['default'], principal: { kind: 'oauth_client', id: 'client-a' } } as AuthInfo;
+ return { remote: true, transport: 'http', sourceId: 'default', auth, localFederatedSourceIds: ['default'] };
+}
+
+const runLocal = (params: Record<string, unknown>, notices?: Notice[]) =>
+ operationsByName.traverse_graph.handler(localCtx(notices), params) as Promise<any>;
+
+describe('traverse_graph hops', () => {
+ test('two-hop chain returns answers with evidence, oriented across stored direction', async () => {
+ const res = await runLocal({ slug: 'people/alice-example', hops: HOPS });
+ expect(res.diagnostics.status).toBe('fired');
+ expect(res.answers.map((a: any) => a.slug).sort()).toEqual(['people/bob-example', 'people/priv-example']);
+ const bob = res.paths[res.answers.findIndex((a: any) => a.slug === 'people/bob-example')];
+ expect(bob.nodes).toEqual(['people/alice-example', 'companies/acme-example', 'people/bob-example']);
+ expect(bob.edges[1]).toMatchObject({ link_type: 'founded', stored_from: 'companies/acme-example', orientation: 'flipped' });
+ });
+
+ test('remote callers: private pages hidden; context only from sealed pages, sanitized and bounded', async () => {
+ const remote = async () => JSON.parse((await dispatchToolCall(engine, 'traverse_graph', { slug: 'people/alice-example', hops: HOPS }, remoteOpts())).content[0].text);
+ const unsealed = await remote();
+ expect(unsealed.answers.map((a: any) => a.slug)).toEqual(['people/bob-example']);
+ expect(unsealed.paths[0].edges[1].context).toBeNull();
+ const before = await engine.executeRaw<{ v: number }>(`SELECT chunker_version AS v FROM pages WHERE slug = 'companies/acme-example'`);
+ await engine.executeRaw(`UPDATE pages SET chunker_version = 4 WHERE slug = 'companies/acme-example'`);
+ const body = await remote();
+ await engine.executeRaw(`UPDATE pages SET chunker_version = $1 WHERE slug = 'companies/acme-example'`, [before[0].v]);
+ const ctx = body.paths[0].edges[1].context as string;
+ expect(ctx.startsWith('founded by bob')).toBe(true);
+ expect(ctx.length).toBeLessThanOrEqual(160);
+ });
+
+ test('invalid hops and conflicting params are invalid_params with the exact problem', async () => {
+ await expect(runLocal({ slug: 'people/alice-example', hops: [{ link_type: 'mentions', toward: 'object' }] }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('hops[0].link_type') });
+ await expect(runLocal({ slug: 'people/alice-example', hops: [{ link_type: 'founded', toward: 'in' }] }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('hops[0].toward') });
+ await expect(runLocal({ slug: 'people/alice-example', hops: [...HOPS, ...HOPS] }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('at most 3 hops') });
+ await expect(runLocal({ slug: 'people/alice-example', hops: HOPS, depth: 2, link_type: 'founded' }))
+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('depth, link_type') });
+ });
+
+ test('anchor_not_found, no_edges and empty_hop each carry a notice with the next call', async () => {
+ const notices: Notice[] = [];
+ const missing = await runLocal({ slug: 'people/nobody-example', hops: HOPS }, notices);
+ expect(missing.diagnostics.status).toBe('anchor_not_found');
+ expect(notices.pop()).toMatchObject({ code: 'relational_chain', fix: { mcp: { tool: 'search' } } });
+ const none = await runLocal({ slug: 'companies/lonely-example', hops: [{ link_type: 'founded', toward: 'subject' }] }, notices);
+ expect(none.diagnostics.status).toBe('no_edges');
+ expect(notices.pop()).toMatchObject({ fix: { mcp: { tool: 'traverse_graph', arguments: { slug: 'companies/lonely-example', depth: 1 } } } });
+ const later = await runLocal({ slug: 'people/alice-example', hops: [HOPS[0], { link_type: 'advises', toward: 'subject' }] }, notices);
+ expect(later.diagnostics).toMatchObject({ status: 'empty_hop', empty_hop: 2 });
+ expect(notices.pop()).toMatchObject({ fix: { mcp: { tool: 'traverse_graph', arguments: { hops: [HOPS[0]] } } } });
+ });
+
+ test('without hops the op keeps its existing shape', async () => {
+ const res = await runLocal({ slug: 'people/alice-example', link_type: 'invested_in', direction: 'out' });
+ expect(Array.isArray(res)).toBe(true);
+ });
+});