Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): live-by-default temporal graph reads (GBRA-49 P1)

garrytan5a4c7d90912c
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 25ff219388..2b62fb2724 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -112,11 +112,11 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S
|---|---|---|---|---|
| `add_link` | Create a typed link (edge) from one page to another in the same source. | write | | |
| `find_orphans` | Find disconnected pages. | read | | |
-| `get_backlinks` | List links pointing to a page. | read | yes | |
+| `get_backlinks` | List links pointing to a page, such as who works at a company. | read | yes | |
| `get_links` | List a page's outgoing links (typed edges to other pages). | read | | |
| `list_link_sources` | Link provenances in the brain (e.g. | read | yes | |
| `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |
-| `traverse_graph` | Walk the link graph from a page. | read | yes | |
+| `traverse_graph` | Walk the link graph from a page along relationships that are true today (status: "all" walks history, as_of a past date). | read | yes | |
## loops
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 70283d6408..8763328f1d 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -47,6 +47,7 @@ const CONSTANT_ALLOWLIST: Record<string, string> = {
EMBED_SKIP_FILTER_FRAGMENT: 'src/core/embed-skip.ts: constant embed_skip predicate over alias p',
QUARANTINE_FILTER_FRAGMENT: 'src/core/quarantine.ts: constant quarantine visibility predicate over the pages alias p',
PAGE_SORT_SQL: 'src/core/types.ts: ORDER BY text keyed by the PageFilters sort union (whitelisted enum)',
+ TEMPORAL_LINK_SELECT_SQL: 'src/core/link-validity.ts: constant select list over the lr_t relationship-state join',
};
const VETTED_BUILDERS: Record<string, string> = {
@@ -64,6 +65,8 @@ const VETTED_BUILDERS: Record<string, string> = {
privateTimelineEventFilterFragment: 'src/core/search/private-visibility.ts: constant timeline-event visibility predicate over a caller alias',
privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',
vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',
+ temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',
+ relationshipFilterSql: 'src/core/link-validity.ts: relationship-state probe over a caller alias; dates pass isCalendarDate and inline as DATE literals, status/scope are literals',
};
const SQL_ARG_METHODS: Record<string, number> = { query: 0, unsafe: 0, executeRaw: 0 };
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsv
index 9d35c2f5ab..c38676eb32 100644
--- a/scripts/engine-sql-baseline.tsv
+++ b/scripts/engine-sql-baseline.tsv
@@ -14,7 +14,6 @@ migrated code-edges
migrated facts
migrated files
migrated health
-migrated link-relationships
migrated links
migrated pages
migrated salience
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..49fde4b332 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 3224 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)
src/core/cycle/synthesize.ts 3297 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)
src/core/cycle/extract-atoms.ts 1808 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)
-src/core/engine.ts 2678 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)
+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 temporal typed edges: LinkReadScope import
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 2926 ratchet +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)
src/core/postgres-engine.ts 2917 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)
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 2124 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)
+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 temporal typed edges: RelationalFanoutOpts.temporal
src/core/minions/queue.ts 2522 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
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/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 8dfef2b9a9..eb0d8fb8df 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -694,7 +694,7 @@ export const CHECKPOINT_LINKS_RENDER_CAP = 10;
// packers in ops/facts.ts — the packer prices exactly the bytes the renderer
// emits, so `text` honors budget_tokens instead of overshooting it.
export const renderCardLine = (c: EntityCard): string =>
- `- **${c.entity.title}** → \`${c.entity.slug}\`${c.summary ? ` — ${c.summary}` : ''} (use get_page/entity before relying on details)`;
+ `- **${c.entity.title}** → \`${c.entity.slug}\`${c.summary ? ` — ${c.summary}` : ''}${c.relationship_note ? ` [${c.relationship_note}]` : ''} (use get_page/entity before relying on details)`;
export const renderThreadLine = (t: EntityOpenThread): string =>
`- [${t.kind}] ${t.text}${t.date ? ` (${t.date})` : ''}`;
export const renderFactLine = (f: TurnContextFact): string =>
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index 3ca0f45f6b..4a1af9edce 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -22,8 +22,20 @@ import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
-import { refreshRelationships, type RelationshipKey } from './link-relationships.ts';
-import { isTemporalLinkType } from '../link-validity.ts';
+import { refreshRelationships, type RelationshipKey } from '../link-relationships.ts';
+import { isTemporalLinkType, relationshipFilterSql, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, annotateTemporalRow } from '../link-validity.ts';
+import type { LinkReadScope } from '../link-validity.ts';
+
+/** Bounded link reads annotate rows with relationship status (never filter) when a temporal read is requested. */
+function finishTemporal(rows: unknown[], opts?: LinkReadScope): Link[] {
+ const t = opts?.temporal;
+ return (t ? rows.map(r => annotateTemporalRow(r as Link, t.asOf)) : rows) as Link[];
+}
+
+/** WHERE fragment that keeps only edges matching the caller's temporal policy (walks and fanout). */
+function temporalWalkFilter(alias: string, opts?: LinkReadScope) {
+ return opts?.temporal ? trustedSql(`AND ${relationshipFilterSql(alias, { ...opts.temporal, excludePrivate: opts.excludePrivate })}`) : sqlFragment``;
+}
export async function addLink(
exec: SqlExecutor,
@@ -232,8 +244,11 @@ export async function removeLink(
}
-export async function getLinks(exec: ScopedRead, slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadScope): Promise<Link[]> {
const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
+ const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
+ const finish = (rows: unknown[]) => finishTemporal(rows, opts);
// #2200: federated grant scopes ALL THREE page endpoints — from, to, AND
// the origin (the page that authored the edge, surfaced as origin_slug).
// Scoping only from+to would still leak an out-of-grant origin's slug; the
@@ -246,16 +261,16 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: { sourceId
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])
+ LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[]) ${trustedSql(tJoin)}
WHERE f.slug = ${slug} AND f.source_id = ANY(${ids}::text[]) AND t.source_id = ANY(${ids}::text[])
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
// v0.31.8 (D16) + #2200: the federated arm above is the first branch; the
// two below preserve pre-v0.31.8 semantics. Without opts.sourceId, no
@@ -270,37 +285,40 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: { sourceId
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id
+ LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE f.slug = ${slug} AND f.source_id = ${opts.sourceId}
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id
+ LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE f.slug = ${slug}
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
-export async function getBacklinks(exec: ScopedRead, slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+export async function getBacklinks(exec: ScopedRead, slug: string, opts?: LinkReadScope): Promise<Link[]> {
const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
+ const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
+ const finish = (rows: unknown[]) => finishTemporal(rows, opts);
// #2200: federated grant scopes all three endpoints (mirrors getLinks) —
// the referrer (from), the queried page (to), AND the origin — so neither
// a foreign referrer nor a foreign origin slug is disclosed to the caller.
@@ -311,16 +329,16 @@ export async function getBacklinks(exec: ScopedRead, slug: string, opts?: { sour
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])
+ LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[]) ${trustedSql(tJoin)}
WHERE t.slug = ${slug} AND t.source_id = ANY(${ids}::text[]) AND f.source_id = ANY(${ids}::text[])
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
// v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks
// (incl. the #3754 soft-delete endpoint filter on all three arms).
@@ -330,32 +348,32 @@ export async function getBacklinks(exec: ScopedRead, slug: string, opts?: { sour
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id
+ LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE t.slug = ${slug} AND t.source_id = ${opts.sourceId}
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
const rows = (await exec.run(sqlFragment`
SELECT f.slug as from_slug, f.source_id as from_source_id,
t.slug as to_slug, t.source_id as to_source_id,
l.link_type, l.context, l.link_source,
o.slug as origin_slug, o.source_id as origin_source_id,
- l.origin_field
+ l.origin_field ${trustedSql(tSel)}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
- LEFT JOIN pages o ON o.id = l.origin_page_id
+ LEFT JOIN pages o ON o.id = l.origin_page_id ${trustedSql(tJoin)}
WHERE t.slug = ${slug}
AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${trustedSql(privacy)}
ORDER BY l.id
`)).rows;
- return rows as unknown as Link[];
+ return finish(rows);
}
@@ -493,7 +511,7 @@ export async function traverseGraph(
WHERE g.depth < ${depth}
AND NOT (p2.id = ANY(g.visited))
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- ${stepScope}
+ ${stepScope} ${temporalWalkFilter('l', opts)}
ORDER BY p2.slug ASC, p2.id ASC
LIMIT ${cap})`
: sqlFragment`SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id
@@ -503,7 +521,7 @@ export async function traverseGraph(
WHERE g.depth < ${depth}
AND NOT (p2.id = ANY(g.visited))
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- ${stepScope}`;
+ ${stepScope} ${temporalWalkFilter('l', opts)}`;
// Cycle prevention: visited array tracks page IDs already in the path.
const rows = (await exec.run(sqlFragment`
WITH RECURSIVE graph AS (
@@ -526,7 +544,7 @@ export async function traverseGraph(
(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))
FROM links l2
JOIN pages p3 ON p3.id = l2.to_page_id
- WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope}),
+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope} ${temporalWalkFilter('l2', opts)}),
'[]'::jsonb
) as links
FROM (SELECT DISTINCT id, slug, source_id, title, type, depth
@@ -554,7 +572,7 @@ export async function traverseGraph(
export async function traversePathsDetailed(
exec: LegacyUnscopedRead,
slug: string,
- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
+ opts?: LinkReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },
): Promise<{ paths: GraphPath[]; truncated: boolean }> {
const privacy = (page: string, link?: string) => opts?.excludePrivate
? trustedSql(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sqlFragment``;
@@ -607,7 +625,7 @@ export async function traversePathsDetailed(
WHERE w.depth + 1 < ${depth}
AND NOT (p2.id = ANY(w.visited))
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${stepScope}
),
capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),
@@ -621,7 +639,7 @@ export async function traversePathsDetailed(
JOIN pages p2 ON p2.id = l.to_page_id
WHERE w.depth < ${depth}
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${stepScope}
ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id
LIMIT ${TRAVERSE_PATH_ROW_CAP + 1}
@@ -639,7 +657,7 @@ export async function traversePathsDetailed(
WHERE w.depth + 1 < ${depth}
AND NOT (p2.id = ANY(w.visited))
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${stepScope}
),
capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),
@@ -653,7 +671,7 @@ export async function traversePathsDetailed(
JOIN pages p2 ON p2.id = l.from_page_id
WHERE w.depth < ${depth}
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${stepScope}
ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id
LIMIT ${TRAVERSE_PATH_ROW_CAP + 1}
@@ -671,7 +689,7 @@ export async function traversePathsDetailed(
WHERE w.depth + 1 < ${depth}
AND NOT (p2.id = ANY(w.visited))
AND p2.deleted_at IS NULL ${privacy('p2', 'l')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${stepScope}
),
capped AS (SELECT id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),
@@ -687,7 +705,7 @@ export async function traversePathsDetailed(
WHERE w.depth < ${depth}
AND pf.deleted_at IS NULL ${privacy('pf', 'l')}
AND pt.deleted_at IS NULL ${privacy('pt')}
- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
+ AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}
${pfScope}
${ptScope}
ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id
diff --git a/src/core/engine.ts b/src/core/engine.ts
index f946f3a2dd..19ed698f3e 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1,4 +1,5 @@
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
+import type { LinkReadScope } from './link-validity.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';
export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';
@@ -65,7 +66,7 @@ export interface SourceRow {
config: Record<string, unknown>;
}
-export interface TraverseGraphOpts extends PageReadScope {
+export interface TraverseGraphOpts extends LinkReadScope {
sourceId?: string;
sourceIds?: string[];
frontierCap?: number;
@@ -1458,13 +1459,13 @@ export interface BrainEngine {
* grant); the scalar branch is internal/CLI and keeps cross-source visibility
* (reconcileLinks + back-link validators depend on it).
*/
- getLinks(slug: string, opts?: PageReadScope): Promise<Link[]>;
+ getLinks(slug: string, opts?: LinkReadScope): Promise<Link[]>;
/**
* v0.31.8 (D12 + D16): same `opts.sourceId` semantics as `getLinks`,
* applied to the to-page side of the join. #2200: `opts.sourceIds` federated
* grant constrains both endpoints (see `getLinks`).
*/
- getBacklinks(slug: string, opts?: PageReadScope): Promise<Link[]>;
+ getBacklinks(slug: string, opts?: LinkReadScope): Promise<Link[]>;
/**
* v114 (#1941): distinct link_source provenances with edge counts, for
* `gbrain link-sources`. Source-scoped via `{sourceId?, sourceIds?}` (both
@@ -1541,7 +1542,7 @@ export interface BrainEngine {
*/
traversePathsDetailed(
slug: string,
- opts?: PageReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },
+ opts?: LinkReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },
): Promise<{ paths: GraphPath[]; truncated: boolean }>;
/**
* Typed-edge relational fan-out for the relational recall arm (v0.43).
diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.ts
index 2195ebe5f4..f976af92f3 100644
--- a/src/core/entity-identity.ts
+++ b/src/core/entity-identity.ts
@@ -307,7 +307,7 @@ export async function unionLinksAcrossIdentity(
slug: string,
links: Link[],
direction: 'out' | 'in',
- opts: { sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean } = {},
+ opts: { sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean; temporal?: import('./link-validity.ts').EdgeTemporalOpts } = {},
): Promise<Link[]> {
if (!(await isIdentityUnionEnabled(engine))) return links;
let members: EntityIdentityMember[];
@@ -345,6 +345,7 @@ export async function unionLinksAcrossIdentity(
sourceId: m.source_id,
...(opts.allowedSources?.length ? { sourceIds: opts.allowedSources } : {}),
excludePrivate: opts.excludePrivate,
+ ...(opts.temporal ? { temporal: opts.temporal } : {}),
};
const memberLinks = direction === 'out'
? await engine.getLinks(m.slug, memberScope)
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1ff419a60e..15a87375a3 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -319,6 +319,7 @@ export const NOTICE_CODES = {
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },
+ former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },
degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },
source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
diff --git a/src/core/engine-sql/link-relationships.ts b/src/core/link-relationships.ts
similarity index 98%
rename from src/core/engine-sql/link-relationships.ts
rename to src/core/link-relationships.ts
index 9fb73cdfea..963fb8c968 100644
--- a/src/core/engine-sql/link-relationships.ts
+++ b/src/core/link-relationships.ts
@@ -17,12 +17,12 @@
* as live, the same as an unrefreshed relationship).
*/
import { createHash } from 'node:crypto';
-import { executeRawJsonb } from '../sql-query.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { executeRawJsonb } from './sql-query.ts';
+import { privatePagesFilterFragment } from './search/private-visibility.ts';
import {
buildRelationshipState, relationSemantics, statusAt, stintsToMultirange, dateKey, TEMPORAL_LINK_TYPES,
type AssertionEvidence, type TransitionEvidence, type RelationshipScope, type TransitionProducer,
-} from '../link-validity.ts';
+} from './link-validity.ts';
export interface RelationshipKey { from_page_id: number; to_page_id: number; link_type: string }
diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.ts
index 2b853062a2..06b6549436 100644
--- a/src/core/link-temporal-apply.ts
+++ b/src/core/link-temporal-apply.ts
@@ -15,7 +15,7 @@ import type { BrainEngine, LinkBatchInput } from './engine.ts';
import type { Page } from './types.ts';
import { executeRawJsonb } from './sql-query.ts';
import { deriveTemporalEvidence, rowKey, type TemporalEvidence } from './link-temporal-evidence.ts';
-import { refreshRelationships, type RelationshipKey } from './engine-sql/link-relationships.ts';
+import { refreshRelationships, type RelationshipKey } from './link-relationships.ts';
import { TEMPORAL_LINK_TYPES } from './link-validity.ts';
type Tx = Pick<BrainEngine, 'executeRaw'>;
diff --git a/src/core/link-validity.ts b/src/core/link-validity.ts
index a2141fea10..3a5016f336 100644
--- a/src/core/link-validity.ts
+++ b/src/core/link-validity.ts
@@ -17,6 +17,7 @@
*
* Pure module except the SQL fragment builders; no engine imports.
*/
+import type { PageReadScope } from './types.ts';
export type RelationSemantics = 'state' | 'event' | 'reference';
export type TransitionKind = 'start' | 'end';
@@ -322,6 +323,11 @@ function recordedMs(v: string | Date | null): number {
// ─── SQL ─────────────────────────────────────────────────────────────────
+/** Link reads that may apply a temporal edge policy. `temporal` absent = every edge, unannotated (reference consumers). */
+export interface LinkReadScope extends PageReadScope {
+ temporal?: EdgeTemporalOpts;
+}
+
export interface EdgeTemporalOpts {
/** live (default), ended, or all. */
status?: EdgeStatusFilter;
@@ -412,3 +418,96 @@ function periodEnd(date: string, precision: DatePrecision): string {
: new Date(Date.UTC(y, m - 1, d + 1));
return next.toISOString().slice(0, 10);
}
+
+// ─── Row annotation (bounded per-page reads: get_links / get_backlinks / entity cards) ──
+
+export type EdgeRowStatus = RelationshipStatus | 'reference';
+
+/** Annotation fields added to link rows when a temporal read is requested. */
+export interface TemporalAnnotation {
+ status: EdgeRowStatus;
+ /** Stints [from, until) when the relationship has temporal state. */
+ stints?: Stint[];
+ /** When the brain first recorded evidence for the relationship. */
+ recorded_at?: string | null;
+ /** When the brain recorded that the relationship ended. */
+ retired_at?: string | null;
+}
+
+/** LEFT JOIN of a links alias onto its relationship state row for the read scope. */
+export function temporalLinkJoinSql(linkAlias: string, excludePrivate?: boolean): string {
+ return `LEFT JOIN link_relationships lr_t ON lr_t.from_page_id = ${linkAlias}.from_page_id
+ AND lr_t.to_page_id = ${linkAlias}.to_page_id AND lr_t.link_type = ${linkAlias}.link_type
+ AND lr_t.scope = '${excludePrivate ? 'world' : 'all'}'`;
+}
+
+export const TEMPORAL_LINK_SELECT_SQL = `, lr_t.valid_ranges::text AS temporal_ranges, lr_t.semantics AS temporal_semantics,
+ lr_t.disputed AS temporal_disputed, lr_t.undated_past AS temporal_undated_past, lr_t.first_start::text AS temporal_first_start,
+ lr_t.recorded_at AS temporal_recorded_at, lr_t.retired_at AS temporal_retired_at`;
+
+const TEMPORAL_COLUMNS = ['temporal_ranges', 'temporal_semantics', 'temporal_disputed', 'temporal_undated_past',
+ 'temporal_first_start', 'temporal_recorded_at', 'temporal_retired_at'] as const;
+
+const iso = (v: unknown): string | null => v == null ? null : v instanceof Date ? v.toISOString() : String(v);
+
+/** Replace the temporal_* columns of a row with its annotation (status at `asOf`, default today UTC). */
+export function annotateTemporalRow<T extends { link_type: string }>(row: T, asOf?: string): T & TemporalAnnotation & { first_start?: string | null } {
+ const r = row as unknown as Record<string, unknown>;
+ const ranges = r.temporal_ranges;
+ const semantics = r.temporal_semantics as 'state' | 'event' | null | undefined;
+ const out = { ...row } as T & TemporalAnnotation & { first_start?: string | null };
+ for (const c of TEMPORAL_COLUMNS) delete (out as unknown as Record<string, unknown>)[c];
+ if (relationSemantics(row.link_type) === 'reference') return Object.assign(out, { status: 'reference' as const });
+ if (ranges == null || !semantics) return Object.assign(out, { status: 'live' as const });
+ const stints = parseMultirange(ranges);
+ const status = statusAt({ semantics, stints, disputed: r.temporal_disputed === true, undatedPast: Number(r.temporal_undated_past ?? 0) }, asOf);
+ return Object.assign(out, {
+ status, stints,
+ recorded_at: iso(r.temporal_recorded_at), retired_at: iso(r.temporal_retired_at),
+ first_start: r.temporal_first_start == null ? null : String(r.temporal_first_start).slice(0, 10),
+ });
+}
+
+/**
+ * Same semantics as `relationshipFilterSql`, applied to an annotated row.
+ * Used where the read is bounded (one page's edges) so callers can also count
+ * what they hid.
+ */
+export function edgeMatchesTemporal(row: TemporalAnnotation & { first_start?: string | null }, opts: EdgeTemporalOpts = {}): boolean {
+ const status = opts.status ?? 'live';
+ if (opts.disabled) return true;
+ if (row.status === 'reference') return status !== 'ended';
+ if (opts.during) {
+ if (!row.stints) return true;
+ return row.stints.some(s => (s.from === null || s.from < opts.during!.until) && (s.until === null || s.until > opts.during!.from));
+ }
+ if (status === 'all') return true;
+ if (status === 'ended') {
+ const day = opts.asOf ?? utcToday();
+ return (row.status === 'ended' || row.status === 'ended_unknown_date') && (row.first_start == null || row.first_start <= day);
+ }
+ if (row.status === 'disputed') return !opts.asOf;
+ return row.status === 'live' || row.status === 'event';
+}
+
+const OFF_VALUES = new Set(['off', 'false', '0', 'no', 'disabled']);
+
+/** `graph.edge_validity` read policy: on unless explicitly turned off; fail-open to on. */
+export async function edgeValidityEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ const value = await engine.getConfig('graph.edge_validity');
+ return !(typeof value === 'string' && OFF_VALUES.has(value.trim().toLowerCase()));
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * Status a relational question asks about: "former employees of X" → ended;
+ * "who worked at X" / "used to" → all (history); present tense → live.
+ */
+export function relationQueryStatus(query: string): EdgeStatusFilter {
+ if (/\b(?:former|ex-|previous(?:ly)?|past|old)\b/i.test(query) && !/\b(?:current(?:ly)?|now)\b/i.test(query)) return 'ended';
+ if (/\b(?:worked|used\s+to|did\s+\S+\s+work|was\s+(?:an?\s+)?(?:employee|advisor|partner)|have\s+(?:ever\s+)?worked|ever)\b/i.test(query)) return 'all';
+ return 'live';
+}
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index 7bf7c5aacb..ce252b670e 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', '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']);
export interface NoticeAudience {
transport: Transport;
diff --git a/src/core/ops/edge-temporal.ts b/src/core/ops/edge-temporal.ts
new file mode 100644
index 0000000000..0b9abb501c
--- /dev/null
+++ b/src/core/ops/edge-temporal.ts
@@ -0,0 +1,68 @@
+/**
+ * Temporal edge policy for graph read operations (get_links, get_backlinks,
+ * traverse_graph). Graph reads return live relationships by default; `status`
+ * ('live' | 'ended' | 'all'), `as_of` (YYYY-MM-DD) and `during` (YYYY,
+ * YYYY-MM, YYYY-MM-DD or FROM..UNTIL) choose history. `graph.edge_validity off`
+ * turns the policy off (every edge, as before). Hidden former relationships are
+ * reported through the `gbrain.temporal` response meta and a model-visible
+ * `former_relationships_hidden` notice so an empty result is never mistaken
+ * for "no relationship ever existed".
+ */
+import type { OperationContext, ParamDef } from './contract.ts';
+import { opError } from './contract.ts';
+import type { Notice } from '../agent-output.ts';
+import type { Link } from '../types.ts';
+import { edgeMatchesTemporal, edgeValidityEnabled, parseTemporalParams, utcToday, type EdgeTemporalOpts, type TemporalAnnotation } from '../link-validity.ts';
+
+export const TEMPORAL_EDGE_PARAMS: Record<'status' | 'as_of' | 'during', ParamDef> = {
+ status: { type: 'string', enum: ['live', 'ended', 'all'], description: "Relationship status: live (default: what is true now, or at as_of), ended (former only), all (history)." },
+ as_of: { type: 'string', description: 'Answer as of this date (YYYY-MM-DD) instead of today.' },
+ during: { type: 'string', description: 'Relationships true at any point in a period: YYYY, YYYY-MM, YYYY-MM-DD or FROM..UNTIL (e.g. 2022, 2021..2023-06).' },
+};
+
+
+/** Validate the temporal params and resolve the effective policy for this call. */
+export async function resolveEdgeTemporal(ctx: OperationContext, p: Record<string, unknown>, opName: string): Promise<EdgeTemporalOpts> {
+ const parsed = parseTemporalParams({ status: p.status, as_of: p.as_of, during: p.during });
+ if (!parsed.ok) {
+ throw opError('invalid_params', `${opName}: ${parsed.message}`,
+ `Pass ${parsed.param} like status: "all", as_of: "2022-06-30" or during: "2022"; omit it for what is true today.`);
+ }
+ const enabled = await edgeValidityEnabled(ctx.engine);
+ return { ...parsed.opts, disabled: !enabled };
+}
+
+/** Keep the rows matching the policy; count what was hidden. Rows must carry a temporal annotation. */
+export function filterTemporalLinks(links: Link[], temporal: EdgeTemporalOpts): { kept: Link[]; hidden: number } {
+ if (temporal.disabled) return { kept: links, hidden: 0 };
+ const kept = links.filter(l => edgeMatchesTemporal(l as Link & TemporalAnnotation, temporal));
+ return { kept, hidden: links.length - kept.length };
+}
+
+/**
+ * Publish what the temporal policy did: response meta always (when the policy
+ * is on), and a notice when it hid relationships, naming the exact call that
+ * shows them.
+ */
+export function reportTemporal(ctx: OperationContext, opName: string, p: Record<string, unknown>, temporal: EdgeTemporalOpts, hidden: number | null): void {
+ if (temporal.disabled) return;
+ const effective = { status: temporal.status ?? 'live', as_of: temporal.asOf ?? utcToday(), ...(temporal.during ? { during: temporal.during } : {}), ...(hidden !== null ? { hidden } : {}) };
+ ctx.emitResponseMeta?.('gbrain.temporal', effective);
+ if (!hidden || (temporal.status ?? 'live') === 'all') return;
+ const args: Record<string, unknown> = {};
+ for (const key of ['slug', 'source_id', 'all_sources', 'depth', 'link_type', 'direction']) if (p[key] !== undefined) args[key] = p[key];
+ args.status = 'all';
+ const notice: Notice = {
+ code: 'former_relationships_hidden',
+ kind: 'info',
+ why: `${hidden} relationship${hidden === 1 ? '' : 's'} that ${hidden === 1 ? 'is' : 'are'} not ${temporal.status === 'ended' ? 'ended' : 'true'} as of ${effective.as_of} ${hidden === 1 ? 'was' : 'were'} left out of this ${opName} result.`,
+ fix: {
+ mcp: { tool: opName, arguments: args },
+ consent: [],
+ actor: 'agent',
+ why: 'Shows every relationship with its status and dates (live, ended, ended_unknown_date); use as_of: YYYY-MM-DD for a past date.',
+ requires_exclusive: false,
+ },
+ };
+ ctx.emitNotice?.(notice);
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 397f4a794e..7cfae0a9e3 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -703,6 +703,7 @@ const context_pack: Operation = {
open_threads: c.open_threads,
edges: c.edges,
backlink_count: c.backlink_count,
+ ...(c.relationship_note ? { relationship_note: c.relationship_note } : {}),
})),
open_threads,
facts: (ctx.remote === false ? rawFacts.slice(0, facts.length) : facts).map((f) => ({
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 7643344824..243746bf20 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -28,6 +28,7 @@ import { PageMissingError } from '../engine-errors.ts';
import { TRAVERSE_PATH_ROW_CAP } from '../engine-constants.ts';
// #4224: flag-gated cross-source identity union for the link read ops.
import { unionLinksAcrossIdentity } from '../entity-identity.ts';
+import { TEMPORAL_EDGE_PARAMS, resolveEdgeTemporal, filterTemporalLinks, reportTemporal } from './edge-temporal.ts';
// #4655: write-time pack vocabulary enforcement for explicit link verbs.
import {
loadActivePackForWriteVocabulary,
@@ -226,14 +227,26 @@ async function readLinkEdges(
): Promise<Link[]> {
const slug = p.slug as string;
const { requested, policy } = await resolveLinkReadScope(ctx, p, opName);
+ const temporal = await resolveEdgeTemporal(ctx, p, opName);
+ const linkType = typeof p.link_type === 'string' && p.link_type ? p.link_type : undefined;
+ // Rows come back annotated with their relationship status; the policy is
+ // applied below so hidden former relationships can be counted and reported.
+ const annotate = temporal.disabled ? undefined : { ...temporal, status: 'all' as const, during: undefined };
+ const finish = (links: Link[]): Link[] => {
+ const typed = linkType ? links.filter(l => l.link_type === linkType) : links;
+ const { kept, hidden } = filterTemporalLinks(typed, temporal);
+ reportTemporal(ctx, opName, p, temporal, hidden);
+ return kept;
+ };
const scopes: PageReadPolicy[] = ctx.remote === false && policy.sourceIds
? policy.sourceIds.map((sourceId) => ({ ...policy, sourceIds: undefined, sourceId }))
: [policy];
const perScope: Link[][] = [];
for (const sourceOpts of scopes) {
+ const readOpts = annotate ? { ...sourceOpts, temporal: annotate } : sourceOpts;
const links = direction === 'out'
- ? await ctx.engine.getLinks(slug, sourceOpts)
- : await ctx.engine.getBacklinks(slug, sourceOpts);
+ ? await ctx.engine.getLinks(slug, readOpts)
+ : await ctx.engine.getBacklinks(slug, readOpts);
// #4224: flag-gated identity union — merge edges from the page's identity
// co-members (entity_identity.union config, default off; pure no-op then).
// Member visibility never widens past the caller's grant. The scalar base
@@ -244,11 +257,12 @@ async function readLinkEdges(
sourceId: sourceOpts.sourceId,
allowedSources: sourceOpts.sourceIds,
excludePrivate: sourceOpts.excludePrivate,
+ ...(annotate ? { temporal: annotate } : {}),
}));
}
if (perScope.length === 1) {
if (perScope[0].length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
- return perScope[0];
+ return finish(perScope[0]);
}
const seen = new Set<string>();
const merged = perScope.flat().filter((l) => {
@@ -258,7 +272,7 @@ async function readLinkEdges(
return true;
});
if (merged.length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
- return merged;
+ return finish(merged);
}
/**
@@ -310,9 +324,11 @@ const get_links: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- 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). Returns relationships that are true today, each with status and dates; pass status: "all" for history, as_of for a past date, during for a period (e.g. where someone worked in 2022). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.',
params: {
slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },
+ link_type: { type: 'string', description: 'Only this link type (e.g. works_at).' },
+ ...TEMPORAL_EDGE_PARAMS,
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
@@ -326,9 +342,11 @@ const get_backlinks: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: 'List links pointing to a page. Use when finding what mentions an entity.',
+ description: 'List links pointing to a page, such as who works at a company. Returns relationships true today; status: "ended" lists former ones, status: "all" history, as_of / during a past date or period.',
params: {
slug: { type: 'string', description: 'Page slug.', required: true },
+ link_type: { type: 'string', description: 'Only this link type (e.g. works_at).' },
+ ...TEMPORAL_EDGE_PARAMS,
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
@@ -383,12 +401,14 @@ const traverse_graph: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: `Walk the link graph from a page. Remote callers get bidirectional paths at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} by default.`,
+ description: `Walk the link graph from a page along relationships that are true today (status: "all" walks history, as_of a past date). Remote callers get bidirectional paths at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} by default.`,
params: {
slug: { type: 'string', description: 'Start page slug.', required: true },
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'] },
+ status: TEMPORAL_EDGE_PARAMS.status,
+ as_of: TEMPORAL_EDGE_PARAMS.as_of,
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
@@ -420,7 +440,10 @@ const traverse_graph: Operation = {
// #5827: the walk scopes every visited page, so a federated `sourceIds[]`
// (no-grant remote, or a trusted local unqualified read) walks the
// federated set in one query; nodes and edges carry their source ids.
- const { policy: scope } = await resolveLinkReadScope(ctx, p, 'traverse_graph');
+ const { policy: readScope } = await resolveLinkReadScope(ctx, p, 'traverse_graph');
+ const temporal = await resolveEdgeTemporal(ctx, p, 'traverse_graph');
+ const scope = temporal.disabled ? readScope : { ...readScope, temporal };
+ reportTemporal(ctx, 'traverse_graph', p, temporal, null);
// Backward compat: trusted local no-filter callers keep the legacy
// GraphNode[] shape used by `gbrain graph`. Remote MCP callers need the
// natural no-filter invocation to surface inbound-only typed edges too,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 138e0e292e..8491288314 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1855,11 +1855,11 @@ export class PGLiteEngine implements BrainEngine {
return linksImpl.removeLink(this.engineSql, from, to, linkType, linkSource, opts);
}
- async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+ async getLinks(slug: string, opts?: import("./link-validity.ts").LinkReadScope): Promise<Link[]> {
return linksImpl.getLinks(scopedRead(this.engineSql), slug, opts);
}
- async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+ async getBacklinks(slug: string, opts?: import("./link-validity.ts").LinkReadScope): Promise<Link[]> {
return plannerRead(this, this._pageTransaction, () => linksImpl.getBacklinks(scopedRead(this.engineSql), slug, opts));
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index dcf4cff626..9fe8737944 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1595,11 +1595,11 @@ export class PostgresEngine implements BrainEngine {
return linksImpl.removeLink(this.engineSql, from, to, linkType, linkSource, opts);
}
- async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+ async getLinks(slug: string, opts?: import("./link-validity.ts").LinkReadScope): Promise<Link[]> {
return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => linksImpl.getLinks(scopedRead(this.engineSqlOn(tx)), slug, opts));
}
- async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {
+ async getBacklinks(slug: string, opts?: import("./link-validity.ts").LinkReadScope): Promise<Link[]> {
return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => linksImpl.getBacklinks(scopedRead(this.engineSqlOn(tx)), slug, opts));
}
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 58d7dc58d7..eb8621fa34 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -2,6 +2,7 @@ import type { PageReadScope, PageReadPolicy, AdjacencyRow, RelationalFanoutOpts,
import { unverifiedExtractionFragment } from '../extraction-review.ts';
import { currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
+import { relationshipFilterSql } from '../link-validity.ts';
/** Narrow query dependency shared by both engines. */
export type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
@@ -35,6 +36,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
typeFilter = `AND l.link_type = ANY($${params.length}::text[])`;
}
const mentionsFilter = opts?.includeMentions ? '' : `AND l.link_source IS DISTINCT FROM 'mentions'`;
+ const temporalFilter = opts?.temporal ? `AND ${relationshipFilterSql('l', { ...opts.temporal, excludePrivate: opts.excludePrivate })}` : '';
const recurStep = direction === 'out'
? 'JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id'
: direction === 'in'
@@ -53,7 +55,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
FROM walk w ${recurStep}
WHERE w.depth < $2 AND NOT (p2.id = ANY(w.visited))
AND p2.source_id = w.seed_source AND p2.deleted_at IS NULL
- AND ${step} AND ${origin} ${mentionsFilter} ${typeFilter}
+ AND ${step} AND ${origin} ${mentionsFilter} ${typeFilter} ${temporalFilter}
)
SELECT n.source_id, n.slug, MIN(n.depth) AS hop,
COUNT(DISTINCT n.last_link_type) AS edge_count,
diff --git a/src/core/search/relational-intent.ts b/src/core/search/relational-intent.ts
index f6944e78c1..8cb2333468 100644
--- a/src/core/search/relational-intent.ts
+++ b/src/core/search/relational-intent.ts
@@ -30,6 +30,8 @@
* Tested in test/relational-intent.test.ts.
*/
+import { relationQueryStatus, type EdgeStatusFilter } from '../link-validity.ts';
+
export type RelationalKind = 'who_rel' | 'who_at' | 'connects' | 'intro';
export type RelationDirection = 'in' | 'out' | 'both';
@@ -44,6 +46,8 @@ export interface RelationalQuery {
direction: RelationDirection;
/** The matched relation phrase, for telemetry / --explain. */
relationPhrase: string;
+ /** Which relationships the question is about: live (now), ended (former), all (history). */
+ edgeStatus: EdgeStatusFilter;
}
/** Schema-pack vocab extension (D2=B). */
@@ -346,12 +350,12 @@ export function parseRelationalQuery(query: string, vocab?: RelationVocab): Rela
const a = cleanSeed(m[1] ?? '');
const b = cleanSeed(m[2] ?? '');
if (!validSeed(a) || !validSeed(b)) continue;
- return { kind: p.kind, seeds: [a, b], linkTypes: p.linkTypes, direction: p.direction, relationPhrase: m[0].trim() };
+ return { kind: p.kind, seeds: [a, b], linkTypes: p.linkTypes, direction: p.direction, relationPhrase: m[0].trim(), edgeStatus: relationQueryStatus(query) };
}
const seed = cleanSeed(m[1] ?? '');
if (!validSeed(seed)) continue;
- return { kind: p.kind, seeds: [seed], linkTypes: p.linkTypes, direction: p.direction, relationPhrase: m[0].trim() };
+ return { kind: p.kind, seeds: [seed], linkTypes: p.linkTypes, direction: p.direction, relationPhrase: m[0].trim(), edgeStatus: relationQueryStatus(query) };
}
return null;
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 3ed2a317ec..032f6c606f 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -34,6 +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 { stampEvidence, type EvidenceOpts } from './evidence.ts';
export interface RelationalArmOpts extends PageReadPolicy {
@@ -318,7 +319,9 @@ export async function buildRelationalArm(
try {
const sources = await scopeSources(engine, opts);
+ const temporal = await edgeValidityEnabled(engine) ? { status: parsed.edgeStatus } : undefined;
const fanoutOpts = {
+ temporal,
sourceId: opts.sourceId,
sourceIds: opts.sourceIds,
excludePrivate: opts.excludePrivate,
diff --git a/src/core/types.ts b/src/core/types.ts
index 652952789f..a944875090 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1518,6 +1518,7 @@ export interface RelationalFanoutRow {
/** Options for BrainEngine.relationalFanout. */
export interface RelationalFanoutOpts extends PageReadPolicy {
+ temporal?: import('./link-validity.ts').EdgeTemporalOpts; // per-hop temporal edge policy; absent = every edge
/** Resolved seed identities; separate from the read grant for edge origins. */
seedRefs?: Array<{ source_id: string; slug: string }>;
/** Edge types to traverse; null/empty = type-agnostic. */
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1cd8c68b92..f3c09c5c0c 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -543,11 +543,16 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
direction: { type: 'string', enum: ['out', 'in'] },
slug: { type: 'string' },
context: { type: ['string', 'null'] },
+ // Temporal typed edges — ADDITIVE OPTIONAL (frozen-v1 legal).
+ status: { type: 'string' },
+ since: { type: ['string', 'null'] },
+ until: { type: ['string', 'null'] },
},
},
},
backlink_count: { type: 'integer' },
active_fact_count: { type: 'integer' },
+ relationship_note: { type: 'string' },
},
},
suggestions: {
@@ -653,10 +658,14 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
direction: { type: 'string', enum: ['out', 'in'] },
slug: { type: 'string' },
context: { type: ['string', 'null'] },
+ status: { type: 'string' },
+ since: { type: ['string', 'null'] },
+ until: { type: ['string', 'null'] },
},
},
},
backlink_count: { type: 'integer' },
+ relationship_note: { type: 'string' },
},
},
},
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index a37a9abdb3..215d582795 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -20,12 +20,13 @@
* facts respect visibility for remote callers (world-only).
*/
+import { annotateTemporalRow, relationSemantics, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type TemporalAnnotation } from '../link-validity.ts';
import type { BrainEngine, FactRow } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { slugify } from '../entities/resolve.ts';
import { safeSynopsis } from '../context/retrieval-reflex.ts';
import { stampEvidence, markKeywordHits } from '../search/evidence.ts';
-import type { SearchResult } from '../types.ts';
+import type { Link, SearchResult } from '../types.ts';
const EDGE_CAP = 10;
const OPEN_THREADS_CAP = 3;
@@ -39,6 +40,11 @@ export interface EntityCardEdge {
direction: 'out' | 'in';
slug: string;
context: string | null;
+ /** Relationship status today: live, ended, ended_unknown_date, event, reference, … */
+ status?: string;
+ /** Latest stint bounds (YYYY-MM-DD) when the relationship has dated evidence. */
+ since?: string | null;
+ until?: string | null;
}
export interface EntityOpenThread {
@@ -75,6 +81,13 @@ export interface EntityCard {
backlink_count: number;
/** Exact active-fact count (indexed COUNT, not payload length); visibility-filtered for remote. */
active_fact_count: number;
+ /**
+ * Current and ended state relationships of this entity, rendered for agents
+ * ("now: works_at widget-co (since 2025-03-01); ended: works_at acme-example
+ * (2025-03-01)"), plus a stale-summary warning when the summary still names
+ * a relationship that ended. Absent when there is nothing to say.
+ */
+ relationship_note?: string;
}
export interface EntitySuggestion {
@@ -268,18 +281,20 @@ async function assembleCard(
)
.then(rs => rs.map(r => r.alias_norm))
.catch(() => [] as string[]),
- engine.getLinks(pageSlug, { sourceId, excludePrivate }).catch(() => []),
+ engine.getLinks(pageSlug, { sourceId, excludePrivate, temporal: { status: 'all' } }).catch(() => []),
engine
.executeRaw<{ from_slug: string; link_type: string; context: string | null }>(
- `SELECT f.slug AS from_slug, l.link_type, l.context
+ `SELECT f.slug AS from_slug, l.link_type, l.context${TEMPORAL_LINK_SELECT_SQL}
FROM links l
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
+ ${temporalLinkJoinSql('l', excludePrivate)}
WHERE t.slug = $1 AND t.source_id = $2 AND f.source_id = $2 AND f.deleted_at IS NULL
AND COALESCE(l.link_source, '') <> 'mentions'${inboundPrivacy}`,
[pageSlug, sourceId],
)
- .catch(() => [] as Array<{ from_slug: string; link_type: string; context: string | null }>),
+ .then(rs => rs.map(r => annotateTemporalRow(r)))
+ .catch(() => [] as Array<{ from_slug: string; link_type: string; context: string | null } & TemporalAnnotation>),
engine
.executeRaw<{ n: string | number }>(
`SELECT COUNT(*) AS n
@@ -317,18 +332,26 @@ async function assembleCard(
.catch(() => null),
]);
- const edges: EntityCardEdge[] = [];
- for (const l of outLinks) {
- if (l.link_source === 'mentions') continue;
- edges.push({ type: l.link_type, direction: 'out', slug: l.to_slug, context: l.context || null });
- if (edges.length >= EDGE_CAP) break;
- }
- if (edges.length < EDGE_CAP) {
- for (const l of inEdges) {
- edges.push({ type: l.link_type, direction: 'in', slug: l.from_slug, context: l.context || null });
- if (edges.length >= EDGE_CAP) break;
- }
- }
+ // Live relationships first so ended ones never push a current edge past the cap.
+ const rank = (status?: string) => (status === 'live' || status === 'disputed' ? 0 : status === 'event' || status === 'reference' || !status ? 1 : 2);
+ const edgeOf = (l: { link_type: string; context?: string | null } & Partial<TemporalAnnotation>, direction: 'out' | 'in', slug: string): EntityCardEdge => {
+ const last = l.stints?.[l.stints.length - 1];
+ return {
+ type: l.link_type, direction, slug, context: l.context || null,
+ ...(l.status ? { status: l.status } : {}),
+ ...(last ? { since: last.from, until: last.until } : {}),
+ };
+ };
+ const outCandidates = (outLinks as Array<Link & Partial<TemporalAnnotation>>)
+ .filter(l => l.link_source !== 'mentions')
+ .map(l => edgeOf(l, 'out', l.to_slug));
+ const inCandidates = inEdges.map(l => edgeOf(l as typeof l & Partial<TemporalAnnotation>, 'in', l.from_slug));
+ const edges: EntityCardEdge[] = [
+ ...[...outCandidates].sort((a, b) => rank(a.status) - rank(b.status)),
+ ...[...inCandidates].sort((a, b) => rank(a.status) - rank(b.status)),
+ ].slice(0, EDGE_CAP);
+ const summary = safeSynopsis(row, { keepVisibility: remote ? ['world'] : ['private', 'world'] });
+ const relationshipNote = await buildRelationshipNote(engine, sourceId, summary, outCandidates).catch(() => undefined);
// Open threads (best-effort v1): open-loop rows first (v0.47 — richest:
// direction, due, loop_id), then active commitment facts NOT already
@@ -402,7 +425,7 @@ async function assembleCard(
aka,
// v0.45.7: summary widens in lockstep with the card's fact visibility —
// remote (world-only) keeps ['world']; a local include_private card widens.
- summary: safeSynopsis(row, { keepVisibility: remote ? ['world'] : ['private', 'world'] }),
+ summary,
last_touched: {
updated_at: toIso(row.updated_at),
last_retrieved_at: toIso(row.last_retrieved_at),
@@ -412,7 +435,42 @@ async function assembleCard(
edges,
backlink_count: backlinkCount,
active_fact_count: activeFactCount ?? facts.length,
+ ...(relationshipNote ? { relationship_note: relationshipNote } : {}),
+ };
+}
+
+const NOTE_ENDED_CAP = 3;
+
+/**
+ * "now: works_at widget-co (since 2025-03-01); ended: works_at acme-example
+ * (2025-03-01)". Ended relationships the summary still names always appear
+ * (with a stale-summary warning); other ended ones are capped at the latest
+ * three. Only state relations (works_at, advises, …) take part.
+ */
+async function buildRelationshipNote(engine: BrainEngine, sourceId: string, summary: string, edges: EntityCardEdge[]): Promise<string | undefined> {
+ const state = edges.filter(e => relationSemantics(e.type) === 'state' && e.status);
+ if (state.length === 0) return undefined;
+ const live = state.filter(e => e.status === 'live' || e.status === 'disputed');
+ const ended = state.filter(e => e.status === 'ended' || e.status === 'ended_unknown_date');
+ if (ended.length === 0) return undefined;
+ const titles = new Map((await engine.executeRaw<{ slug: string; title: string | null }>(
+ `SELECT slug, title FROM pages WHERE source_id = $1 AND slug = ANY($2::text[])`, [sourceId, ended.map(e => e.slug)])).map(r => [r.slug, r.title ?? '']));
+ const lower = summary.toLowerCase();
+ const named = (e: EntityCardEdge) => {
+ const title = (titles.get(e.slug) ?? '').trim().toLowerCase();
+ const base = e.slug.split('/').pop()!.replace(/-/g, ' ');
+ return (title.length >= 3 && lower.includes(title)) || lower.includes(base);
};
+ const stale = ended.filter(named);
+ const others = ended.filter(e => !named(e)).sort((a, b) => (b.until ?? '').localeCompare(a.until ?? '')).slice(0, NOTE_ENDED_CAP);
+ const fmtLive = (e: EntityCardEdge) => `${e.type} ${e.slug.split('/').pop()}${e.since ? ` (since ${e.since})` : ''}`;
+ const fmtEnded = (e: EntityCardEdge) => `${e.type} ${e.slug.split('/').pop()} (${e.until ?? 'date unknown'})`;
+ const parts = [
+ ...(live.length ? [`now: ${live.map(fmtLive).join(', ')}`] : []),
+ `ended: ${[...stale, ...others].map(fmtEnded).join(', ')}`,
+ ];
+ if (stale.length) parts.push(`summary may be stale: it still names ${stale.map(e => e.slug.split('/').pop()).join(', ')}`);
+ return parts.join('; ');
}
/**
diff --git a/test/e2e/link-relationships-postgres.test.ts b/test/e2e/link-relationships-postgres.test.ts
index f5bbcba889..020f17064d 100644
--- a/test/e2e/link-relationships-postgres.test.ts
+++ b/test/e2e/link-relationships-postgres.test.ts
@@ -4,7 +4,7 @@
* datemultirange text, JSONB recordset binding and the graph generation
* sequence through postgres.js.
*/
-import { test } from 'bun:test';
+import { afterAll, beforeAll, test } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { defineLinkRelationshipTests } from '../helpers/link-temporal-scenario.ts';
@@ -13,11 +13,13 @@ const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
test.skip('link relationships Postgres scenario skipped (DATABASE_URL unset)', () => {});
} else {
- defineLinkRelationshipTests('postgres', async () => {
- const eng = new PostgresEngine();
+ let engine: PostgresEngine;
+ beforeAll(async () => {
+ engine = new PostgresEngine();
assertSafeE2eDatabaseUrl(databaseUrl);
- await eng.connect({ database_url: databaseUrl });
- await eng.initSchema();
- return eng;
- }, eng => eng.disconnect(), 'lrtpg');
+ await engine.connect({ database_url: databaseUrl });
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+ defineLinkRelationshipTests('postgres', () => engine, 'lrtpg');
}
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index 62a5a4fe36..b4a4de7c3a 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -89,7 +89,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE t.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "bbb2209d09e9db7b7bfa4d3a99b2e6aef24b44fb9c8545f0f58aa07b320dd2f1"
+ "textSha256": "d2c8035b5052ef8e240b6ce187fa4d7cb115f7bdfa8715f5eeca192d1350a32b"
}
],
"excludePrivate": [
@@ -99,7 +99,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE t.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))))) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY l.id",
- "textSha256": "b2675f9fab43452f1bf53a39bfd4e4842f17657497467d24b8e7e29a93d3d1f1"
+ "textSha256": "78fff14c59664591e3d70908a3612abc70b413b6feeefe7ebdbb0efe076493c7"
}
],
"sourceId": [
@@ -110,7 +110,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE t.slug = $1 AND t.source_id = $2 AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "66b9e4e2d79b3236efe05c234089d86f91c4286d9e1f7afbd35d626a18aae16c"
+ "textSha256": "08ce8b478b512d421cbb33409fb939a72f1f360a6b824bdc686131d7b95abe2d"
}
],
"sourceIds": [
@@ -123,7 +123,7 @@
"array<string>"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($1::text[]) WHERE t.slug = $2 AND t.source_id = ANY($3::text[]) AND f.source_id = ANY($4::text[]) AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "e77d0bcedf2207f2702287d9f43d909f29ffd9fdb959ea0ae96127417196ce27"
+ "textSha256": "46101181416dccde2f2913fc226973d2c93d96a450f9a4dd76d58e0bf0d2e25f"
}
]
},
@@ -135,7 +135,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "e47cd60fa4248491a041a1539bb444bb874f353c5c17a8706d4670e0ebf3b869"
+ "textSha256": "96da37ef54a5916de3c8f917e7b4e24b307ed856470a0b66e55d7a824267c530"
}
],
"excludePrivate": [
@@ -145,7 +145,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))))) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY l.id",
- "textSha256": "c636b80ef601623a19a7fa61d485a30ae7a2b4e3fbbaa70889e2bd303dd40da5"
+ "textSha256": "c18718df5c7bf72128b52e597830831f082b85cf33947d073a9ff1ec7bd574eb"
}
],
"sourceId": [
@@ -156,7 +156,7 @@
"string"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND f.source_id = $2 AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "047a5dbd950079e6eabb438e6bacdb6e7083d107cbb4c455d4262a94e862cc8e"
+ "textSha256": "61df3b9ef95b784698a9ab8bd34bfe1e32f99ea818308cca13b4fc27d30d6bc6"
}
],
"sourceIds": [
@@ -169,7 +169,7 @@
"array<string>"
],
"sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($1::text[]) WHERE f.slug = $2 AND f.source_id = ANY($3::text[]) AND t.source_id = ANY($4::text[]) AND f.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY l.id",
- "textSha256": "f506c27e60abdc7fd8a0a42fe2452ad356672d9ab3704e9695222a8ff25485fe"
+ "textSha256": "91f3265342073e2c19e896963efdcc0222d60df69364902239bf08367fb4f0da"
}
]
},
@@ -429,7 +429,7 @@
"number"
],
"sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $3) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "668c5de92d0904e614566a97f482304b5fc3a6fcb27c5f6eed10993b13ee7e55"
+ "textSha256": "5c336c4483dab0e5893bfff19cb3968108a3312402aef13178d2d5829ab99acb"
}
],
"excludePrivate": [
@@ -441,7 +441,7 @@
"number"
],
"sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND (COALESCE(p3.frontmatter->>'visibility', CASE WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p3.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p3.source_id AND derived_origin.slug = p3.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p3.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p3.type = 'event' AND p3.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p3.source_id AND chronicle_origin.slug = p3.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p3.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p3.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') = 'array' THEN p3.frontmatter->'derived_from' ELSE jsonb_build_array(p3.frontmatter->'derived_from') END) AS declared(slug))))) AND (l2.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l2.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $3) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "4e31963ee44b7309d252388f3cb9042ca69c6e06208e2c81c54265791edd8ffb"
+ "textSha256": "429fcf8d1218102a88f64e14cd3c8a27591e582e2de0b9b36ee43b37884ea154"
}
],
"frontierCap": [
@@ -454,7 +454,7 @@
"number"
],
"sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL (SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL ORDER BY p2.slug ASC, p2.id ASC LIMIT $3) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $4) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "4a15dff50622e72c2c64563c116f1b59b02c0b64eee8d10022ae6febbc1288a1"
+ "textSha256": "ff8d91623f7d0deae58a6866d514eaf62a5ca64e1f456d7d4cb07052a23685c7"
}
],
"sourceId": [
@@ -468,8 +468,8 @@
"string",
"number"
],
- "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = $2 UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $3 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND p2.source_id = $4 ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND p3.source_id = $5), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $6) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "f527f0c25594e2baf9d848c3e4d5a5819f8490a6b03208086aa4c88343981a2a"
+ "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = $2 UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $3 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND p2.source_id = $4 ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND p3.source_id = $5 ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $6) capped) g ORDER BY g.depth, g.slug, g.source_id",
+ "textSha256": "af76f0948aa5f8f01f4303f9f8e2c24abb3f950a50d0a6b7f56a8c3d0f699dec"
}
],
"sourceIds": [
@@ -483,8 +483,8 @@
"array<string>",
"number"
],
- "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = ANY($2::text[]) UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $3 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND p2.source_id = ANY($4::text[]) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND p3.source_id = ANY($5::text[])), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $6) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "0691360c6f5d9b85c81372113ee3120f69617e34b4a980b9bbd8b77ad91c3b84"
+ "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = ANY($2::text[]) UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $3 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND p2.source_id = ANY($4::text[]) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND p3.source_id = ANY($5::text[]) ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $6) capped) g ORDER BY g.depth, g.slug, g.source_id",
+ "textSha256": "733ad24d082dbbf77b97f87117b52a6da365438c1dbca764f3486f5564916eb2"
}
]
},
@@ -505,7 +505,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, p.slug, p.source_id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL SELECT p2.id, p2.slug, p2.source_id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth + 1 < $2 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND ($3 OR l.link_type = $4) ), capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT $5), nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $6 AS walk_truncated, w.id as from_id, w.slug as from_slug, w.source_id as from_source_id, p2.id as to_id, p2.slug as to_slug, p2.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth < $7 AND p2.deleted_at IS NULL AND ($8 OR l.link_type = $9) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $10",
- "textSha256": "e85a15fac4e1db7f3451b223ff4f2b68341957636a2c74f142600fd36771edd2"
+ "textSha256": "c3442529a0698fb3a666ab6d105ba5fae3cfa885245264bef12eb2d98867b114"
}
]
},
@@ -526,7 +526,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL SELECT p2.id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END WHERE w.depth + 1 < $2 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND ($3 OR l.link_type = $4) ), capped AS (SELECT id, depth FROM walk LIMIT $5), nodes AS (SELECT DISTINCT id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $6 AS walk_truncated, pf.id as from_id, pf.slug as from_slug, pf.source_id as from_source_id, pt.id as to_id, pt.slug as to_slug, pt.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages pf ON pf.id = l.from_page_id JOIN pages pt ON pt.id = l.to_page_id WHERE w.depth < $7 AND pf.deleted_at IS NULL AND pt.deleted_at IS NULL AND ($8 OR l.link_type = $9) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $10",
- "textSha256": "6ebe2010f651c3a10e2c52680122ad0e38b9cdf69246cd8e1fd1b0e5e0f9ea85"
+ "textSha256": "93cae18d1d0db70209c65f154fcc60e9b8858a4318c2fd8fc5c6c0da5271ca96"
}
],
"both+sourceIds+excludePrivate": [
@@ -549,7 +549,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.source_id = ANY($2::text[]) UNION ALL SELECT p2.id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END WHERE w.depth + 1 < $3 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) AND ($4 OR l.link_type = $5) AND p2.source_id = ANY($6::text[]) ), capped AS (SELECT id, depth FROM walk LIMIT $7), nodes AS (SELECT DISTINCT id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $8 AS walk_truncated, pf.id as from_id, pf.slug as from_slug, pf.source_id as from_source_id, pt.id as to_id, pt.slug as to_slug, pt.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages pf ON pf.id = l.from_page_id JOIN pages pt ON pt.id = l.to_page_id WHERE w.depth < $9 AND pf.deleted_at IS NULL AND (COALESCE(pf.frontmatter->>'visibility', CASE WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pf.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pf.source_id AND derived_origin.slug = pf.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pf.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pf.type = 'event' AND pf.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pf.source_id AND chronicle_origin.slug = pf.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pf.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pf.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') = 'array' THEN pf.frontmatter->'derived_from' ELSE jsonb_build_array(pf.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) AND pt.deleted_at IS NULL AND (COALESCE(pt.frontmatter->>'visibility', CASE WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pt.source_id AND derived_origin.slug = pt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pt.type = 'event' AND pt.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pt.source_id AND chronicle_origin.slug = pt.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pt.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pt.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') = 'array' THEN pt.frontmatter->'derived_from' ELSE jsonb_build_array(pt.frontmatter->'derived_from') END) AS declared(slug))))) AND ($10 OR l.link_type = $11) AND pf.source_id = ANY($12::text[]) AND pt.source_id = ANY($13::text[]) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $14",
- "textSha256": "a64eb869b6d5b1c54a74bf9330f6bde2921a916361888af77ab05f9ee3fb34de"
+ "textSha256": "85acaff908f93f5c9f65ac8ca9f4027aaba1d3e01ca61fa5308b4d810301642e"
}
],
"default": [
@@ -568,7 +568,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, p.slug, p.source_id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL SELECT p2.id, p2.slug, p2.source_id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth + 1 < $2 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND ($3 OR l.link_type = $4) ), capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT $5), nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $6 AS walk_truncated, w.id as from_id, w.slug as from_slug, w.source_id as from_source_id, p2.id as to_id, p2.slug as to_slug, p2.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth < $7 AND p2.deleted_at IS NULL AND ($8 OR l.link_type = $9) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $10",
- "textSha256": "e85a15fac4e1db7f3451b223ff4f2b68341957636a2c74f142600fd36771edd2"
+ "textSha256": "c3442529a0698fb3a666ab6d105ba5fae3cfa885245264bef12eb2d98867b114"
}
],
"in": [
@@ -587,7 +587,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, p.slug, p.source_id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL UNION ALL SELECT p2.id, p2.slug, p2.source_id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON l.to_page_id = w.id JOIN pages p2 ON p2.id = l.from_page_id WHERE w.depth + 1 < $2 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND ($3 OR l.link_type = $4) ), capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT $5), nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $6 AS walk_truncated, p2.id as from_id, p2.slug as from_slug, p2.source_id as from_source_id, w.id as to_id, w.slug as to_slug, w.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON l.to_page_id = w.id JOIN pages p2 ON p2.id = l.from_page_id WHERE w.depth < $7 AND p2.deleted_at IS NULL AND ($8 OR l.link_type = $9) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $10",
- "textSha256": "42ebd2f252ca54faaa92aee69cb1695930b827a4517500528c616991e26c2705"
+ "textSha256": "4756f322dc94d858cd282090d9d00008cd68876d2694bda4f6cb422dc371778f"
}
],
"out+sourceId+linkType": [
@@ -609,7 +609,7 @@
"number"
],
"sql": "WITH RECURSIVE walk AS ( SELECT p.id, p.slug, p.source_id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = $2 UNION ALL SELECT p2.id, p2.slug, p2.source_id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth + 1 < $3 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND ($4 OR l.link_type = $5) AND p2.source_id = $6 ), capped AS (SELECT id, slug, source_id, depth FROM walk LIMIT $7), nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $8 AS walk_truncated, w.id as from_id, w.slug as from_slug, w.source_id as from_source_id, p2.id as to_id, p2.slug as to_slug, p2.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id WHERE w.depth < $9 AND p2.deleted_at IS NULL AND ($10 OR l.link_type = $11) AND p2.source_id = $12 ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $13",
- "textSha256": "687df7c9ed8c269f0340ef55ef0b34a7306388ef4937c3933066e27572fce591"
+ "textSha256": "0782a48ffe3c9e19c3ec03b24e4c62d515574b0e27df687bee2c7d12147d4bb1"
}
]
}
diff --git a/test/helpers/link-temporal-scenario.ts b/test/helpers/link-temporal-scenario.ts
index 63a76841a9..7cb882c533 100644
--- a/test/helpers/link-temporal-scenario.ts
+++ b/test/helpers/link-temporal-scenario.ts
@@ -5,10 +5,11 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import type { BrainEngine } from '../../src/core/engine.ts';
-import { refreshRelationships, relationshipKeysForPages, staleRelationshipKeys } from '../../src/core/engine-sql/link-relationships.ts';
+import { refreshRelationships, relationshipKeysForPages, staleRelationshipKeys } from '../../src/core/link-relationships.ts';
import { relationshipFilterSql, parseMultirange } from '../../src/core/link-validity.ts';
-export function defineLinkRelationshipTests(label: string, open: () => Promise<BrainEngine>, close: (e: BrainEngine) => Promise<void>, tag = 'lrt') {
+/** The caller owns the engine lifecycle (beforeAll connect / afterAll disconnect); `engineOf` returns it. */
+export function defineLinkRelationshipTests(label: string, engineOf: () => BrainEngine, tag = 'lrt') {
let eng: BrainEngine;
const ids: Record<string, number> = {};
const alice = `people/${tag}-alice-example`;
@@ -40,14 +41,13 @@ export function defineLinkRelationshipTests(label: string, open: () => Promise<B
describe(`link_relationships refresh (${label})`, () => {
beforeAll(async () => {
- eng = await open();
+ eng = engineOf();
await page(alice, 'person');
await page(notes, 'note', { visibility: 'private' });
for (const c of [acme, widget, fund]) await page(c, 'company');
});
afterAll(async () => {
await eng.executeRaw(`DELETE FROM pages WHERE slug LIKE $1`, [`%/${tag}-%`]);
- await close(eng);
});
test('schema objects exist after initSchema', async () => {
diff --git a/test/link-relationships.test.ts b/test/link-relationships.test.ts
index d6d2b037e9..aa7bc14e3f 100644
--- a/test/link-relationships.test.ts
+++ b/test/link-relationships.test.ts
@@ -1,14 +1,18 @@
/**
* Temporal typed edges — relationship state refresh and the liveness filter on
- * a real PGLite brain (schema + migration + engine-sql domain). The Postgres
- * twin is test/e2e/link-relationships-postgres.test.ts.
+ * a real PGLite brain (schema + migration + shared refresh). The Postgres twin
+ * is test/e2e/link-relationships-postgres.test.ts.
*/
+import { afterAll, beforeAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { defineLinkRelationshipTests } from './helpers/link-temporal-scenario.ts';
-defineLinkRelationshipTests('pglite', async () => {
- const eng = new PGLiteEngine();
- await eng.connect({});
- await eng.initSchema();
- return eng;
-}, eng => eng.disconnect());
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+
+defineLinkRelationshipTests('pglite', () => engine);
diff --git a/test/link-temporal-reads.test.ts b/test/link-temporal-reads.test.ts
new file mode 100644
index 0000000000..e1b706275e
--- /dev/null
+++ b/test/link-temporal-reads.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Temporal typed edges — read surfaces: get_links / get_backlinks /
+ * traverse_graph status, as_of and during params, the hidden-relationships
+ * notice + meta, entity cards (all edges with status, relationship note,
+ * rendered context_pack line), the relational search arm and the
+ * graph.edge_validity off switch.
+ */
+import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+import { renderCardLine } from '../src/core/context/turn-context.ts';
+import { buildRelationalArm } from '../src/core/search/relational-recall.ts';
+
+setDefaultTimeout(60_000);
+let engine: PGLiteEngine;
+const notices: Notice[] = [];
+const meta: Record<string, unknown> = {};
+
+const ctx = (remote = false): OperationContext => ({
+ engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false, remote, sourceId: 'default',
+ emitNotice: (n: Notice) => { notices.push(n); },
+ emitResponseMeta: (k: string, v: unknown) => { meta[k] = v; },
+} as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+async function put(slug: string, fm: string, body: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op('put_page').handler(ctx(), { slug, ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: `---\n${fm}\n---\n\n${body}` });
+}
+const targets = (rows: unknown) => (rows as Array<{ to_slug: string }>).map(r => r.to_slug).sort();
+const sources = (rows: unknown) => (rows as Array<{ from_slug: string }>).map(r => r.from_slug).sort();
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); resetGateway();
+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');
+ await put('companies/widget-co', 'type: company\ntitle: Widget', 'Another company.');
+ await put('people/alice-example', 'type: person\ntitle: Alice', [
+ 'Alice is CTO of [Acme](../companies/acme-example).',
+ '',
+ '## Timeline',
+ '',
+ '- **2019-02-01** | linkedin — Joined [Acme](../companies/acme-example) as CTO',
+ '- **2025-03-01** | linkedin — Left [Acme](../companies/acme-example) to join [Widget](../companies/widget-co)',
+ '- **2025-03-02** | note — works at [Widget](../companies/widget-co)',
+ ].join('\n'));
+});
+afterAll(async () => { await engine.disconnect(); resetGateway(); });
+
+describe('get_links / get_backlinks', () => {
+ test('default returns live relationships with status and dates; notice names the history call', async () => {
+ notices.length = 0;
+ const rows = await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at' }) as Array<Record<string, unknown>>;
+ expect(targets(rows)).toEqual(['companies/widget-co']);
+ expect(rows[0].status).toBe('live');
+ expect(rows[0].stints).toEqual([{ from: '2025-03-01', until: null }]);
+ const notice = notices.find(n => n.code === 'former_relationships_hidden')!;
+ expect(notice.why).toContain('1 relationship');
+ expect(notice.fix?.mcp).toEqual({ tool: 'get_links', arguments: { slug: 'people/alice-example', link_type: 'works_at', status: 'all' } });
+ expect((meta['gbrain.temporal'] as { hidden: number }).hidden).toBe(1);
+ });
+
+ test('status all, ended, as_of and during', async () => {
+ const all = await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', status: 'all' }) as Array<Record<string, unknown>>;
+ expect(targets(all)).toEqual(['companies/acme-example', 'companies/widget-co']);
+ expect(all.find(r => r.to_slug === 'companies/acme-example')!.status).toBe('ended');
+ expect(targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', status: 'ended' }))).toEqual(['companies/acme-example']);
+ expect(targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', as_of: '2022-06-30' }))).toEqual(['companies/acme-example']);
+ expect(targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', during: '2025' }))).toEqual(['companies/acme-example', 'companies/widget-co']);
+ expect(sources(await op('get_backlinks').handler(ctx(), { slug: 'companies/acme-example', link_type: 'works_at' }))).toEqual([]);
+ expect(sources(await op('get_backlinks').handler(ctx(), { slug: 'companies/acme-example', link_type: 'works_at', status: 'ended' }))).toEqual(['people/alice-example']);
+ });
+
+ test('invalid temporal params are rejected with guidance', async () => {
+ await expect(op('get_links').handler(ctx(), { slug: 'people/alice-example', as_of: 'last year' })).rejects.toThrow(/as_of/);
+ await expect(op('get_links').handler(ctx(), { slug: 'people/alice-example', status: 'former' })).rejects.toThrow(/status/);
+ });
+
+ test('graph.edge_validity off returns every edge as before', async () => {
+ await engine.setConfig('graph.edge_validity', 'off');
+ try {
+ expect(targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at' }))).toEqual(['companies/acme-example', 'companies/widget-co']);
+ } finally { await engine.setConfig('graph.edge_validity', 'on'); }
+ });
+});
+
+describe('traverse_graph', () => {
+ test('walks live relationships by default, history with status all, the past with as_of', async () => {
+ const walk = async (p: Record<string, unknown>) => ((await op('traverse_graph').handler(ctx(), { slug: 'people/alice-example', depth: 2, direction: 'out', link_type: 'works_at', ...p })) as Array<{ to_slug: string }>).map(e => e.to_slug).sort();
+ expect(await walk({})).toEqual(['companies/widget-co']);
+ expect(await walk({ status: 'all' })).toEqual(['companies/acme-example', 'companies/widget-co']);
+ expect(await walk({ as_of: '2022-01-01' })).toEqual(['companies/acme-example']);
+ });
+});
+
+describe('entity cards and context_pack text', () => {
+ test('card keeps every edge with status, live first, and carries the relationship note', async () => {
+ const res = await buildEntityCard(engine, 'default', 'people/alice-example', { remote: false });
+ const card = (res as { card: Parameters<typeof renderCardLine>[0] }).card;
+ const works = card.edges.filter(e => e.type === 'works_at');
+ expect(works.map(e => `${e.slug}:${e.status}`)).toEqual(['companies/widget-co:live', 'companies/acme-example:ended']);
+ expect(card.relationship_note).toContain('now: works_at widget-co (since 2025-03-01)');
+ expect(card.relationship_note).toContain('ended: works_at acme-example (2025-03-01)');
+ expect(card.relationship_note).toContain('summary may be stale');
+ expect(renderCardLine(card)).toContain('[now: works_at widget-co');
+ });
+});
+
+describe('relational search arm', () => {
+ test('present tense asks for live relationships; "former" asks for ended ones', async () => {
+ const now = await buildRelationalArm(engine, 'who works at acme-example', {});
+ expect(now.map(r => r.slug)).not.toContain('people/alice-example');
+ const former = await buildRelationalArm(engine, 'who were the former employees of acme-example', {});
+ const worked = await buildRelationalArm(engine, 'who worked at acme-example', {});
+ expect([...former, ...worked].map(r => r.slug)).toContain('people/alice-example');
+ });
+});