Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
search: chains walk live relationships; tense markers set one hop's status
garrytane76b215c51d1
diff --git a/docs/guides/multi-hop.md b/docs/guides/multi-hop.mdindex 57e44a6d81..9a3615c4b5 100644--- a/docs/guides/multi-hop.md+++ b/docs/guides/multi-hop.md@@ -94,8 +94,9 @@ the hops run outward from it. Questions it does not plan, and says so in a- two relationships joined by "and" / "or" ("companies Alice founded andinvested in" is an intersection, not a chain), unless what follows "and"points back with "them" / "those";-- negation ("did not invest"), time ("in 2021", "used to"), counting and- superlatives;+- negation ("did not invest"), dates and time windows ("in 2021", "before+ 2020"), a tense marker on a relationship that does not end ("formerly+ invested in"), counting and superlatives;- two named entities, quoted names, or relationships whose page types do notchain.@@ -120,6 +121,15 @@ lists attendees in an `Attendees:` or `Participants:` section (see[attendance evidence](attendance-evidence.md)); a person merely mentioned in ameeting's notes is not an attendee.+Chains walk relationships that are true today, the same rule every graph read+follows ([temporal edges](temporal-edges.md)): an advisory role or job that+ended is skipped, while events such as founding and investing stay true after+they happen. A tense marker right before a relationship that can end sets+that hop alone: "the companies Alice formerly advised" walks ended advisory+roles, "used to work at" and "worked at" walk every job, "currently works at"+walks live ones; the other hops keep the default. `traverse_graph` with `hops` takes `status` and `as_of` like a+plain walk, and `graph.edge_validity off` turns the rule off.+## Direction and evidenceBody links keep the direction of the page they are written on: "founded bydiff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 431a69d6d2..d6f0efeae1 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -422,7 +422,7 @@ Traverse link graph from a page. Remote callers default to bidirectional edges (| `depth` | number | Max traversal depth (capped at 10). Default 5, except a remote call that lets direction default to 'both' uses 2 (bidirectional path enumeration is combinatorial on hubs); an explicit depth is always honored up to the cap. || `link_type` | string | Filter to one link type (per-edge filter, traversal only follows matching edges) || `direction` | string (`in`, `out`, `both`) | Traversal direction ('in', 'out', or 'both'). Remote callers default to 'both'; trusted local no-filter callers get the legacy outgoing-node output. |-| `hops` | array of `{link_type, toward}` | Typed chain of 1-3 hops from the start page, e.g. `[{"link_type":"invested_in","toward":"object"},{"link_type":"founded","toward":"subject"}]` (companies the person invested in, then their founders). `toward` follows the relationship's meaning (`object`: subject → object; `subject`: object → subject), not stored link direction. Returns `{anchor, answers, paths, diagnostics}` with each answer's evidence edges; a chain that finds nothing carries a `relational_chain` notice with the next call. Not combinable with `depth`, `link_type` or `direction`. Chain link types: founded, invested_in, led_round, advises, works_at, attended, yc_partner. See docs/guides/multi-hop.md. |+| `hops` | array of `{link_type, toward}` | Typed chain of 1-3 hops from the start page, e.g. `[{"link_type":"invested_in","toward":"object"},{"link_type":"founded","toward":"subject"}]` (companies the person invested in, then their founders). `toward` follows the relationship's meaning (`object`: subject → object; `subject`: object → subject), not stored link direction. Returns `{anchor, answers, paths, diagnostics}` with each answer's evidence edges; a chain that finds nothing carries a `relational_chain` notice with the next call. Not combinable with `depth`, `link_type` or `direction`; `status` and `as_of` pick which relationships each hop walks (live by default). Chain link types: founded, invested_in, led_round, advises, works_at, attended, yc_partner. See docs/guides/multi-hop.md. || `source_id` | string | Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers. || `all_sources` | boolean | Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9c6155bd70..ad8890a2ce 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grownsrc/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 delegatesrc/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 delegatesrc/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 2201 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override+src/core/types.ts 2202 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop)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 slacksrc/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/core/ops/links.ts b/src/core/ops/links.tsindex b2aaaa1f8b..a1538afbb7 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -465,9 +465,11 @@ async function traverseChain(ctx: OperationContext, p: Record<string, unknown>,`Fix ${parsed.path} and retry; omit hops to walk the graph without a chain.`);}const { policy } = await resolveLinkReadScope(ctx, p, 'traverse_graph');+ const temporal = await resolveEdgeTemporal(ctx, p, 'traverse_graph');+ reportTemporal(ctx, 'traverse_graph', p, temporal, null);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 { rows, diagnostics } = await runRelationalChain(ctx.engine, anchors, plan, temporal.disabled ? policy : { ...policy, temporal });const remote = ctx.remote !== false;const edge = (e: ChainEvidenceEdge) => ({ ...e, context: presentEdgeContext(e.context, remote) });const answers = rows.filter(r => r.role === 'answer');diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsindex 45601fd105..fa7ab51d93 100644--- a/src/core/search/read-enrichment.ts+++ b/src/core/search/read-enrichment.ts@@ -100,8 +100,8 @@ function inlineIds(ids: number[], label: string): string {* 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+ * origin and degree contributor passes the read policy (and, with `temporal`,+ * the relationship-validity predicate) 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[]> {@@ -118,6 +118,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: Cconst 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}))`;+ const live = opts.temporal ? `AND ${relationshipFilterSql(`${a}l`, { ...opts.temporal, excludePrivate: opts.excludePrivate })}` : '';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_idFROM f CROSS JOIN LATERAL (@@ -127,7 +128,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: C) ${a}lCROSS JOIN LATERAL ${byId(`${a}l.from_page_id`)} ${a}fCROSS 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}`;+ WHERE ${a}f.source_id = ${a}t.source_id AND ${pf} AND ${pt} AND ${origin} ${live}`;};// The LATERAL link scan is fenced the same way, so the walk always starts// from the frontier's links.@@ -135,6 +136,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: Cconst inBranch = branch('to_page_id', 'i');const nb = pageReadFilter('nb', policy, params, true);const dg = pageReadFilter('dg', policy, params, true);+ const degreeLive = opts.temporal ? `AND ${relationshipFilterSql('dl', { ...opts.temporal, excludePrivate: opts.excludePrivate })}` : '';const ev = pageReadFilter('ev', policy, params, true);const textGate = requiresSafeChunks(policy) ? `AND ${safeChunksFilter('ev')} AND NOT ${protectedBodyFilter('ev')}` : '';params.push(opts.toward);@@ -183,7 +185,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: CSELECT 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_idFROM links dlWHERE (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'+ AND dl.link_type = ANY($4::text[]) AND dl.link_source IS DISTINCT FROM 'mentions' ${degreeLive}OFFSET 0) dnCROSS JOIN LATERAL ${byId('dn.nb_id')} nbdiff --git a/src/core/search/relational-chain.ts b/src/core/search/relational-chain.tsindex 8df5406aca..fbc7fd464a 100644--- a/src/core/search/relational-chain.ts+++ b/src/core/search/relational-chain.ts@@ -23,6 +23,7 @@import type { BrainEngine } from '../engine.ts';import type { ChainHopEdge, PageReadPolicy } from '../types.ts';+import type { EdgeStatusFilter, EdgeTemporalOpts } from '../link-validity.ts';import { hubWeight } from './hub-dampening.ts';import { pageReadFilter } from './read-policy-sql.ts';import { sanitizeRemoteBody } from '../remote-body.ts';@@ -58,6 +59,8 @@ export interface ChainHop {toward: 'object' | 'subject';/** Page type the landing node must have, when the question names one. */nodeType?: string | null;+ /** Which relationships this hop walks when relationship validity is on ("formerly advised" → ended); default: the call's policy. */+ status?: EdgeStatusFilter;}export interface ChainPlan {@@ -186,7 +189,7 @@ export async function runRelationalChain(engine: Pick<BrainEngine, 'relationalChainHop'>,anchors: ChainAnchor[],plan: ChainPlan,- policy: PageReadPolicy,+ policy: PageReadPolicy & { temporal?: EdgeTemporalOpts },limits: ChainLimits = DEFAULT_CHAIN_LIMITS,): Promise<{ rows: RelationalChainRow[]; diagnostics: ChainDiagnostics }> {const diagnostics: ChainDiagnostics = { status: 'fired', per_hop: [], cap_hit: null };@@ -212,6 +215,7 @@ export async function runRelationalChain(const sig = signatureFor(hop.linkTypes);const edges = await engine.relationalChainHop(nodes.map(n => n.id), {...policy,+ ...(hop.status && policy.temporal ? { temporal: { ...policy.temporal, status: hop.status } } : {}),linkTypes: hop.linkTypes, toward: hop.toward,subjectTypes: [...sig.subject], objectTypes: [...sig.object],degreeLinkTypes, neighborCap: limits.neighborCap,diff --git a/src/core/search/relational-plan.ts b/src/core/search/relational-plan.tsindex acc4f265fd..f81abbd09d 100644--- a/src/core/search/relational-plan.ts+++ b/src/core/search/relational-plan.ts@@ -29,7 +29,9 @@** Refused as `unsupported` (never answered with a one-hop guess): coordination* or disjunction of relations (an "and" followed by a back-reference is a- * sequence, not coordination), negation, time constraints, comparatives,+ * sequence, not coordination), negation, dates and time windows (a tense+ * marker right before a relation that can end, "formerly advised", sets that+ * hop's relationship status instead), comparatives,* counting, quoted names, more than one candidate anchor, more than three* hops, type-incoherent chains.*@@ -38,6 +40,7 @@import { LINK_SIGNATURES, linkFamily, MAX_CHAIN_HOPS, type ChainHop } from './relational-chain.ts';import { parseRelationalQuery } from './relational-intent.ts';+import { relationSemantics, type EdgeStatusFilter } from '../link-validity.ts';export interface RelationalPlan {/** Raw anchor phrase, resolved to a page later (scope-aware). */@@ -116,6 +119,14 @@ const RELATIVE = new Set(['that', 'which', 'who', 'whom']);const HEAD_LEAD = new Set(['among', 'of', 'our', 'my']);const PREPS = new Set(['of', 'in', 'at', 'behind', 'for', 'to', 'into', 'with']);const POLITE = new Set(['list', 'show', 'name', 'find', 'give', 'me', 'tell', 'please', 'us', 'could', 'can', 'would', 'you', 'i', 'know', 'want', 'like', 'wondering', 'curious', 'see']);+/**+ * Tense markers right before a state relation pick which relationships that+ * hop walks under relationship validity ("formerly advised" → ended, "used to+ * work at" → all). Dates and other time words stay refused.+ */+const TENSE: Readonly<Record<string, EdgeStatusFilter>> = {+ former: 'ended', formerly: 'ended', previously: 'ended', past: 'ended', current: 'live', currently: 'live',+};/** Pronouns pointing back at the previous step's pages ("..., who founded THEM"). */const BACKREF = new Set(['them', 'those', 'these', 'they']);/** Head nouns that name no page type ("which other PARTIES invested ..."). */@@ -130,8 +141,8 @@ const HEAD_TYPES: Readonly<Record<string, string>> = {const REFUSE: Readonly<Record<string, string>> = {and: 'coordination', or: 'coordination', nor: 'coordination', but: 'coordination',not: 'negation', never: 'negation', no: 'negation', without: 'negation', except: 'negation', "n't": 'negation',- before: 'time', after: 'time', since: 'time', during: 'time', until: 'time', ago: 'time', currently: 'time',- previously: 'time', recently: 'time', formerly: 'time', former: 'time', current: 'time', year: 'time', years: 'time',+ before: 'time', after: 'time', since: 'time', during: 'time', until: 'time', ago: 'time',+ recently: 'time', year: 'time', years: 'time',most: 'comparative', more: 'comparative', least: 'comparative', fewest: 'comparative', top: 'comparative',many: 'count', count: 'count', number: 'count',};@@ -204,7 +215,23 @@ export function parseRelationalPlan(query: string): PlanResult {const why = REFUSE[t.lower] ?? (/^(1[89]|20)\d\d$/.test(t.lower) ? 'time' : undefined);if (why) return { kind: 'unsupported', reason: `${why} constraints are not planned ("${t.text}")` };}- if (toks.some((t, i) => t.lower === 'used' && toks[i + 1]?.lower === 'to')) return { kind: 'unsupported', reason: 'time constraints are not planned ("used to")' };+ const tenseOf = new Map<Rel, EdgeStatusFilter>();+ const tenseTok = new Set<number>();+ for (let i = 0; i < toks.length; i++) {+ const usedTo = toks[i].lower === 'used' && toks[i + 1]?.lower === 'to';+ const status = usedTo ? 'all' : TENSE[toks[i].lower];+ if (!status) continue;+ const marker = query.slice(toks[i].start, toks[usedTo ? i + 1 : i].end);+ let j = i + (usedTo ? 2 : 1);+ while (j < toks.length && DETERMINERS.has(toks[j].lower)) j++;+ const rel = rels.find(r => r.from === j);+ if (!rel) return { kind: 'unsupported', reason: `time constraints are not planned ("${marker}")` };+ if (relationSemantics(rel.entry.rel) !== 'state') return { kind: 'unsupported', reason: `${rel.entry.rel} does not end, so "${marker}" is not planned` };+ tenseOf.set(rel, status);+ tenseTok.add(i);+ if (usedTo) tenseTok.add(i + 1);+ }+ for (const r of rels) if (!tenseOf.has(r) && toks[r.from].lower === 'worked' && r.entry.rel === 'works_at') tenseOf.set(r, 'all');if (relCount > MAX_CHAIN_HOPS) return { kind: 'unsupported', reason: `more than ${MAX_CHAIN_HOPS} relations` };// Classify every non-relation token; leftovers form the anchor.@@ -212,7 +239,7 @@ export function parseRelationalPlan(query: string): PlanResult {let excludeAnchor = false;const leftover: number[] = [];for (let i = 0; i < toks.length; i++) {- if (used[i]) continue;+ if (used[i] || tenseTok.has(i)) continue;const l = toks[i].lower;if (OTHER_MARKERS.has(l)) { excludeAnchor = true; continue; }if (l === "'s" || l === 'and' || GENERIC_HEADS.has(l)) continue;@@ -239,7 +266,7 @@ export function parseRelationalPlan(query: string): PlanResult {// "which companies DID ... back") is always outermost; the rest order by// how many content tokens separate them from the anchor, nouns binding// tighter than verbs at equal distance.- const scaffold = (l: string) => WH.has(l) || AUX.has(l) || DETERMINERS.has(l) || POLITE.has(l) || OTHER_MARKERS.has(l) || GENERIC_HEADS.has(l) || HEAD_TYPES[l] !== undefined;+ const scaffold = (l: string) => TENSE[l] !== undefined || WH.has(l) || AUX.has(l) || DETERMINERS.has(l) || POLITE.has(l) || OTHER_MARKERS.has(l) || GENERIC_HEADS.has(l) || HEAD_TYPES[l] !== undefined;const isVerb = (r: Rel) => r.entry.form === 'verb' || r.entry.form === 'passive';const startsWithWh = lead < toks.length && WH.has(toks[lead].lower);// "which companies DID alice back": the auxiliary is followed by its subject,@@ -250,7 +277,7 @@ export function parseRelationalPlan(query: string): PlanResult {(startsWithWh && toks.slice(0, r.from).every(t => scaffold(t.lower))) ||(auxInverted && r === lastRel && r.to === toks.length - 1));- const skip = (l: string) => DETERMINERS.has(l) || PREPS.has(l) || RELATIVE.has(l) || AUX.has(l) || OTHER_MARKERS.has(l) || l === "'s" || l === 'by' || l === 'whose';+ const skip = (l: string) => TENSE[l] !== undefined || l === 'used' || DETERMINERS.has(l) || PREPS.has(l) || RELATIVE.has(l) || AUX.has(l) || OTHER_MARKERS.has(l) || l === "'s" || l === 'by' || l === 'whose';const dist = (r: Rel) => {const [a, b] = r.to < aStart ? [r.to + 1, aStart] : [aEnd + 1, r.from];return toks.slice(a, b).filter((t, k) => !used[a + k] && !skip(t.lower)).length + toks.slice(a, b).filter((_, k) => used[a + k]).length;@@ -279,7 +306,8 @@ export function parseRelationalPlan(query: string): PlanResult {case 'agent': toward = 'subject'; break;case 'out': toward = 'object'; break;}- hops.push({ linkTypes: lts, toward });+ const status = tenseOf.get(r);+ hops.push({ linkTypes: lts, toward, ...(status ? { status } : {}) });phrases.push(phrase);}if (hops.length > MAX_CHAIN_HOPS) return { kind: 'unsupported', reason: `more than ${MAX_CHAIN_HOPS} relations` };diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.tsindex 4b8bd310f1..3906534aac 100644--- a/src/core/search/relational-recall.ts+++ b/src/core/search/relational-recall.ts@@ -34,7 +34,7 @@ import { buildVisibilityClause } from './sql-ranking.ts';import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from './relational-intent.ts';-import { edgeValidityEnabled } from '../link-validity.ts';+import { edgeValidityEnabled, type EdgeTemporalOpts } from '../link-validity.ts';import { stampEvidence, type EvidenceOpts } from './evidence.ts';import { parseRelationalPlan } from './relational-plan.ts';import { LINK_SIGNATURES, presentEdgeContext, resolveChainAnchors, runRelationalChain, type ChainAnchor, type ChainDiagnostics, type ChainStatus, type RelationalChainRow } from './relational-chain.ts';@@ -447,7 +447,7 @@ export async function buildRelationalArm(});if (opts.orientOneHop && parsed.kind === 'who_rel' && parsed.direction !== 'both'&& parsed.linkTypes?.length && parsed.linkTypes.every(lt => LINK_SIGNATURES[lt])) {- rows = await withOrientedOneHop(engine, rows, resolved, parsed, opts);+ rows = await withOrientedOneHop(engine, rows, resolved, parsed, temporal ? { ...opts, temporal } : opts);}const list = await hydrate(engine, rows, resolved[0].slug, opts);meta.fired = list.length > 0;@@ -488,7 +488,9 @@ async function planChain(const anchors: ChainAnchor[] = [];for (const ref of refs) anchors.push(...await resolveChainAnchors(engine, ref.slug, { ...opts, sourceIds: undefined, sourceId: ref.source_id }));meta.seeds_resolved = anchors.length;- const { rows, diagnostics } = await runRelationalChain(engine, anchors, { hops: plan.hops, excludeAnchor: plan.excludeAnchor }, opts);+ // Live relationships by default; a tense marker on one relation ("formerly advised") sets that hop's status.+ const temporal = await edgeValidityEnabled(engine) ? { status: 'live' as const } : undefined;+ const { rows, diagnostics } = await runRelationalChain(engine, anchors, { hops: plan.hops, excludeAnchor: plan.excludeAnchor }, temporal ? { ...opts, temporal } : opts);meta.plan = {status: diagnostics.status, anchor: plan.anchor, anchor_slugs: anchors.map(a => a.slug),hops: diagnostics.per_hop, answers: rows.filter(r => r.role === 'answer').length,@@ -547,7 +549,7 @@ async function withOrientedOneHop(rows: RelationalFanoutRow[],seeds: Array<{ source_id: string; slug: string }>,parsed: RelationalQuery,- opts: RelationalArmOpts,+ opts: RelationalArmOpts & { temporal?: EdgeTemporalOpts },): Promise<RelationalFanoutRow[]> {const anchors: ChainAnchor[] = [];for (const s of seeds) anchors.push(...await resolveChainAnchors(engine, s.slug, { ...opts, sourceIds: undefined, sourceId: s.source_id }));diff --git a/src/core/types.ts b/src/core/types.tsindex 8263800cfa..b05136cf7b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1581,6 +1581,7 @@ export interface ChainHopOpts extends PageReadPolicy {degreeLinkTypes: string[];/** Max logical edges returned per frontier node (deterministic: lowest link id first). */neighborCap: number;+ temporal?: import('./link-validity.ts').EdgeTemporalOpts; // relationship-validity policy per link row; absent = every edge}/**diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex bdab94abcd..8a5863e593 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 197373,- "stdoutSha256": "c24014bb9d4d2fcc6b6ec6af92fd77ae6d5aafa090dedda4d0fb9af651361b2f",+ "stdoutBytes": 199265,+ "stdoutSha256": "3ee8da67bc32b9b638fd0d94477cc03bbc59eca82a800d0563b56fca13fdfcb2","toolNames": ["remember","entity",@@ -1479,7 +1479,9 @@"from": "string","link_source": "string?","link_type": "string?",- "to": "string"+ "to": "string",+ "valid_from": "string?",+ "valid_until": "string?"},"required_scopes": [],"schema": {@@ -1503,6 +1505,14 @@"to": {"description": "Slug of the page the link points to, e.g. 'companies/acme-example'.","type": "string"+ },+ "valid_from": {+ "description": "When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in.",+ "type": "string"+ },+ "valid_until": {+ "description": "When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended.",+ "type": "string"}},"required": [@@ -1554,15 +1564,19 @@"scope": "write"},{- "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.","idempotent": true,"local_only": false,"mutating": false,"name": "get_links","parameters": {"all_sources": "boolean?",+ "as_of": "string?",+ "during": "string?",+ "link_type": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1571,6 +1585,18 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD.",+ "type": "string"+ },+ "during": {+ "description": "Period: 2022, 2022-03 or 2021..2023.",+ "type": "string"+ },+ "link_type": {+ "description": "Only this type.",+ "type": "string"+ },"slug": {"description": "Slug of the page whose outgoing links to list.","type": "string"@@ -1578,6 +1604,15 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live (true now).",+ "enum": [+ "live",+ "ended",+ "all"+ ],+ "type": "string"}},"required": [@@ -1595,8 +1630,10 @@"name": "get_backlinks","parameters": {"all_sources": "boolean?",+ "as_of": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1605,6 +1642,10 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD",+ "type": "string"+ },"slug": {"description": "Page slug.","type": "string"@@ -1612,6 +1653,14 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live.",+ "enum": [+ "live",+ "all"+ ],+ "type": "string"}},"required": [@@ -1644,12 +1693,14 @@"name": "traverse_graph","parameters": {"all_sources": "boolean?",+ "as_of": "string?","depth": "number?","direction": "string?","hops": "array?","link_type": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1658,6 +1709,10 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD",+ "type": "string"+ },"depth": {"description": "Max depth (cap 10).","type": "number"@@ -1699,6 +1754,14 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live.",+ "enum": [+ "live",+ "all"+ ],+ "type": "string"}},"required": [@@ -6286,6 +6349,7 @@"degraded_dedup","empty_retrieval","features_auto_fix",+ "former_relationships_hidden","listing_truncated","local_transcripts","onboard_opportunities",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex dd3266dd7e..ed7389d446 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -310,6 +310,7 @@"sourceIds?: string[] | undefined","subjectTypes: string[]","takesHoldersAllowList?: string[] | undefined",+ "temporal?: EdgeTemporalOpts | undefined","toward: \"object\" | \"subject\""],"name": "ChainHopOpts"@@ -7495,6 +7496,7 @@"sourceIds?: string[] | undefined","subjectTypes: string[]","takesHoldersAllowList?: string[] | undefined",+ "temporal?: EdgeTemporalOpts | undefined","toward: \"object\" | \"subject\""],"name": "ChainHopOpts"diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.tsindex e43999f2ae..770e81f864 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-esticonst 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; +279 for traverse_graph's optional `hops` typed-chain parameter). */-const SERVED_STARTER_MAX_JSON_CHARS = 26_050;+/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; temporal status/as_of params under 26,000; +279 for traverse_graph's optional `hops` typed-chain parameter, 26,278 measured). */+const SERVED_STARTER_MAX_JSON_CHARS = 26_300;/** 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;diff --git a/test/relational-plan.test.ts b/test/relational-plan.test.tsindex b77ce6f255..86ae4fcd51 100644--- a/test/relational-plan.test.ts+++ b/test/relational-plan.test.ts@@ -71,12 +71,47 @@ describe('parseRelationalPlan: plans', () => {});});+describe('parseRelationalPlan: tense markers on relations that can end', () => {+ const statuses = (q: string) => {+ const r = parseRelationalPlan(q);+ return r.kind === 'plan' ? r.plan.hops.map(h => [h.linkTypes[0], h.toward, h.status ?? null]) : r;+ };+ test('"formerly advised" walks ended advisory relationships; the founding hop keeps the default', () => {+ expect(statuses('Who founded the companies Alice Example formerly advised?'))+ .toEqual([['advises', 'object', 'ended'], ['founded', 'subject', null]]);+ });+ test('"used to work at" walks every employment; "worked at" too', () => {+ expect(statuses('Who advises the companies Bob Example used to work at?'))+ .toEqual([['works_at', 'object', 'all'], ['advises', 'subject', null]]);+ expect(statuses('Who founded the companies Bob Example worked at?'))+ .toEqual([['works_at', 'object', 'all'], ['founded', 'subject', null]]);+ });+ test('a marker attaches to the relation right after it', () => {+ expect(statuses("Which companies did Carol Example's former employees found?"))+ .toEqual([['works_at', 'subject', 'ended'], ['founded', 'object', null]]);+ expect(statuses('Who currently works at the companies founded by Dave Example?'))+ .toEqual([['founded', 'object', null], ['works_at', 'subject', 'live']]);+ });+ test('events do not end, and dates stay refused', () => {+ for (const [q, reason] of [+ ['Who founded the companies Alice Example formerly invested in?', 'does not end'],+ ['Who previously founded the companies Bob Example backed?', 'does not end'],+ ['Who advised the companies Bob Example funded in 2021?', 'time'],+ ['Who founded the companies Alice Example advised before 2020?', 'time'],+ ['Formerly, who founded the companies Alice Example advises?', 'time'],+ ] as const) {+ const r = parseRelationalPlan(q);+ expect(r.kind).toBe('unsupported');+ expect(r.kind === 'unsupported' && r.reason).toContain(reason);+ }+ });+});+describe('parseRelationalPlan: refusals', () => {for (const [q, reason] of [['Which companies did Alice Example found and invest in?', 'coordination'],['Who advised the companies that Bob Example funded in 2021?', 'time'],['Who founded companies that Alice Example did not invest in?', 'negation'],- ['Who used to work at companies backed by fund-a?', 'time'],['How many founders of companies backed by fund-a are there?', 'count'],['Who founded the companies "Alice" invested in?', 'quoted'],] as const) {diff --git a/test/traverse-graph-hops.test.ts b/test/traverse-graph-hops.test.tsindex ab6ded2d9b..b2565b4410 100644--- a/test/traverse-graph-hops.test.ts+++ b/test/traverse-graph-hops.test.ts@@ -15,6 +15,8 @@ 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';+import { buildRelationalArm } from '../src/core/search/relational-recall.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';let engine: PGLiteEngine;@@ -109,3 +111,34 @@ describe('traverse_graph hops', () => {expect(Array.isArray(res)).toBe(true);});});++describe('traverse_graph hops: relationship validity', () => {+ test('an ended state relationship is not walked by default; status "all" walks it', async () => {+ await engine.putPage('people/carol-example', { type: 'person', title: 'carol', compiled_truth: 'carol', timeline: '' });+ await engine.putPage('companies/old-example', { type: 'company', title: 'old', compiled_truth: 'old', timeline: '' });+ await engine.addLink('companies/old-example', 'people/bob-example', 'founded by bob', 'founded', 'markdown');+ await operationsByName.add_link.handler(localCtx(), {+ from: 'people/carol-example', to: 'companies/old-example', link_type: 'advises', valid_from: '2019-01-01', valid_until: '2021-06-30',+ });+ const hops = [{ link_type: 'advises', toward: 'object' }, { link_type: 'founded', toward: 'subject' }];+ const live = await runLocal({ slug: 'people/carol-example', hops });+ expect(live.answers).toEqual([]);+ expect(live.diagnostics.status).toBe('no_edges');+ const all = await runLocal({ slug: 'people/carol-example', hops, status: 'all' });+ expect(all.answers.map((a: { slug: string }) => a.slug)).toEqual(['people/bob-example']);+ const then = await runLocal({ slug: 'people/carol-example', hops, as_of: '2020-03-01' });+ expect(then.answers.map((a: { slug: string }) => a.slug)).toEqual(['people/bob-example']);++ // The search arm: present tense walks live relationships, "formerly" walks the ended one.+ for (const slug of ['people/bob-example', 'companies/old-example']) {+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `${slug} body` }]);+ }+ const arm = async (q: string) => {+ let meta: any;+ const list = await buildRelationalArm(engine, q, { planner: true, onMeta: m => { meta = m; } });+ return { answers: list.filter(r => r.relational?.role === 'answer').map(r => r.slug), status: meta.plan?.status };+ };+ expect(await arm('Who founded the companies Carol Example advises?')).toEqual({ answers: [], status: 'no_edges' });+ expect(await arm('Who founded the companies Carol Example formerly advised?')).toEqual({ answers: ['people/bob-example'], status: 'fired' });+ });+});