Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust-reads): eligibility policy, read floor in search arms and facts reads, trust labels on search/recall (#5575 A6, A7, ENG-8, ENG-14)
garrytan4489861ecc48
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 115b47f7d3..cc2353a1cb 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -67,6 +67,8 @@ const VETTED_BUILDERS: Record<string, string> = {privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',+ projectionEligibleSql: 'src/core/eligibility/sql.ts: read-eligibility predicate over a caller alias; splices only closed tier and reason-family vocabularies (no values)',+ pageEligibleSql: 'src/core/eligibility/sql.ts: page trust-floor and activation predicate over a caller alias; closed vocabularies only',relationshipFilterSql: 'src/core/link-validity.ts: relationship-state probe over a caller alias; dates pass isCalendarDate and inline as DATE literals, status/scope are literals',};diff --git a/src/core/eligibility/sql.ts b/src/core/eligibility/sql.tsindex 9647e7281f..52400562cc 100644--- a/src/core/eligibility/sql.ts+++ b/src/core/eligibility/sql.ts@@ -59,9 +59,24 @@ export function activationSuppressedSql(table: EligibilityTable, alias: string):AND elig_r.verdict = 'flag' AND elig_r.reason_families && ARRAY[${ACTIVATION_REASON_FAMILIES.map(f => `'${f}'`).join(',')}]::text[]))`;}-/** The whole row predicate for one projection table under a policy. Always hides quarantined-page projections. */+/**+ * A row a purge hid because one of its derivation inputs was purged+ * (`needs_rederive`, written by facts/derivation-inputs.ts) never surfaces,+ * even on reads that include expired or inactive rows, until a deriver+ * regenerates it.+ */+export function rederiveHiddenSql(table: EligibilityTable, alias: string): string {+ return `NOT EXISTS (SELECT 1 FROM needs_rederive elig_nr WHERE elig_nr.derived_table = '${table}' AND elig_nr.derived_id = ${alias}.id::text)`;+}++/**+ * The whole row predicate for one projection table under a policy. Always+ * hides quarantined-page projections and rows awaiting re-derivation.+ * Gate holds never reach these tables (write_gate_holds) and purged rows are+ * deleted, so neither needs a clause here.+ */export function projectionEligibleSql(table: Exclude<EligibilityTable, 'pages'>, alias: string, policy: ReadEligibility | undefined): string {- const clauses = [quarantinedProjectionHiddenSql(table, alias)];+ const clauses = [quarantinedProjectionHiddenSql(table, alias), rederiveHiddenSql(table, alias)];if (policy?.floor) clauses.push(trustFloorSql(alias, policy.floor));if (policy?.suppressFlagged) clauses.push(`NOT ${activationSuppressedSql(table, alias)}`);return clauses.join(' AND ');diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex e242bba508..f82d755d75 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -26,6 +26,8 @@ import type { SqlExecutor } from './executor.ts';import type { LegacyUnscopedRead } from './brands.ts';import { sqlFragment, trustedSql } from './fragment.ts';import { compileRowNormalizer } from './normalize.ts';+import { projectionEligibleSql } from '../eligibility/sql.ts';+import { storedTrustTier } from '../trust/tier.ts';export type EmbeddingCast = '::vector' | '::halfvec';@@ -46,6 +48,11 @@ async function embeddingCast(exec: SqlExecutor, probe: ResolveEmbeddingCast | un* silently misses matches outside the newest-N window on high-cardinality* entities. Parity with the pglite engine's `_listFacts`.*/+/** #5575: the read-eligibility predicate for list reads that pass a policy (eligibility/sql.ts). */+function eligibilityClause(opts: FactListOpts | undefined) {+ return opts?.eligibility ? sqlFragment`AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``;+}+function grepPattern(opts: FactListOpts | undefined): string | null {return (opts?.grep && opts.grep.trim()) ? '%' + escapeLikePattern(opts.grep.trim()) + '%' : null;}@@ -359,6 +366,7 @@ export async function listFactsByEntity(${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}+ ${eligibilityClause(opts)}ORDER BY valid_from DESC, id DESCLIMIT ${limit} OFFSET ${offset}`)).rows;@@ -394,6 +402,7 @@ export async function listFactsSince(${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}+ ${eligibilityClause(opts)}ORDER BY ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} DESC, id DESCLIMIT ${limit} OFFSET ${offset}`)).rows;@@ -433,6 +442,7 @@ export async function listFactsKeyset(${afterCondition}${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}+ ${eligibilityClause(opts)}ORDER BY created_at ASC, id ASCLIMIT ${limit}`)).rows;@@ -463,6 +473,7 @@ export async function listFactsBySession(${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}+ ${eligibilityClause(opts)}ORDER BY created_at DESC, id DESCLIMIT ${limit} OFFSET ${offset}`)).rows;@@ -472,7 +483,7 @@ export async function listFactsBySession(export async function listSupersessions(exec: LegacyUnscopedRead,source_id: string,- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('../engine.ts').FactListOpts['eligibility'] },): Promise<FactRow[]> {const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);const since = opts?.since ?? null;@@ -489,6 +500,7 @@ export async function listSupersessions(AND superseded_by IS NOT NULL${since ? sqlFragment`AND COALESCE(expired_at, valid_until) >= ${since}` : sqlFragment``}${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}+ ${opts?.eligibility ? sqlFragment`AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``}ORDER BY COALESCE(expired_at, valid_until) DESC, id DESCLIMIT ${limit}`)).rows;@@ -703,6 +715,13 @@ interface FactRowSqlShape {fact_fingerprint?: string | null;created_at_iso?: string | null;attributed_to?: FactAttribution | null;+ trust_tier?: string | null;+ write_origin?: unknown;+}++function originRecord(value: unknown): Record<string, unknown> | null {+ const parsed = typeof value === 'string' ? (() => { try { return JSON.parse(value) as unknown; } catch { return null; } })() : value;+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;}/**@@ -757,6 +776,8 @@ function rowToFact(raw: FactRowSqlShape): FactRow {...(row.fact_fingerprint ? { fact_fingerprint: row.fact_fingerprint } : {}),...(row.created_at_iso ? { created_at_iso: row.created_at_iso } : {}),...(row.attributed_to ? { attributed_to: row.attributed_to } : {}),+ ...(row.trust_tier ? { trust_tier: storedTrustTier(row.trust_tier) } : {}),+ ...(row.write_origin !== undefined ? { write_origin: originRecord(row.write_origin) } : {}),};}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 8727b02ff7..00d47c4ad2 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -542,6 +542,9 @@ export interface FactRow {created_at_iso?: string;/** Who asserted the claim (migration v215); null when attribution is unavailable. */attributed_to?: FactAttribution | null;+ /** #5575: the stored trust tier and write origin (absent on brains before the trust migration). */+ trust_tier?: import('./trust/tier.ts').TrustTier;+ write_origin?: Record<string, unknown> | null;}/**@@ -652,6 +655,8 @@ export interface FactListOpts {excludeAuditRows?: boolean;/** #5888: listFactsSince/listFactsBySession also select `gbrain_fact_fingerprint(fact)` as `fact_fingerprint`. */fingerprint?: boolean;+ /** #5575 read eligibility (eligibility/sql.ts): read floor, quarantined-page and needs_rederive hiding, proactive suppression. Unset for internal writers. */+ eligibility?: import('./eligibility/policy.ts').ReadEligibility;}/** Per-source operational health snapshot consumed by `gbrain doctor`. */@@ -2254,7 +2259,7 @@ export interface BrainEngine {*/listSupersessions(source_id: string,- opts?: { since?: Date; limit?: number; visibility?: FactVisibility[] },+ opts?: { since?: Date; limit?: number; visibility?: FactVisibility[]; eligibility?: FactListOpts['eligibility'] },): Promise<FactRow[]>;/**diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 632ba4c2a0..efe842fcfe 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -38,6 +38,10 @@ import { parseTtlShorthand } from '../facts/ttl-parse.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';import type { SearchResult } from '../types.ts';import type { BrainEngine, FactRow } from '../engine.ts';+import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';+import { stampPageTrust } from '../eligibility/stamp.ts';+import { trustFields } from '../eligibility/labels.ts';+import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';// ============================================================@@ -225,6 +229,7 @@ const recall: Operation = {include_pending: { type: 'boolean', description: 'Add pending count.' },return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: 'Evidence unit for results[] (see search).' },return_window: { type: 'number', description: 'Window size 1-3.' },+ min_trust: MIN_TRUST_PARAM,},scope: 'read',verb: true,@@ -275,6 +280,9 @@ const recall: Operation = {ctx.remote === false? undefined: ['world'] as ('private' | 'world')[];+ // #5575: read floor (token floor, min_trust, read policy) plus the+ // quarantined-page and needs_rederive hiding, applied in each arm's SQL.+ const eligibility = await resolveReadEligibility(ctx, { minTrust: p.min_trust });type FactRows = Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>;type FactRowItem = FactRows[number];@@ -330,6 +338,7 @@ const recall: Operation = {visibility,grep: grep ?? undefined,excludeAuditRows: true,+ eligibility,};if (p.supersessions === true) {@@ -338,7 +347,7 @@ const recall: Operation = {// private newest row consume a limit slot and hide an older world row.rows = mergeNewest(await Promise.all(factSources.map(src =>- ctx.engine.listSupersessions(src, { since: since ?? undefined, limit, visibility }),+ ctx.engine.listSupersessions(src, { since: since ?? undefined, limit, visibility, eligibility }),)),// v0.46 (#3014): matches the engine's ORDER BY COALESCE(expired_at,// valid_until) — ontology supersessions carry valid_until only.@@ -440,7 +449,7 @@ const recall: Operation = {// like search/query/get_page/list_pages/resolve_slugs. sourceScopeOpts// alone pinned this arm to the scalar source, so a `federated: true`// source was invisible to recall while visible to every sibling read op.- const searchScope = federatedSearchScope(ctx, sourceIdParam);+ const searchScope = { ...federatedSearchScope(ctx, sourceIdParam), ...(eligibility.floor ? { minTrust: eligibility.floor } : {}) };// #4352 — recall's page-search arm enforces `visibility: private` for// untrusted callers (matches the facts arms' world-only filter above).const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');@@ -462,6 +471,7 @@ const recall: Operation = {bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));const applied = effectivePlan(evidencePlan, searchResults);if (applied) ({ results: searchResults, delivery } = await deliverEvidence(ctx.engine, searchResults, applied, { ...searchScope, excludePrivate, requireSafeChunks: ctx.remote !== false }));+ searchResults = await stampPageTrust(ctx.engine, searchResults, eligibility.floor);}// Pack what is delivered: results redacted for all; facts for remote only (localVerbatim).@@ -545,6 +555,7 @@ const recall: Operation = {// is the protocol name for the stored source attribution.fact_id: String(r.id),provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),+ ...trustFields(r.trust_tier, r.write_origin),})),total: packedFacts.length,...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),@@ -562,6 +573,7 @@ const recall: Operation = {provenance: r.slug,...(r.delivered ? { delivered: r.delivered } : {}),...(r.relational ? { relational: r.relational } : {}),+ ...(r.trust_tier ? { trust_tier: r.trust_tier, origin: r.origin } : {}),})),...(searchDegraded ? { search_degraded: searchDegraded } : {}),...(searchDegraded ? {} : await searchAnswerFeedback(ctx, 'recall', packedResults)),@@ -1266,7 +1278,7 @@ async function recallKeywordOnlyReason(ctx: OperationContext): Promise<string |*/async function keylessRecallRows(ctx: OperationContext, queryText: string, limit: number, excludePrivate: boolean,- searchScope: { sourceId?: string; sourceIds?: string[] },+ searchScope: { sourceId?: string; sourceIds?: string[]; minTrust?: TrustTier },): Promise<SearchResult[]> {if (await keylessChainQuestion(ctx, queryText)) {return hybridSearchCached(ctx.engine, queryText, {diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex d073d63031..9e430acec8 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2429,7 +2429,7 @@ export class PGLiteEngine implements BrainEngine {async listSupersessions(source_id: string,- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility'] },): Promise<FactRow[]> {return factsImpl.listSupersessions(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, opts);}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d92ca200f5..8e28ffbe52 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -2166,7 +2166,7 @@ export class PostgresEngine implements BrainEngine {async listSupersessions(source_id: string,- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility'] },): Promise<FactRow[]> {return factsImpl.listSupersessions(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, opts);}