Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
rank_entities: compute remote coverage over caller-readable pages only
garrytanf29239a43559
diff --git a/docs/guides/graph-ranking.md b/docs/guides/graph-ranking.mdindex b29cb8b541..c5c6080d06 100644--- a/docs/guides/graph-ranking.md+++ b/docs/guides/graph-ranking.md@@ -86,10 +86,12 @@ CLI keeps the trusted view (deleted pages and the scope still apply).`coverage.state` is `current`, `behind` (link extraction has pages to catch up,so counts cover only pages whose links are extracted; `note` says so) or-`unread` (the backlog could not be read). It reads the same backlog as doctor's-`links_extraction_lag` for each source in scope. The local CLI also gets the-page counts; a remote caller gets the state alone, because the counts include-pages it cannot read. The brain host catches up with `gbrain extract --stale`.+`unread` (the backlog could not be read). The local CLI reads the same backlog+as doctor's `links_extraction_lag` for each source in scope and also gets the+page counts. A remote caller gets the state alone, computed over the pages it+can read (the same rule as the ranking): a private, quarantined or+foreign-source page never makes its coverage `behind`. The brain host catches+up with `gbrain extract --stale`.## rank_entities_timeoutdiff --git a/src/core/engine-sql/graph-rank.ts b/src/core/engine-sql/graph-rank.tsindex 8361272c3b..726190b289 100644--- a/src/core/engine-sql/graph-rank.ts+++ b/src/core/engine-sql/graph-rank.ts@@ -42,6 +42,8 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { quarantineFilterFragment } from '../quarantine.ts';import { rankingLinkSql } from '../link-ranking-policy.ts';import { MAX_RETIREMENT_HOPS, retiredPageSql } from '../entities/resolve.ts';+import { staleForExtractionSql } from './pages.ts';+import { ALIAS_DERIVATION_VERSION, MENTION_EXTRACTOR_VERSION } from '../mentions/pass.ts';export type RankDirection = 'in' | 'out' | 'both';@@ -82,7 +84,7 @@ const REDIRECT_TARGET_SQL = "regexp_replace(regexp_replace(btrim(split_part(regeconst FOLD_REASON_SQL = "CASE WHEN btrim(COALESCE(rp.frontmatter->>'superseded_by', '')) <> '' THEN 'superseded_by' ELSE 'merged_into' END";/** The pages (alias vp) a counted edge, chain hop, fold target or link origin may touch, evaluated once per page. */-function readablePageSql(opts: RankEntitiesStatementOpts): SqlFragment {+function readablePageSql(opts: Pick<RankEntitiesStatementOpts, 'sourceIds' | 'remote'>): SqlFragment {const scope = opts.sourceIds ? sqlFragment` AND vp.source_id = ANY(${opts.sourceIds}::text[])` : sqlFragment``;if (!opts.remote) return sqlFragment`vp.deleted_at IS NULL${scope}`;const privacy = opts.remote.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('vp')}`) : sqlFragment``;@@ -90,6 +92,26 @@ function readablePageSql(opts: RankEntitiesStatementOpts): SqlFragment {AND EXISTS (SELECT 1 FROM sources rank_source WHERE rank_source.id = vp.source_id AND NOT rank_source.archived)`;}+/**+ * A remote caller's coverage for one source, over the pages it may read (the+ * same readable predicate as the ranking): does any readable page still owe+ * link extraction, and (with mentionTypes) a mention pass? Pages the caller+ * cannot read never move the state.+ */+export function rankCoverageStatement(opts: { sourceId: string; excludePrivate: boolean; versionTs: string; mentionTypes?: string[] }): { text: string; params: unknown[] } {+ const readable = readablePageSql({ sourceIds: [opts.sourceId], remote: { excludePrivate: opts.excludePrivate } });+ const mentionDue = opts.mentionTypes+ ? sqlFragment`EXISTS (SELECT 1 FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id+ WHERE p.id IN (SELECT id FROM readable) AND (s.page_id IS NULL OR s.mention_revision IS DISTINCT FROM p.knowledge_revision+ OR s.mention_version IS DISTINCT FROM ${MENTION_EXTRACTOR_VERSION}+ OR (p.type = ANY(${opts.mentionTypes}::text[]) AND (s.alias_revision IS DISTINCT FROM p.knowledge_revision OR s.alias_version IS DISTINCT FROM ${ALIAS_DERIVATION_VERSION}))))`+ : sqlFragment`false`;+ return renderFragment(sqlFragment`+ WITH readable AS MATERIALIZED (SELECT vp.id FROM pages vp WHERE ${readable})+ SELECT EXISTS (SELECT 1 FROM pages WHERE id IN (SELECT id FROM readable) AND ${staleForExtractionSql(opts.versionTs)}) AS link_behind,+ ${mentionDue} AS mention_due`);+}+export function rankEntitiesStatement(opts: RankEntitiesStatementOpts): { text: string; params: unknown[] } {const mentions = opts.includeMentions ? sqlFragment`` : sqlFragment` AND l.link_source IS DISTINCT FROM 'mentions'`;const linkType = opts.linkType !== undefined ? sqlFragment` AND l.link_type = ${opts.linkType}` : sqlFragment``;diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 3fb62400a4..ae38678f21 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -34,7 +34,7 @@ import { compileRowNormalizer } from './normalize.ts';import { stagingNeedsTextSql } from '../page-body/schema.ts';import { atomRetirementPurgeHold } from '../persistence/atom-retirement-hold.ts';import { createPageVersion } from '../page-state/versions.ts';-import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';+import { renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';import { pickCanonicalOrigin } from '../persistence/origin-guard.ts';@@ -782,6 +782,11 @@ function stalePagesWhere(opts?: { sourceId?: string; versionTs?: string; attendareturn sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}${held}`;}+/** The pages (unaliased `pages` rows) link extraction still owes work: stale, not attendance-blocked, not held (rank_entities' remote coverage). */+export function staleForExtractionSql(versionTs: string): SqlFragment {+ return stalePagesWhere({ versionTs, attendance: 'exclude', held: 'exclude' });+}+/*** #6803 (D1): the live page count, the stale count without attendance-blocked pages and the attendance-blocked count* in one statement, so doctor's `links_extraction_lag` and the sync nudge share one predicate and one threshold input.diff --git a/src/core/ops/graph-rank.ts b/src/core/ops/graph-rank.tsindex b7a590d270..09e3633e11 100644--- a/src/core/ops/graph-rank.ts+++ b/src/core/ops/graph-rank.ts@@ -103,9 +103,10 @@ function parseFolded(value: unknown): Array<{ slug: string; reason: string }> {return Array.isArray(list) ? list.map(f => ({ slug: String(f.slug), reason: String(f.reason) })) : [];}-async function readCoverage(ctx: OperationContext, sourceIds: string[] | undefined, includeMentions: boolean): Promise<Coverage> {+async function readCoverage(ctx: OperationContext, sourceIds: string[] | undefined, includeMentions: boolean, excludePrivate: boolean): Promise<Coverage> {const targets: Array<string | undefined> = sourceIds ?? [undefined];if (targets.length > COVERAGE_SOURCE_CAP) return { state: 'unread', reason: 'too_many_sources' };+ if (ctx.remote !== false) return readRemoteCoverage(ctx, sourceIds, includeMentions, excludePrivate);const { readExtractionLag } = await import('../extraction-lag.ts');const sum = { total: 0, actionable: 0, attendance_blocked: 0, held: 0, mention_due: null as number | null };try {@@ -120,9 +121,29 @@ async function readCoverage(ctx: OperationContext, sourceIds: string[] | undefin} catch {return { state: 'unread', reason: 'read_failed' };}- const state = sum.actionable > 0 || (includeMentions && (sum.mention_due ?? 0) > 0) ? 'behind' : 'current';- // The counts include pages a remote caller cannot read, so remote callers get the state alone.- return ctx.remote === false ? { state, ...sum } : { state };+ return { state: sum.actionable > 0 || (includeMentions && (sum.mention_due ?? 0) > 0) ? 'behind' : 'current', ...sum };+}++/** A remote caller's state alone, computed over the pages it may read: a page it cannot see never makes coverage behind. */+async function readRemoteCoverage(ctx: OperationContext, sourceIds: string[] | undefined, includeMentions: boolean, excludePrivate: boolean): Promise<Coverage> {+ const { effectiveLinkExtractorWatermark } = await import('../link-extraction-watermark.ts');+ const { linkableTypesFor, loadSourcePack, readMentionPolicy } = await import('../mentions/policy.ts');+ const { rankCoverageStatement } = await import('../engine-sql/graph-rank.ts');+ try {+ const versionTs = await effectiveLinkExtractorWatermark(ctx.engine);+ const policy = includeMentions ? await readMentionPolicy(ctx.engine) : null;+ const ids = sourceIds ?? (await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map(r => r.id);+ if (ids.length > COVERAGE_SOURCE_CAP) return { state: 'unread', reason: 'too_many_sources' };+ for (const sourceId of ids) {+ const mentionTypes = policy?.enabled ? linkableTypesFor(await loadSourcePack(ctx.engine, sourceId), policy) : undefined;+ const { text, params } = rankCoverageStatement({ sourceId, excludePrivate, versionTs, ...(mentionTypes ? { mentionTypes } : {}) });+ const [row] = await ctx.engine.executeRaw<{ link_behind: boolean; mention_due: boolean }>(text, params, { timeoutMs: 10_000 });+ if (row?.link_behind || row?.mention_due) return { state: 'behind' };+ }+ } catch {+ return { state: 'unread', reason: 'read_failed' };+ }+ return { state: 'current' };}async function attachDuplicates(ctx: OperationContext, rows: RankedEntity[], filter: EntityTypeFilter, excludePrivate: boolean): Promise<number> {@@ -198,7 +219,7 @@ const rank_entities: Operation = {inbound: Number(r.inbound), outbound: Number(r.outbound), neighbors: Number(r.neighbors), ...folded };});const duplicatesChecked = await attachDuplicates(ctx, entities, resolution.filter, excludePrivate);- const coverage = await readCoverage(ctx, sourceIds, params.includeMentions);+ const coverage = await readCoverage(ctx, sourceIds, params.includeMentions, excludePrivate);const notes: string[] = [];if (resolution.status === 'pack_unavailable') notes.push('The schema pack did not load, so no entity types are known: pass types explicitly, e.g. ["person"].');if (coverage.state === 'behind') notes.push('Link extraction is behind: counts cover only pages whose links are extracted (the brain host runs gbrain extract --stale to catch up).');diff --git a/test/rank-entities.test.ts b/test/rank-entities.test.tsindex 0b37b1e716..79e23c883c 100644--- a/test/rank-entities.test.ts+++ b/test/rank-entities.test.ts@@ -8,6 +8,7 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';import { operations, type OperationContext } from '../src/core/operations.ts';import { OperationError } from '../src/core/ops/contract.ts';import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { ALIAS_DERIVATION_VERSION, MENTION_EXTRACTOR_VERSION } from '../src/core/mentions/pass.ts';let engine: PGLiteEngine;@@ -222,6 +223,39 @@ describe('rank_entities remote visibility', () => {expect(Object.keys((await rank(local()) as any).coverage)).toContain('actionable');});+ test('pages the caller cannot read change local coverage and leave remote coverage current', async () => {+ await seedBase();+ const settle = async () => {+ await engine.executeRaw("UPDATE pages SET links_extracted_at = now() + interval '1 day'");+ await engine.executeRaw(`INSERT INTO page_mention_state (page_id, source_id, mention_revision, mention_version, alias_revision, alias_version)+ SELECT id, source_id, knowledge_revision, $1, knowledge_revision, $2 FROM pages ON CONFLICT (page_id) DO NOTHING`, [MENTION_EXTRACTOR_VERSION, ALIAS_DERIVATION_VERSION]);+ };+ await settle();+ const all = { source_id: '__all__' };+ const coverageOf = async (ctx: OperationContext, params: Record<string, unknown>) => (await rank(ctx, params) as any).coverage;+ for (const include_mentions of [false, true]) {+ expect((await coverageOf(ctxOf({ sourceId: '__all__' }), { ...all, include_mentions })).state).toBe('current');+ expect(await coverageOf(remote(), { include_mentions })).toEqual({ state: 'current' });+ }+ const cases: Array<[string, boolean, () => Promise<void>]> = [+ ['private page', true, () => page('notes/secret', 'note', 'source-a', { visibility: 'private' })],+ ['quarantined page', false, () => page('notes/quarantined', 'note', 'source-a', { quarantine: 'synthetic' })],+ ['foreign-source page', true, () => page('notes/foreign', 'note', 'source-b')],+ ];+ for (const [label, linkStale, seed] of cases) {+ await settle();+ await seed();+ const localState = async (include_mentions: boolean) => (await coverageOf(ctxOf({ sourceId: '__all__' }), { ...all, include_mentions })).state;+ expect({ label, links: await localState(false), mentions: await localState(true) })+ .toEqual({ label, links: linkStale ? 'behind' : 'current', mentions: 'behind' });+ for (const include_mentions of [false, true]) {+ expect({ label, include_mentions, coverage: await coverageOf(remote(), { include_mentions }) }).toEqual({ label, include_mentions, coverage: { state: 'current' } });+ }+ }+ await page('notes/readable', 'note');+ expect(await coverageOf(remote(), {})).toEqual({ state: 'behind' });+ });+test('a source outside the grant answers not_found', async () => {await seedBase();await expect(rank(remote(), { source_id: 'source-b' })).rejects.toMatchObject({ code: 'not_found' });