Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(graph): breadth-first graph walks, each page and edge once at its shortest depth
garrytan342781ed392c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a960d5fe22..cd00a9e171 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.293.0] - 2026-10-17++**Graph walks are breadth-first: each page and edge comes back once, at its shortest depth, and dense clusters walk in milliseconds.** First step of the graph-traversal plan (HydraDB evaluation, autoplan run-20261017033903).++### What changed++| Situation | Before | Now |+|---|---|---|+| A graph walk (`traverse_graph`, `gbrain graph`, `think` graph context) | enumerated every simple path, capped at 20,000 paths; a page came back once per depth some path reached it, and an edge once per depth | visits each page once, at its shortest distance, and returns each edge once (one hop past its shallower walked endpoint); the pages and edges reached are the same |+| A walk over a densely linked cluster (12-page clique, depth 5) | 55 to 90 ms on Postgres under the path cap (22 s before the cap) | 4 to 9 ms |+| A walk that reaches a large share of the brain | the 20,000-path cap could stop before deeper pages were reached | stops at 20,000 visited pages, shallowest first; the truncation warning names both caps |+| `frontierCap` on `traverseGraph` | an approximate per-iteration cap applied before deduplication | an exact per-layer cap on new pages, in (slug, id) order |++Every per-hop filter is unchanged and still applies at every step: soft delete, `excludePrivate` (page and link-origin privacy), source scope, link type and temporal policy.++### What you need to do++Nothing. Callers that relied on a page appearing at several depths now see it once, at its shortest depth.++### For contributors++- `src/core/engine-sql/links.ts`: one breadth-first CTE (`bfsWalkCtes`) serves `traverseGraph` and `traversePathsDetailed` on both engines.+- `test/traverse-bfs.test.ts` checks the walks against a TypeScript shortest-path reference and the old CTE on seeded random graphs, and checks that a private, out-of-scope, private-origin or soft-deleted page in the middle of a chain stops the walk.+- The dense-hub fixture (`test/helpers/dense-hub.ts`) now has 12 ring links per spoke, so the row-cap tests still overflow 5,000 edges now that each edge is returned once.+- `scripts/bench-graph-walk.ts` times the walks on PGLite and, with `GBRAIN_BENCH_DATABASE_URL`, on Postgres.+- `relationalFanout` still enumerates paths (3 hops at most); moving it to breadth-first changes search ranking and is a follow-up.+## [0.60.292.0] - 2026-10-17**Writes on a brain whose schema is behind are refused up front, `repair ghost-pages` works on a source with a shared skillpack, and large fact batches no longer stall a managed brain.** Fix wave 19 (#6910, #6904, #6898, #6906, plus two test-infra flakes).diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 6ba6b863c7..54d92975ae 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -153,7 +153,7 @@ RRF fusion, multi-query expansion, and 4-layer dedup are engine-agnostic. They o- `tsvector` + `GIN` index for full-text search with `ts_rank` weighting- `pgvector` HNSW index for cosine similarity vector search- `pg_trgm` + `GIN` for fuzzy slug resolution-- Recursive CTEs for graph traversal+- Recursive CTEs for graph traversal (breadth-first, each page visited once)- Trigger-based search_vector (spans pages + timeline_entries)- JSONB for frontmatter with GIN index- Connection pooling via Supabase Supavisor (port 6543)@@ -1146,7 +1146,7 @@ Every method in `BrainEngine`. The full interface. No optional methods, no featu| Keyword search | tsvector + ts_rank | tsvector + ts_rank | Identical (real Postgres) || Vector search | pgvector HNSW | pgvector HNSW | Same operators; bounded fallback/cancellation differs || Fuzzy slug | pg_trgm | pg_trgm | Identical (real Postgres) |-| Graph traversal | Recursive CTE | Recursive CTE | Same SQL |+| Graph traversal | Breadth-first recursive CTE (one row per layer) | Breadth-first recursive CTE (one row per layer) | Same SQL || Transactions | Full ACID | Full ACID | Both support this || JSONB queries | GIN index | GIN index | Identical || Concurrent access | Connection pooling | Single process | PGLite limitation |diff --git a/scripts/bench-graph-walk.ts b/scripts/bench-graph-walk.tsnew file mode 100644index 0000000000..f52ea44937--- /dev/null+++ b/scripts/bench-graph-walk.ts@@ -0,0 +1,133 @@+/**+ * Graph walk benchmark: the breadth-first walks against the simple-path CTE+ * they replaced, on the graphs where the old walk was slow.+ *+ * Graphs (fictional, seeded):+ * clique 12 pages, every page links to every other (the 22 s case)+ * hub test/helpers/dense-hub.ts: 400 spokes around one hub, ring of 12+ * powerlaw 10,000 pages, 60,000 links, targets skewed toward hub pages+ *+ * For each graph, start page and depth it times `traverseGraph` and+ * `traversePathsDetailed` (out and both) through the engine, and the old+ * CTE's walk core (kept inline here, capped at the old 20,000-row+ * TRAVERSE_WALK_ROW_CAP), reporting median and p95 wall time over --runs runs.+ *+ * Usage: bun scripts/bench-graph-walk.ts [--runs 5] [--json]+ * Runs on PGLite. Set GBRAIN_BENCH_DATABASE_URL to a disposable test database+ * to run the same walks on Postgres (its pages and links tables are reset).+ */+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import type { BrainEngine, LinkBatchInput } from '../src/core/engine.ts';+import { seedDenseHub, DENSE_HUB_SLUG } from '../test/helpers/dense-hub.ts';++const args = process.argv.slice(2);+const runs = Number(args[args.indexOf('--runs') + 1]) || 5;+const json = args.includes('--json');++const OLD_WALK = {+ out: `WITH RECURSIVE g AS (+ SELECT p.id, 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, g.depth + 1, g.visited || p2.id FROM 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 count(*) FROM (SELECT DISTINCT id, depth FROM (SELECT id, depth FROM g LIMIT 20000) c) d`,+ both: `WITH RECURSIVE g AS (+ SELECT p.id, 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, g.depth + 1, g.visited || p2.id FROM g JOIN links l ON (l.from_page_id = g.id OR l.to_page_id = g.id)+ JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = g.id THEN l.to_page_id ELSE l.from_page_id END+ WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL)+ SELECT count(*) FROM (SELECT DISTINCT id, depth FROM (SELECT id, depth FROM g LIMIT 20001) c) d`,+};++async function seed(engine: BrainEngine) {+ await seedDenseHub(engine);+ const put = async (slug: string) => engine.putPage(slug, { type: 'note', title: slug, compiled_truth: slug, timeline: '' });+ const clique = (i: number) => `clique/n${String(i).padStart(2, '0')}`;+ for (let i = 0; i < 12; i++) await put(clique(i));+ const links: LinkBatchInput[] = [];+ for (let i = 0; i < 12; i++) for (let j = 0; j < 12; j++) if (i !== j) links.push({ from_slug: clique(i), to_slug: clique(j), link_type: 'mentions', link_source: 'manual' });+ const pl = (i: number) => `pl/p${String(i).padStart(5, '0')}`;+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, frontmatter)+ SELECT 'pl/p' || lpad(g::text, 5, '0'), 'default', 'note', 'p' || g, '', '', '{}'::jsonb FROM generate_series(0, 9999) g`);+ let s = 42;+ const rand = () => {+ s = (s + 0x6d2b79f5) | 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+ await engine.addLinksBatch(links);+ const seen = new Set<string>();+ const from: number[] = [];+ const to: number[] = [];+ while (seen.size < 60000) {+ const f = Math.floor(rand() * 10000);+ const t = Math.floor(Math.pow(rand(), 3) * 10000);+ if (f === t || seen.has(`${f}|${t}`)) continue;+ seen.add(`${f}|${t}`);+ from.push(f);+ to.push(t);+ }+ const ids = new Map((await engine.executeRaw<{ id: number; slug: string }>(`SELECT id, slug FROM pages WHERE slug LIKE 'pl/%'`)).map(r => [r.slug, Number(r.id)]));+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source)+ SELECT f, t, 'works_with', 'manual' FROM unnest($1::int[], $2::int[]) AS e(f, t)`,+ [from.map(i => ids.get(pl(i))), to.map(i => ids.get(pl(i)))]);+ console.error(`[bench] seeded ${links.length + from.length} links`);+ await engine.executeRaw('ANALYZE pages, links');+ return { clique: clique(0), hub: DENSE_HUB_SLUG, powerlaw_hub: pl(0), powerlaw_leaf: pl(7777) };+}++async function time(fn: () => Promise<unknown>) {+ const ms: number[] = [];+ for (let i = 0; i < runs; i++) {+ const t = performance.now();+ await fn();+ ms.push(performance.now() - t);+ }+ ms.sort((a, b) => a - b);+ return { p50: ms[Math.floor(ms.length / 2)], p95: ms[Math.min(ms.length - 1, Math.ceil(ms.length * 0.95) - 1)] };+}++async function bench(name: string, engine: BrainEngine) {+ const starts = await seed(engine);+ const rows: Array<Record<string, unknown>> = [];+ for (const [graph, slug] of Object.entries(starts)) for (const depth of [1, 2, 3, 5]) {+ console.error(`[bench] ${name} ${graph} depth ${depth}`);+ const nodes = await time(() => engine.traverseGraph(slug, depth));+ const out = await time(() => engine.traversePathsDetailed(slug, { depth, direction: 'out' }));+ const both = await time(() => engine.traversePathsDetailed(slug, { depth, direction: 'both' }));+ const oldOut = await time(() => engine.executeRaw(OLD_WALK.out, [slug, depth]));+ const oldBoth = await time(() => engine.executeRaw(OLD_WALK.both, [slug, depth - 1]));+ rows.push({ engine: name, graph, depth, traverseGraph: nodes, pathsOut: out, pathsBoth: both, oldWalkOut: oldOut, oldWalkBoth: oldBoth });+ }+ return rows;+}++const fmt = (t: { p50: number; p95: number }) => `${t.p50.toFixed(1)} / ${t.p95.toFixed(1)}`;+const results: Array<Record<string, unknown>> = [];+const pglite = new PGLiteEngine();+await pglite.connect({});+await pglite.initSchema();+results.push(...await bench('pglite', pglite));+await pglite.disconnect();+const url = process.env.GBRAIN_BENCH_DATABASE_URL;+if (url) {+ const pg = new PostgresEngine();+ await pg.connect({ database_url: url });+ await pg.initSchema();+ await pg.executeRaw('TRUNCATE pages, links RESTART IDENTITY CASCADE');+ results.push(...await bench('postgres', pg));+ await pg.disconnect();+}+if (json) {+ console.log(JSON.stringify(results, null, 2));+} else {+ console.log('median / p95 ms; old = the pre-BFS walk core alone, capped at 20,000 rows');+ console.log('| engine | graph | depth | traverseGraph | paths out | paths both | old walk out | old walk both |');+ console.log('|---|---|---:|---:|---:|---:|---:|---:|');+ for (const r of results) {+ console.log(`| ${r.engine} | ${r.graph} | ${r.depth} | ${fmt(r.traverseGraph as never)} | ${fmt(r.pathsOut as never)} | ${fmt(r.pathsBoth as never)} | ${fmt(r.oldWalkOut as never)} | ${fmt(r.oldWalkBoth as never)} |`);+ }+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c04d96e089..d12b4ede14 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -888,6 +888,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.289.0', text: '`gbrain repair ghost-pages` now retires legacy knowledge ghosts under `skills/` that no live pack skill owns, as a database-only soft delete, and lists ghosts on files the adopted skillpack owns apart as `ghost_skill_pack_member` with a restore step; a per-item caller refusal is recorded `refused` instead of aborting the run.' },{ since: '0.60.289.0', text: 'Managed fact extraction that gives one entity more than 50 facts in one batch now publishes them as parts of at most 50, each its own extract_facts request published in queue order, so one publication no longer holds the brain-wide write counters for every fact. Each part\'s receipt says so (publication: partial or final_part, part.index/of, part.deferred_facts, part.follow_up); the batch\'s completion receipt still counts the whole group. Conversation entity hints never name a retired alias page (canonical: false, superseded_by/merged_into, alias or redirect status): its canonical page is hinted instead, or nothing when the redirect cannot be followed.' },{ since: '0.60.289.0', text: 'OpenClaw context engine: when a module that assemble() loads lazily fails to load (for example, a host runtime that rejects Bun-only imports), it now prints one stderr line per module, `[gbrain] context engine: failed to load <module> (<error code>); brain context is degraded`, instead of failing silently. Context assembly still fails open, and nothing else changes.' },+ { since: '0.60.293.0', text: 'Graph walks (`traverse_graph`, `gbrain graph`, the graph context `think` gathers) are now breadth-first: each page and each edge comes back once, at its shortest depth from the start page, instead of once per depth some path reached it. The pages and edges reached are unchanged; only repeated deeper copies are gone, and a walk over a densely linked cluster that took seconds now takes milliseconds. A walk now stops at 20,000 visited pages (the old cap counted paths), and the truncation warning names both caps.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-constants.ts b/src/core/engine-constants.tsindex da6056cae0..1d88bca6cf 100644--- a/src/core/engine-constants.ts+++ b/src/core/engine-constants.ts@@ -26,23 +26,23 @@ export const DELETE_BATCH_SIZE = 500;/*** Total-row cap on `traversePaths` / `traversePathsDetailed` (both engines).- * The edge walk is a path-enumerating recursive CTE whose `both` branch- * fans out combinatorially on an entity hub (10^2-10^3 edges at depth 5 is- * millions of rows), and the in-memory edge dedup only ran AFTER the DB had- * materialized every row. The final SELECT is bounded to `CAP + 1` rows- * (the extra row is the truncation probe): the ORDER BY depth contract means- * the DEEPEST edges are the ones dropped, so a truncated result is still the- * complete shallow neighbourhood. Counts raw rows before dedup — the deduped- * `paths.length` can be well under the cap on a truncated walk.+ * The breadth-first walk returns each qualifying edge once, but a hub's+ * neighbourhood can still hold far more edges than a caller can use. The+ * final SELECT is bounded to `CAP + 1` rows (the extra row is the truncation+ * probe): the ORDER BY depth contract means the DEEPEST edges are the ones+ * dropped, so a truncated result is still the complete shallow+ * neighbourhood. Counts raw rows before the provenance dedup, so the deduped+ * `paths.length` can be under the cap on a truncated walk.*/export const TRAVERSE_PATH_ROW_CAP = 5000;/**- * Cap on the simple-path rows the graph walks (`traverseGraph`,- * `traversePaths*`, both engines) enumerate before projecting. The walk keeps- * a per-path visited array, so a dense hub has combinatorially many simple- * paths (a 12-page clique at depth 5 took 22 s); the recursive CTE is pulled- * lazily, so a LIMIT on it stops the enumeration. Rows arrive breadth-first,- * so a capped walk keeps the complete shallow neighbourhood.+ * Cap on the pages a graph walk (`traverseGraph`, `traversePaths*`, both+ * engines) visits. The walk is breadth-first and visits each page once, so+ * its work is bounded by the pages and edges it touches; the cap bounds a walk+ * that reaches a huge share of the brain. It is enforced inside the recursion+ * in (depth, slug, id) order, so a capped walk keeps the complete shallow+ * neighbourhood. Before the breadth-first walk this capped enumerated simple+ * paths (a 12-page clique at depth 5 took 22 s).*/export const TRAVERSE_WALK_ROW_CAP = 20000;diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.tsindex 4ded4bf560..81b767b1fd 100644--- a/src/core/engine-sql/links.ts+++ b/src/core/engine-sql/links.ts@@ -21,7 +21,7 @@ import { PageMissingError } from '../engine-errors.ts';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 { sqlFragment, trustedSql, type SqlFragment } from './fragment.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';@@ -521,6 +521,73 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {}+/**+ * Breadth-first walk shared by `traverseGraph` and `traversePathsDetailed`.+ *+ * Each recursive row is one whole BFS layer: its depth, its frontier and every+ * page visited so far. A layer expands the frontier through one indexed+ * `links` join with the caller's per-step filters (soft delete, privacy,+ * source scope, link type, temporal policy), drops already-visited pages with a+ * hash anti-join, and keeps at most `layerCap` new pages and never more than+ * TRAVERSE_WALK_ROW_CAP + 1 visited pages in total, in (slug, id) order. Every+ * page therefore appears once, at its shortest distance from the seed, and the+ * work is bounded by the pages and edges touched instead of by the number of+ * simple paths (the old per-path CTE took 22 s on a 12-page clique at depth 5).+ *+ * Emits two CTEs: `bfs` and `walk(id, depth, pos)`, where `pos` is the page's+ * position in visit order. A walk with more than TRAVERSE_WALK_ROW_CAP rows was+ * truncated; callers keep `pos <= TRAVERSE_WALK_ROW_CAP`.+ */+function bfsWalkCtes(w: {+ seed: SqlFragment;+ maxLayer: number;+ direction: 'in' | 'out' | 'both';+ step: SqlFragment;+ layerCap?: number;+}) {+ const out = sqlFragment`SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id)+ JOIN links l ON l.from_page_id = f.id+ JOIN pages p2 ON p2.id = l.to_page_id+ WHERE ${w.step}`;+ const into = sqlFragment`SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id)+ JOIN links l ON l.to_page_id = f.id+ JOIN pages p2 ON p2.id = l.from_page_id+ WHERE ${w.step}`;+ const neighbours = w.direction === 'out' ? out : w.direction === 'in' ? into : sqlFragment`${out} UNION ALL ${into}`;+ const budget = sqlFragment`greatest(0, ${TRAVERSE_WALK_ROW_CAP + 1}::int - cardinality(bfs.visited))`;+ const limit = w.layerCap !== undefined && w.layerCap > 0 ? sqlFragment`least(${w.layerCap}::int, ${budget})` : budget;+ return sqlFragment`bfs(depth, frontier, visited) AS (+ SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id)+ FROM pages p WHERE ${w.seed}+ HAVING count(*) > 0+ UNION ALL+ SELECT bfs.depth + 1, n.next, bfs.visited || n.next+ FROM bfs CROSS JOIN LATERAL (+ SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next+ FROM (+ SELECT DISTINCT nb.id, nb.slug FROM (${neighbours}) nb+ WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id)+ ORDER BY nb.slug, nb.id+ LIMIT ${limit}+ ) c+ ) n+ WHERE bfs.depth < ${w.maxLayer}::int AND n.next IS NOT NULL+ ),+ walk AS (+ SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos+ FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord)+ )`;+}++const SCOPED_SOURCE_COLUMNS = { p: 'p.source_id', p2: 'p2.source_id', p3: 'p3.source_id', pf: 'pf.source_id', pt: 'pt.source_id' } as const;++function sourceScope(alias: keyof typeof SCOPED_SOURCE_COLUMNS, opts?: { sourceId?: string; sourceIds?: string[] }) {+ const column = trustedSql(SCOPED_SOURCE_COLUMNS[alias]);+ if (opts?.sourceIds && opts.sourceIds.length > 0) return sqlFragment`AND ${column} = ANY(${opts.sourceIds}::text[])`;+ if (opts?.sourceId) return sqlFragment`AND ${column} = ${opts.sourceId}`;+ return sqlFragment``;+}+export async function traverseGraph(exec: LegacyUnscopedRead,slug: string,@@ -529,98 +596,45 @@ export async function traverseGraph(): Promise<GraphNode[]> {const privacy = (page: string, link?: string) => opts?.excludePrivate? trustedSql(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sqlFragment``;- // v0.34.1 (#861 — P0 leak seal): scope visited nodes to the caller's- // source(s). Without this, the walk follows edges into pages from- // foreign sources, leaking topology + page metadata. The filter- // applies at BOTH the seed (root must be in scope) AND the recursive- // step (every visited neighbor must be in scope). The aggregation- // subquery also filters so the per-node `links` array only includes- // edges to in-scope pages.- const useSourceIds = opts?.sourceIds && opts.sourceIds.length > 0;- const seedScope = useSourceIds- ? sqlFragment`AND p.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND p.source_id = ${opts.sourceId}`- : sqlFragment``;- const stepScope = useSourceIds- ? sqlFragment`AND p2.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND p2.source_id = ${opts.sourceId}`- : sqlFragment``;- const aggScope = useSourceIds- ? sqlFragment`AND p3.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND p3.source_id = ${opts.sourceId}`- : sqlFragment``;- // T8 (v0.36+): frontier cap. When set, the recursive term applies a- // parenthesized LIMIT N with ORDER BY (slug, id) for stable selection.- // Postgres' parenthesized-LIMIT inside a recursive term caps per- // ITERATION, which maps approximately to per-BFS-LAYER (the mapping is- // exact when fanout is bounded; for hub-fanout graphs the cap fires- // early). Post-query, count rows per depth — if any depth == cap, fire- // the truncation callback.- const cap = opts?.frontierCap;- const recursiveStep = cap !== undefined && cap > 0- ? sqlFragment`(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 < ${depth}- AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- ${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- 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 < ${depth}- AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- ${stepScope} ${temporalWalkFilter('l', opts)}`;- // Cycle prevention: visited array tracks page IDs already in the path.+ // v0.34.1 (#861 — P0 leak seal): visited pages are scoped to the caller's+ // source(s) at the seed and at every step, and the per-node `links`+ // aggregation only includes edges to in-scope pages.+ // T8 (v0.36+): `frontierCap` bounds the new pages each BFS layer adds,+ // chosen in (slug, id) order.const rows = (await exec.run(sqlFragment`- 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 = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}-- UNION ALL-- ${recursiveStep}- )- SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth,+ WITH RECURSIVE ${bfsWalkCtes({+ seed: sqlFragment`p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${sourceScope('p', opts)}`,+ maxLayer: depth,+ direction: 'out',+ step: sqlFragment`p2.deleted_at IS NULL ${privacy('p2', 'l')} ${sourceScope('p2', opts)} ${temporalWalkFilter('l', opts)}`,+ layerCap: opts?.frontierCap,+ })}+ SELECT 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.+ -- aggregation. See plan Bug 6/10.(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))FROM links l2JOIN 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} ${temporalWalkFilter('l2', opts)}),+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${sourceScope('p3', opts)} ${temporalWalkFilter('l2', opts)}),'[]'::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 ${TRAVERSE_WALK_ROW_CAP}) capped) g+ FROM (SELECT p.id, p.slug, p.source_id, p.title, p.type, w.depth+ FROM walk w JOIN pages p ON p.id = w.id+ WHERE w.pos <= ${TRAVERSE_WALK_ROW_CAP}::int) gORDER BY g.depth, g.slug, g.source_id`)).rows;- // T8 truncation-detection callback was designed here but the v1 algorithm- // had both false-positive (organic count == cap) and false-negative- // (LIMIT-before-DISTINCT in diamond graphs) cases caught by adversarial- // review. Stripped pending the dedupe-then-cap SQL rewrite + real Postgres- // parity coverage. See TODOS.md → "T8 truncation signal".-return rows.map((r: Record<string, unknown>) => ({slug: r.slug as string,source_id: r.source_id as string,title: r.title as string,type: r.type as string,- depth: r.depth as number,+ depth: Number(r.depth),links: (typeof r.links === 'string' ? JSON.parse(r.links) : r.links) as { to_slug: string; link_type: string }[],}));}@@ -636,59 +650,24 @@ export async function traversePathsDetailed(const depth = opts?.depth ?? 5;const direction = opts?.direction ?? 'out';const linkType = opts?.linkType ?? null;- const linkTypeMatches = linkType !== null;- // v0.34.1 (#861 — P0 leak seal): source-scope filter fragments. Applied- // at seed (root must be in scope) AND at every recursive step (neighbor- // must be in scope) AND in the SELECT join (final edges respect scope).- // The 'both' branch needs filters on BOTH endpoint joins.- const useSourceIds = opts?.sourceIds && opts.sourceIds.length > 0;- const seedScope = useSourceIds- ? sqlFragment`AND p.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND p.source_id = ${opts.sourceId}`- : sqlFragment``;- const stepScope = useSourceIds- ? sqlFragment`AND p2.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND p2.source_id = ${opts.sourceId}`- : sqlFragment``;- // For the 'both' direction's final SELECT, both endpoint joins (pf, pt)- // get scope filters so edges crossing into a foreign source are dropped.- const pfScope = useSourceIds- ? sqlFragment`AND pf.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND pf.source_id = ${opts.sourceId}`- : sqlFragment``;- const ptScope = useSourceIds- ? sqlFragment`AND pt.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sqlFragment`AND pt.source_id = ${opts.sourceId}`- : sqlFragment``;-- // #3754: soft-deleted pages are excluded at seed, every recursive step, and- // the final SELECT joins — a deleted page neither anchors, relays, nor- // terminates a path (mirrors pglite-engine.traversePaths).- let rows;- if (direction === 'out') {- rows = (await exec.run(sqlFragment`- 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 = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}- 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 < ${depth}- AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- 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}),- nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped)- SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,- w.id as from_id, w.slug as from_slug, w.source_id as from_source_id,+ const linkTypeFilter = linkType !== null ? sqlFragment`AND l.link_type = ${linkType}` : sqlFragment``;+ // v0.34.1 (#861 — P0 leak seal) and #3754: source scope, soft delete,+ // privacy, link type and temporal policy apply at the seed, at every BFS+ // step and on both endpoints of every returned edge, so an out-of-scope,+ // private or deleted page neither anchors, relays nor terminates a path.+ // The walk visits pages at depth < `depth`; each qualifying edge is+ // returned once, at one past the depth of its shallower visited endpoint+ // on the walked side ('both' counts either endpoint).+ const walk = bfsWalkCtes({+ seed: sqlFragment`p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${sourceScope('p', opts)}`,+ maxLayer: depth - 1,+ direction,+ step: sqlFragment`p2.deleted_at IS NULL ${privacy('p2', 'l')} ${linkTypeFilter} ${temporalWalkFilter('l', opts)} ${sourceScope('p2', opts)}`,+ });+ const visited = sqlFragment`nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= ${TRAVERSE_WALK_ROW_CAP}::int)`;+ const walkTruncated = sqlFragment`(SELECT count(*) FROM walk) > ${TRAVERSE_WALK_ROW_CAP}::int AS walk_truncated`;+ const edges = direction === 'out'+ ? sqlFragment`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 depthFROM nodes w@@ -696,31 +675,10 @@ export async function traversePathsDetailed(JOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < ${depth}AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- 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}- `)).rows;- } else if (direction === 'in') {- rows = (await exec.run(sqlFragment`- 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 = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}- 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 < ${depth}- AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- 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}),- nodes AS (SELECT DISTINCT id, slug, source_id, depth FROM capped)- SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,- p2.id as from_id, p2.slug as from_slug, p2.source_id as from_source_id,+ ${linkTypeFilter} ${temporalWalkFilter('l', opts)}+ ${sourceScope('p2', opts)}`+ : direction === 'in'+ ? sqlFragment`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 depthFROM nodes w@@ -728,54 +686,44 @@ export async function traversePathsDetailed(JOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < ${depth}AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- 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}- `)).rows;- } else {- rows = (await exec.run(sqlFragment`- WITH RECURSIVE walk AS (- SELECT p.id, 0::int as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}- 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 < ${depth}- AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL ${privacy('p2', 'l')}- AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''}) ${temporalWalkFilter('l', opts)}- ${stepScope}- ),- capped AS (SELECT id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),- nodes AS (SELECT DISTINCT id, depth FROM capped)- SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,- pf.id as from_id, pf.slug as from_slug, pf.source_id as from_source_id,+ ${linkTypeFilter} ${temporalWalkFilter('l', opts)}+ ${sourceScope('p2', opts)}`+ : sqlFragment`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)+ l.link_type, l.context, e.depth + 1 as depth+ FROM (+ SELECT l.id AS link_id, wf.depth FROM nodes wf+ JOIN links l ON l.from_page_id = wf.id+ LEFT JOIN nodes wt ON wt.id = l.to_page_id+ WHERE wt.id IS NULL OR wf.depth <= wt.depth+ UNION ALL+ SELECT l.id, wt.depth FROM nodes wt+ JOIN links l ON l.to_page_id = wt.id+ LEFT JOIN nodes wf ON wf.id = l.from_page_id+ WHERE wf.id IS NULL OR wt.depth < wf.depth+ ) e+ JOIN links l ON l.id = e.link_idJOIN pages pf ON pf.id = l.from_page_idJOIN pages pt ON pt.id = l.to_page_id- WHERE w.depth < ${depth}+ WHERE e.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 ?? ''}) ${temporalWalkFilter('l', opts)}- ${pfScope}- ${ptScope}- ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id- LIMIT ${TRAVERSE_PATH_ROW_CAP + 1}- `)).rows;- }+ ${linkTypeFilter} ${temporalWalkFilter('l', opts)}+ ${sourceScope('pf', opts)}+ ${sourceScope('pt', opts)}`;+ const rows = (await exec.run(sqlFragment`+ WITH RECURSIVE ${walk}, ${visited}+ SELECT ${walkTruncated}, ${edges}+ ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id+ LIMIT ${TRAVERSE_PATH_ROW_CAP + 1}+ `)).rows;// Row cap: the LIMIT above fetched CAP + 1 rows; the probe row only tells// us the walk overflowed and is dropped with everything past the cap.const truncated = rows.length > TRAVERSE_PATH_ROW_CAP || (rows as Array<{ walk_truncated?: boolean }>).some((r) => r.walk_truncated === true);const bounded = (truncated ? rows.slice(0, TRAVERSE_PATH_ROW_CAP) : rows) as Record<string, unknown>[];- // Dedup edges (same edge can appear via multiple visited paths). Keyed on- // page ids, so the same slug in two sources stays two distinct edges.+ // Duplicate link rows (same edge, different provenance) collapse here.+ // Keyed on page ids, so the same slug in two sources stays two edges.const seen = new Set<string>();const result: GraphPath[] = [];for (const r of bounded) {diff --git a/src/core/engine.ts b/src/core/engine.tsindex a9bbf74bc9..0b6dd98984 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -39,22 +39,13 @@ import type {/*** Options for `traverseGraph`.*- * `frontierCap`: when set, the BFS recursive term applies a parenthesized- * `LIMIT N ORDER BY slug,id` so each iteration emits at most N rows. This- * is the "approximately per-layer" cap discussed in the T8 plan — Postgres'- * recursive CTE caps per ITERATION, not strictly per BFS LAYER (BFS layer- * boundaries map to recursive iterations only when fan-out is bounded).- * For hub-fanout graphs the cap fires early and bounds the work. Default:- * unset = no cap (back-compat; existing callers see no change).+ * `frontierCap`: when set, each breadth-first layer adds at most N new+ * pages, chosen after deduplication in (slug, id) order. Default: unset = no+ * per-layer cap (the walk is still bounded by TRAVERSE_WALK_ROW_CAP).*- * NOTE: a truncation-detection signal (`onTruncation` callback) was- * designed but the v1 algorithm had both false-positive (organic count ==- * cap) and false-negative (LIMIT-before-DISTINCT in diamond graphs) cases- * caught by adversarial review. The signal is deferred until a- * dedupe-then-cap SQL rewrite + real Postgres parity coverage lands. See- * TODOS.md → "T8 truncation signal" entry. Callers that need to detect- * truncation can compare `result.length` against expected fanout bounds- * as a coarse-but-honest signal in the interim.+ * NOTE: no truncation signal is exposed yet. The per-layer cap now dedupes+ * before it limits, which was the precondition in TODOS.md → "T8 truncation+ * signal"; restoring the callback is still open there.*//*** v0.38: bare row shape returned by `BrainEngine.listAllSources()`.@@ -1603,7 +1594,8 @@ export interface BrainEngine {* - direction: 'in' (follow to->from), 'out' (follow from->to), 'both'* - depth: max depth from root (default 5)* - sourceId/sourceIds: v0.34.1 source-isolation filter, see traverseGraph- * Uses cycle prevention (visited array in recursive CTE).+ * Breadth-first: each page is visited once, at its shortest depth, and each+ * qualifying edge leaving a visited page is returned once.*/traversePaths(slug: string,diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 7a9912f3ab..631e14b987 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -31,7 +31,7 @@ import type { OperationContext } from './contract.ts';import type { Link, PageReadPolicy } from '../types.ts';import { ALL_SOURCES } from '../source-id.ts';import { PageMissingError } from '../engine-errors.ts';-import { TRAVERSE_PATH_ROW_CAP } from '../engine-constants.ts';+import { TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_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, STARTER_STATUS_PARAM, STARTER_AS_OF_PARAM, resolveEdgeTemporal, filterTemporalLinks, reportTemporal } from './edge-temporal.ts';@@ -439,10 +439,10 @@ const list_link_sources: Operation = {};/**- * Hard cap on traverse_graph depth from MCP callers. Each recursive CTE iteration- * grows a `visited` array per path; in `direction=both` the join is `OR`-based and- * fans out exponentially. Without a cap, a remote MCP caller can pass depth=1e6- * and burn memory/CPU on the database. 10 hops is well beyond any realistic+ * Hard cap on traverse_graph depth from MCP callers. The walk is breadth-first+ * and bounded by TRAVERSE_WALK_ROW_CAP pages, but each hop is one more layer of+ * work; without a cap a remote MCP caller could pass depth=1e6. 10 hops is well+ * beyond any realistic* relationship query (your OpenClaw's "people who attended meetings with Alice"* is 2 hops; the deepest meaningful chain in our test data is 4).*/@@ -450,10 +450,9 @@ const TRAVERSE_DEPTH_CAP = 10;/*** Default depth for the remote no-direction call. #4666 made that call- * bidirectional, and traversePaths' `both` branch is an uncapped- * path-enumerating recursive CTE (no LIMIT) — on an entity hub with 10^2-10^3- * edges the legacy depth-5 default is combinatorial, on the per-agent-turn- * path. Two hops covers the realistic relationship query ("people who+ * bidirectional; on an entity hub a depth-5 `both` walk reaches most of the+ * brain and returns the 5,000-row cap of edges on every agent turn. Two hops+ * covers the realistic relationship query ("people who* attended meetings with Alice"); a caller that wants more passes `depth`* explicitly (still honored up to TRAVERSE_DEPTH_CAP).*/@@ -578,11 +577,12 @@ const traverse_graph: Operation = {return ctx.engine.traverseGraph(slug, depth, scope);}const { paths, truncated } = await ctx.engine.traversePathsDetailed(slug, { depth, linkType, direction, ...scope });- // Row cap hit: the walk's deepest edges were dropped. stderr-only so the- // GraphPath[] wire shape stays unchanged (additive contract).+ // Cap hit: the walk stopped at TRAVERSE_WALK_ROW_CAP visited pages or the+ // output at TRAVERSE_PATH_ROW_CAP edge rows, dropping the deepest edges.+ // stderr-only so the GraphPath[] wire shape stays unchanged.if (truncated) {ctx.logger.warn(- `[gbrain] traverse_graph output truncated at ${TRAVERSE_PATH_ROW_CAP} edge rows (shallowest first). ` ++ `[gbrain] traverse_graph output truncated (walk cap ${TRAVERSE_WALK_ROW_CAP} pages, ${TRAVERSE_PATH_ROW_CAP} edge rows; shallowest first). ` +`Lower depth or narrow with link_type/direction for a complete walk.`,);}diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex dc9ba0d102..8b691c4c2a 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -2747,7 +2747,7 @@"traverseGraph": {"default": [{- "paramCount": 3,+ "paramCount": 4,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2758,7 +2758,7 @@],"excludePrivate": [{- "paramCount": 3,+ "paramCount": 4,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2769,7 +2769,7 @@],"frontierCap": [{- "paramCount": 4,+ "paramCount": 5,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2780,7 +2780,7 @@],"sourceId": [{- "paramCount": 6,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2791,7 +2791,7 @@],"sourceIds": [{- "paramCount": 6,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2804,7 +2804,7 @@"traversePaths": {"default": [{- "paramCount": 10,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2817,7 +2817,7 @@"traversePathsDetailed": {"both": [{- "paramCount": 10,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2828,7 +2828,7 @@],"both+sourceIds+excludePrivate": [{- "paramCount": 14,+ "paramCount": 12,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2839,7 +2839,7 @@],"default": [{- "paramCount": 10,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2850,7 +2850,7 @@],"in": [{- "paramCount": 10,+ "paramCount": 7,"unsafeOptions": {"cancelFence": false,"prepare": true,@@ -2861,7 +2861,7 @@],"out+sourceId+linkType": [{- "paramCount": 13,+ "paramCount": 12,"unsafeOptions": {"cancelFence": false,"prepare": true,diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.jsonindex e593d0a890..758885d2c0 100644--- a/test/fixtures/goldens/sql-text/links.json+++ b/test/fixtures/goldens/sql-text/links.json@@ -652,10 +652,11 @@"params": ["string","number",+ "number","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": "5c336c4483dab0e5893bfff19cb3968108a3312402aef13178d2d5829ab99acb"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ) SELECT 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. 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 p.id, p.slug, p.source_id, p.title, p.type, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) g ORDER BY g.depth, g.slug, g.source_id",+ "textSha256": "1d138974016d115a06f84079f206580472575d4af8ea4dc5f1d5d15b4752b2e9"}],"excludePrivate": [@@ -664,10 +665,11 @@"params": ["string","number",+ "number","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 IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p2.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) ) 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 IN ('atom', 'question') OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p3.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) ), '[]'::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": "8f914f398822929f4503112252fcb46abc675a53a08f2c0359cb216edcd631d6"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL AND ((COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type IN ('atom', 'question') OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p2.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ) SELECT 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. 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 IN ('atom', 'question') OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p3.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) ), '[]'::jsonb ) as links FROM (SELECT p.id, p.slug, p.source_id, p.title, p.type, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) g ORDER BY g.depth, g.slug, g.source_id",+ "textSha256": "65e560327fceecb59e3ec42ee18dd85f9d8289b27e076f1ed5bb076727d2dd12"}],"frontierCap": [@@ -677,10 +679,11 @@"string","number","number",+ "number","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": "ff8d91623f7d0deae58a6866d514eaf62a5ca64e1f456d7d4cb07052a23685c7"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT least($2::int, greatest(0, $3::int - cardinality(bfs.visited))) ) c ) n WHERE bfs.depth < $4::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ) SELECT 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. 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 p.id, p.slug, p.source_id, p.title, p.type, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $5::int) g ORDER BY g.depth, g.slug, g.source_id",+ "textSha256": "b658e1bc870bde70bd2c7597b000c188b43f1851724562e2ca9039c247b3e5d1"}],"sourceId": [@@ -689,13 +692,14 @@"params": ["string","string",- "number","string",+ "number",+ "number","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": "af76f0948aa5f8f01f4303f9f8e2c24abb3f950a50d0a6b7f56a8c3d0f699dec"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = $2 HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL AND p2.source_id = $3 ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $4::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $5::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ) SELECT 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. 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 = $6 ), '[]'::jsonb ) as links FROM (SELECT p.id, p.slug, p.source_id, p.title, p.type, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $7::int) g ORDER BY g.depth, g.slug, g.source_id",+ "textSha256": "3cc559c5a3605ca2ad7bb823bcdf0a7aab599f1147d668bd17215bf300b75f40"}],"sourceIds": [@@ -704,13 +708,14 @@"params": ["string","array<string>",- "number","array<string>",+ "number",+ "number","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": "733ad24d082dbbf77b97f87117b52a6da365438c1dbca764f3486f5564916eb2"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = ANY($2::text[]) HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL AND p2.source_id = ANY($3::text[]) ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $4::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $5::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ) SELECT 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. 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($6::text[]) ), '[]'::jsonb ) as links FROM (SELECT p.id, p.slug, p.source_id, p.title, p.type, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $7::int) g ORDER BY g.depth, g.slug, g.source_id",+ "textSha256": "5dcc1c8123ee64b67bbb6dfb903e9b34c1c5cbcaa00ed2b29d9f9639119d39d6"}]},@@ -721,17 +726,14 @@"params": ["string","number",- "boolean",- "string","number","number","number",- "boolean",- "string",+ "number","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": "c3442529a0698fb3a666ab6d105ba5fae3cfa885245264bef12eb2d98867b114"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) SELECT (SELECT count(*) FROM walk) > $5::int 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 < $6 AND p2.deleted_at IS NULL ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $7",+ "textSha256": "6b1646f346367c36b468f146daaf0048ba87215f1a4c38a54315735aec968b2a"}]},@@ -742,17 +744,14 @@"params": ["string","number",- "boolean",- "string","number","number","number",- "boolean",- "string",+ "number","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": "93cae18d1d0db70209c65f154fcc60e9b8858a4318c2fd8fc5c6c0da5271ca96"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL UNION ALL SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.to_page_id = f.id JOIN pages p2 ON p2.id = l.from_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) SELECT (SELECT count(*) FROM walk) > $5::int AS walk_truncated, e.* FROM ( SELECT DISTINCT ON (l.id) 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 < $6 AND pf.deleted_at IS NULL AND pt.deleted_at IS NULL ORDER BY l.id, w.depth) e ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $7",+ "textSha256": "05658a04bd041382ba5fefb924ee5a7cd2b2df1082492545022cb7c131945ac7"}],"both+sourceIds+excludePrivate": [@@ -761,21 +760,19 @@"params": ["string","array<string>",- "number",- "boolean",- "string",+ "array<string>","array<string>","number","number","number",- "boolean",- "string",+ "number",+ "number","array<string>","array<string>","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 IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p2.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) 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 IN ('atom', 'question') OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pf.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) AND pt.deleted_at IS NULL AND ((COALESCE(pt.frontmatter->>'visibility', CASE WHEN (pt.type IN ('atom', 'question') OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pt.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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": "864c4445a1728c5515f2773d1ee9bcbf52b56d90be4e9fcb38634f0c8606e3fe"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) AND p.source_id = ANY($2::text[]) HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL AND ((COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type IN ('atom', 'question') OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p2.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) AND p2.source_id = ANY($3::text[]) UNION ALL SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.to_page_id = f.id JOIN pages p2 ON p2.id = l.from_page_id WHERE p2.deleted_at IS NULL AND ((COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type IN ('atom', 'question') OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p2.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) AND p2.source_id = ANY($4::text[])) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $5::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $6::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $7::int) SELECT (SELECT count(*) FROM walk) > $8::int AS walk_truncated, e.* FROM ( SELECT DISTINCT ON (l.id) 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 IN ('atom', 'question') OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pf.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) 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 IN ('atom', 'question') OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(origin_private.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) )) AND pt.deleted_at IS NULL AND ((COALESCE(pt.frontmatter->>'visibility', CASE WHEN (pt.type IN ('atom', 'question') OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pt.frontmatter ? 'pinned_question', false)) 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 IN ('atom', 'question') 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 IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') IN ('array', 'string') THEN 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 = ANY(ARRAY( 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)))) ELSE false END)) AND pf.source_id = ANY($10::text[]) AND pt.source_id = ANY($11::text[]) ORDER BY l.id, w.depth) e ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $12",+ "textSha256": "8f83e2be098658f8d4de2c59cb32add39de7ce001badd61e2040a5fd56a93abd"}],"default": [@@ -784,17 +781,14 @@"params": ["string","number",- "boolean",- "string","number","number","number",- "boolean",- "string",+ "number","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": "c3442529a0698fb3a666ab6d105ba5fae3cfa885245264bef12eb2d98867b114"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) SELECT (SELECT count(*) FROM walk) > $5::int 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 < $6 AND p2.deleted_at IS NULL ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $7",+ "textSha256": "6b1646f346367c36b468f146daaf0048ba87215f1a4c38a54315735aec968b2a"}],"in": [@@ -803,17 +797,14 @@"params": ["string","number",- "boolean",- "string","number","number","number",- "boolean",- "string",+ "number","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": "4756f322dc94d858cd282090d9d00008cd68876d2694bda4f6cb422dc371778f"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.to_page_id = f.id JOIN pages p2 ON p2.id = l.from_page_id WHERE p2.deleted_at IS NULL ) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $2::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $3::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $4::int) SELECT (SELECT count(*) FROM walk) > $5::int 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 < $6 AND p2.deleted_at IS NULL ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $7",+ "textSha256": "1d070cca5f93f22000ca40510d235bbaaec3b8500dcbe27651306253af0d37ee"}],"out+sourceId+linkType": [@@ -822,20 +813,19 @@"params": ["string","string",- "number",- "boolean","string","string","number","number","number",- "boolean",+ "number",+ "number","string","string","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": "0782a48ffe3c9e19c3ec03b24e4c62d515574b0e27df687bee2c7d12147d4bb1"+ "sql": "WITH RECURSIVE bfs(depth, frontier, visited) AS ( SELECT 0, array_agg(p.id ORDER BY p.slug, p.id), array_agg(p.id ORDER BY p.slug, p.id) FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND p.source_id = $2 HAVING count(*) > 0 UNION ALL SELECT bfs.depth + 1, n.next, bfs.visited || n.next FROM bfs CROSS JOIN LATERAL ( SELECT array_agg(c.id ORDER BY c.slug, c.id) AS next FROM ( SELECT DISTINCT nb.id, nb.slug FROM (SELECT p2.id, p2.slug FROM unnest(bfs.frontier) f(id) JOIN links l ON l.from_page_id = f.id JOIN pages p2 ON p2.id = l.to_page_id WHERE p2.deleted_at IS NULL AND l.link_type = $3 AND p2.source_id = $4) nb WHERE NOT EXISTS (SELECT 1 FROM unnest(bfs.visited) v(id) WHERE v.id = nb.id) ORDER BY nb.slug, nb.id LIMIT greatest(0, $5::int - cardinality(bfs.visited)) ) c ) n WHERE bfs.depth < $6::int AND n.next IS NOT NULL ), walk AS ( SELECT u.id, b.depth, row_number() OVER (ORDER BY b.depth, u.ord) AS pos FROM bfs b CROSS JOIN LATERAL unnest(b.frontier) WITH ORDINALITY u(id, ord) ), nodes AS (SELECT p.id, p.slug, p.source_id, w.depth FROM walk w JOIN pages p ON p.id = w.id WHERE w.pos <= $7::int) SELECT (SELECT count(*) FROM walk) > $8::int 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 l.link_type = $10 AND p2.source_id = $11 ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $12",+ "textSha256": "d1275e879f837c8bd9166c7fcd82418e72a8c48f60a99ed70829946fae502c2d"}]}diff --git a/test/helpers/dense-hub.ts b/test/helpers/dense-hub.tsindex 8e7ac55a83..17673b85c4 100644--- a/test/helpers/dense-hub.ts+++ b/test/helpers/dense-hub.ts@@ -3,13 +3,13 @@** `cap/hub` has 200 inbound spokes (cap/s000..cap/s199 -> hub) and 200* outbound spokes (hub -> cap/s200..cap/s399). The 400 spokes also form a- * ring where every spoke links to the next `ringOffsets` spokes, so a- * `direction: 'both'` walk from the hub at depth 3 touches every edge at- * every depth level: distinct (from, to, type, depth) keys =- * 400 + 2 * (400 + 400 * ringOffsets). With the default 5 offsets that is- * 5,200 deduped edges (> TRAVERSE_PATH_ROW_CAP) from ~49k raw CTE rows —- * enough to overflow the cap on the DEDUPED count, so the pre-cap engine is- * discriminable from the capped one by `paths.length` alone.+ * ring where every spoke links to the next `ringOffsets` spokes. The+ * breadth-first walk returns each edge once, at the depth just past its+ * shallower endpoint, so a `direction: 'both'` walk from the hub at depth 2+ * or more returns every edge: 400 + 400 * ringOffsets. With the default 12+ * offsets that is 5,200 edges (> TRAVERSE_PATH_ROW_CAP), enough to overflow+ * the cap, so a capped walk is discriminable from an uncapped one by+ * `paths.length` alone.** Slugs share one prefix + zero-padded index so ORDER BY from_slug, to_slug* sorts identically under any collation (Postgres vs PGLite parity).@@ -23,7 +23,7 @@ export function denseHubSpoke(i: number): string {return `cap/s${String(i).padStart(3, '0')}`;}-export async function seedDenseHub(engine: BrainEngine, ringOffsets = 5): Promise<{ edges: number }> {+export async function seedDenseHub(engine: BrainEngine, ringOffsets = 12): Promise<{ edges: number }> {await engine.putPage(DENSE_HUB_SLUG, { type: 'note', title: 'Hub', compiled_truth: 'hub body', timeline: '' });for (let i = 0; i < DENSE_HUB_SPOKES; i++) {await engine.putPage(denseHubSpoke(i), { type: 'note', title: `Spoke ${i}`, compiled_truth: `spoke ${i}`, timeline: '' });diff --git a/test/traverse-bfs.test.ts b/test/traverse-bfs.test.tsnew file mode 100644index 0000000000..d93897cc5f--- /dev/null+++ b/test/traverse-bfs.test.ts@@ -0,0 +1,175 @@+/**+ * Breadth-first graph walks: each page once, at its shortest distance.+ *+ * On seeded random graphs (soft-deleted pages, three link types, cycles) the+ * engine walks must match a TypeScript BFS reference exactly, and the distinct+ * pages and edges they return must match the pre-BFS simple-path CTE, which+ * is kept here as the reference for the old contract. Only duplicate deeper+ * copies of a page or edge may differ from the old walk.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const PAGES = 60;+const LINKS = 220;+const TYPES = ['works_at', 'invested_in', 'mentions'];+const slugOf = (i: number) => `bfs/p${String(i).padStart(2, '0')}`;++let engine: PGLiteEngine;+const edges: Array<{ from: number; to: number; type: string }> = [];+const deleted = new Set<number>();++function rng(seed: number) {+ let s = seed;+ return () => { s = (s * 1103515245 + 12345) % 2147483648; return s / 2147483648; };+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const rand = rng(7);+ for (let i = 0; i < PAGES; i++) {+ await engine.putPage(slugOf(i), { type: 'note', title: `p${i}`, compiled_truth: `page ${i}`, timeline: '' });+ }+ const seen = new Set<string>();+ while (edges.length < LINKS) {+ const from = Math.floor(rand() * PAGES);+ const to = Math.floor(Math.pow(rand(), 2) * PAGES);+ const type = TYPES[Math.floor(rand() * TYPES.length)];+ const key = `${from}|${to}|${type}`;+ if (from === to || seen.has(key)) continue;+ seen.add(key);+ edges.push({ from, to, type });+ }+ await engine.addLinksBatch(edges.map(e => ({ from_slug: slugOf(e.from), to_slug: slugOf(e.to), link_type: e.type, link_source: 'manual' })));+ for (const i of [5, 17, 33]) {+ deleted.add(i);+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE slug = $1', [slugOf(i)]);+ }+}, 120_000);++afterAll(async () => { await engine.disconnect(); });++type Dir = 'out' | 'in' | 'both';++function live(e: { from: number; to: number }) {+ return !deleted.has(e.from) && !deleted.has(e.to);+}++function neighbours(w: number, dir: Dir, linkType?: string): number[] {+ const out: number[] = [];+ for (const e of edges) {+ if (!live(e) || (linkType && e.type !== linkType)) continue;+ if (dir !== 'in' && e.from === w) out.push(e.to);+ if (dir !== 'out' && e.to === w) out.push(e.from);+ }+ return out;+}++function distances(seed: number, maxLayer: number, dir: Dir, linkType?: string): Map<number, number> {+ const dist = new Map<number, number>([[seed, 0]]);+ let frontier = [seed];+ for (let d = 1; d <= maxLayer && frontier.length; d++) {+ const next: number[] = [];+ for (const w of frontier) for (const n of neighbours(w, dir, linkType)) {+ if (!dist.has(n)) { dist.set(n, d); next.push(n); }+ }+ frontier = next;+ }+ return dist;+}++function expectedPaths(seed: number, depth: number, dir: Dir, linkType?: string): string[] {+ const dist = distances(seed, depth - 1, dir, linkType);+ const out: string[] = [];+ for (const e of edges) {+ if (!live(e) || (linkType && e.type !== linkType)) continue;+ const sides = [dir !== 'in' ? dist.get(e.from) : undefined, dir !== 'out' ? dist.get(e.to) : undefined].filter((d): d is number => d !== undefined);+ if (sides.length) out.push(`${slugOf(e.from)}>${slugOf(e.to)}|${e.type}|${Math.min(...sides) + 1}`);+ }+ return out.sort();+}++const SEEDS = [0, 1, 2, 9, 41];++describe('breadth-first walks match a shortest-path reference', () => {+ test('traverseGraph returns each reachable page once at its shortest depth', async () => {+ let deepest = 0;+ for (const seed of SEEDS) for (const depth of [1, 2, 3, 5]) {+ const nodes = await engine.traverseGraph(slugOf(seed), depth);+ deepest = Math.max(deepest, ...nodes.map(n => n.depth));+ const got = nodes.map(n => `${n.slug}@${n.depth}`).sort();+ const want = [...distances(seed, depth, 'out')].map(([p, d]) => `${slugOf(p)}@${d}`).sort();+ expect(got).toEqual(want);+ }+ expect(deepest).toBeGreaterThanOrEqual(3);+ }, 60_000);++ test('traversePaths returns every qualifying edge once, one hop past its shallower walk-side page', async () => {+ let total = 0;+ for (const seed of SEEDS) for (const depth of [1, 2, 4]) for (const dir of ['out', 'in', 'both'] as Dir[]) for (const linkType of [undefined, 'works_at']) {+ const { paths, truncated } = await engine.traversePathsDetailed(slugOf(seed), { depth, direction: dir, linkType });+ total += paths.length;+ expect(truncated).toBe(false);+ const got = paths.map(p => `${p.from_slug}>${p.to_slug}|${p.link_type}|${p.depth}`).sort();+ expect(got).toEqual(expectedPaths(seed, depth, dir, linkType));+ }+ expect(total).toBeGreaterThan(1000);+ }, 120_000);+});++describe('distinct results are unchanged from the simple-path walk', () => {+ test('traverseGraph reaches the same pages as the pre-BFS CTE', async () => {+ for (const seed of SEEDS) for (const depth of [2, 3, 4]) {+ const old = await engine.executeRaw<{ slug: string }>(`+ WITH RECURSIVE graph AS (+ SELECT p.id, p.slug, 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, 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 slug FROM graph ORDER BY slug`, [slugOf(seed), depth]);+ const nodes = await engine.traverseGraph(slugOf(seed), depth);+ expect([...new Set(nodes.map(n => n.slug))].sort()).toEqual(old.map(r => r.slug));+ }+ }, 60_000);+});++describe('a page the caller may not read never relays a walk', () => {+ test('private, out-of-scope and soft-deleted pages in the middle of a chain stop the walk', async () => {+ const { __resetPrivateVisibilityCacheForTests } = await import('../src/core/search/private-visibility.ts');+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('relay-b', 'relay-b', '{}'::jsonb) ON CONFLICT DO NOTHING`);+ for (const relay of ['private', 'foreign', 'deleted', 'origin']) {+ for (const hop of ['a', 'b', 'c']) {+ await engine.putPage(`relay/${relay}-${hop}`, {+ type: 'note', title: `${relay} ${hop}`, compiled_truth: hop, timeline: '',+ frontmatter: relay === 'private' && hop === 'b' ? { visibility: 'private' } : {},+ });+ }+ await engine.addLinksBatch([+ { from_slug: `relay/${relay}-a`, to_slug: `relay/${relay}-b`, link_type: 'works_at', link_source: 'manual' },+ { from_slug: `relay/${relay}-b`, to_slug: `relay/${relay}-c`, link_type: 'works_at', link_source: 'manual' },+ ]);+ }+ await engine.executeRaw(`UPDATE pages SET source_id = 'relay-b' WHERE slug = 'relay/foreign-b'`);+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'relay/deleted-b'`);+ await engine.executeRaw(`UPDATE pages SET frontmatter = '{"visibility":"private"}'::jsonb WHERE slug = 'relay/origin-c'`);+ await engine.executeRaw(`UPDATE links SET origin_page_id = (SELECT id FROM pages WHERE slug = 'relay/origin-c')+ WHERE from_page_id = (SELECT id FROM pages WHERE slug = 'relay/origin-a')`);+ __resetPrivateVisibilityCacheForTests();++ const reached = async (relay: string, opts: Record<string, unknown>) => {+ const nodes = await engine.traverseGraph(`relay/${relay}-a`, 3, opts);+ const paths = await engine.traversePaths(`relay/${relay}-a`, { depth: 3, direction: 'both', ...opts });+ return { nodes: nodes.map(n => n.slug).sort(), paths: paths.flatMap(p => [p.from_slug, p.to_slug]) };+ };+ for (const [relay, opts] of [['private', { excludePrivate: true }], ['foreign', { sourceId: 'default' }], ['deleted', {}], ['origin', { excludePrivate: true }]] as const) {+ const r = await reached(relay, opts);+ expect(r.nodes).toEqual([`relay/${relay}-a`]);+ expect(r.paths).not.toContain(`relay/${relay}-c`);+ }+ const open = await reached('private', {});+ expect(open.nodes).toEqual(['relay/private-a', 'relay/private-b', 'relay/private-c']);+ }, 60_000);+});diff --git a/test/traverse-paths-row-cap.test.ts b/test/traverse-paths-row-cap.test.tsindex 2b7a6625b7..531591edc5 100644--- a/test/traverse-paths-row-cap.test.ts+++ b/test/traverse-paths-row-cap.test.ts@@ -61,7 +61,7 @@ describe('traversePaths row cap (PGLite)', () => {test('traversePaths (the GraphPath[] projection) honours the same cap', async () => {const paths = await engine.traversePaths(DENSE_HUB_SLUG, { depth: 3, direction: 'both' });- // Pre-cap: 5,200 deduped edges (every edge at depth 2 AND depth 3).+ // Pre-cap: 5,200 edges (every edge of the fixture, each once).expect(paths.length).toBeLessThanOrEqual(TRAVERSE_PATH_ROW_CAP);const detailed = await engine.traversePathsDetailed(DENSE_HUB_SLUG, { depth: 3, direction: 'both' });expect(paths).toEqual(detailed.paths);