Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(access): keep the vector arm for members; statistics-led access predicate (GBRA-218)
garrytan0516ce4a698d
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 6a76dd6a7d..f77752e30f 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originRestrictedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). The readers tests use `frontmatter ? 'readable_by'`, never `->'readable_by' IS NULL`, whose row estimate (1) sent restricted vector searches into nested-loop sequential scans. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`.+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`.- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/scripts/bench-member-access.ts b/scripts/bench-member-access.tsindex 81e9ff0a2b..168e7d1813 100644--- a/scripts/bench-member-access.ts+++ b/scripts/bench-member-access.ts@@ -26,6 +26,7 @@ const arg = (name: string, def: number) => { const i = process.argv.indexOf(nameconst PAGES = arg('--pages', 5000);const QUERIES = arg('--queries', 60);const JSON_MODE = process.argv.includes('--json');+const SHARES = (process.argv.includes('--shares') ? process.argv[process.argv.indexOf('--shares') + 1] : '0,0.2,0.8').split(',').map(Number);const DIMS = 1536;const SRC = 'bench-src';const SYLLABLES = 'ba ce di fo gu ha je ki lo mu na pe qi ro su ta ve wi xo yu za'.split(' ');@@ -88,7 +89,9 @@ async function runCell(share: number) {const t0 = performance.now();const out = await dispatchToolCall(engine, 'search', params, { remote: true, transport: 'http', auth, sourceId,takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'], ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });- return { ms: performance.now() - t0, text: out.content.map(c => c.text).join('\n') };+ const text = out.content.map(c => c.text).join('\n');+ if (out.isError || text.includes('vector_arm_failed')) throw new Error(`bench search degraded or failed: ${text.slice(0, 300)}`);+ return { ms: performance.now() - t0, text };}const slugsIn = (text: string) => [...new Set(text.match(/notes\/page-\d+/g) ?? [])];@@ -127,7 +130,7 @@ async function runCell(share: number) {configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'bench' } });__setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);const all: Record<string, unknown>[] = [];-for (const share of [0, 0.2, 0.8]) {+for (const share of SHARES) {const cells = await runCell(share);if (cells) all.push(...cells);}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 582cd6db13..928136fbd2 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -63,13 +63,13 @@ function privacyPartSql(pageAlias: string): string {* (`member:<id>` and its `group:<g>` entries) meets them, through the one SQL* normalization gbrain_access_readers() (malformed values read as nobody). A* page derived from a page that names readers is readable by no remote caller- * (originRestrictedSql). No escape hatch, operator opt-out or granted source+ * (originAllowedSql). No escape hatch, operator opt-out or granted source* relaxes this part; with an empty identity it hides every restricted page.* `identity` must pass validIdentity (its alphabet has no quote), so it is* embedded as literals; anything else empties it (fail closed).*/export function accessAllowedSql(pageAlias: string, identity: readonly string[]): string {- return `(${readersAllowedSql(pageAlias, identity)} AND NOT ${originRestrictedSql(pageAlias)})`;+ return `(${readersAllowedSql(pageAlias, identity)} AND ${originAllowedSql(pageAlias)})`;}/**@@ -84,7 +84,8 @@ export function readersAllowedSql(alias: string, identity: readonly string[], roconst ids = identity.length && validIdentity(identity) ? identity : [];const readers = row === 'page' ? `${alias}.page_readers` : `gbrain_access_readers(${alias}.frontmatter)`;const listed = ids.length ? ` OR ${readers} && ARRAY[${ids.map(id => `'${id}'`).join(', ')}]::text[]` : '';- return `(NOT (${alias}.frontmatter ? 'readable_by')${listed})`;+ const none = row === 'page' ? `(${alias}.page_readers IS NULL AND NOT (${alias}.frontmatter ? 'readable_by'))` : `NOT (${alias}.frontmatter ? 'readable_by')`;+ return `(${none}${listed})`;}/** A page names readers (valid or not); SQL twin of hasReaders. */@@ -101,11 +102,13 @@ function namesReadersSql(alias: string): string {* the origin gained readers are covered; new derivations are stamped private* by isDerivationPrivate. The lineage test lives in the SQL function* gbrain_access_origin_restricted (migration v274) behind a cheap type and- * key guard, so a read plans one function call instead of four subplans.+ * key guard, so a read plans one function call instead of four subplans. Both+ * parts lead with column tests (page_readers IS NULL, type) so the planner's+ * row estimate follows column statistics instead of a default guess.*/-function originRestrictedSql(p: string): string {- return `(CASE WHEN ${p}.type IN ('atom', 'question', 'concept', 'event') OR ${p}.frontmatter ? 'derived_from'- THEN gbrain_access_origin_restricted(${p}.id, ${p}.source_id, ${p}.type, ${p}.frontmatter) ELSE false END)`;+function originAllowedSql(p: string): string {+ return `((${p}.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (${p}.frontmatter ? 'derived_from'))+ OR NOT gbrain_access_origin_restricted(${p}.id, ${p}.source_id, ${p}.type, ${p}.frontmatter))`;}/**diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 589b9de18d..91fa1dd46f 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -113,7 +113,7 @@ export interface VectorSearchStatement {* of the probe (a segmented page has no body string).*/export const INDEX_WALK_PAGE_COLUMNS = ['id', 'slug', 'source_id', 'title', 'type', 'frontmatter', 'deleted_at', 'updated_at', 'effective_date',- 'effective_date_source', 'trust_tier', 'body_generation', 'chunker_version', 'knowledge_revision', 'text_projection_revision'] as const;+ 'effective_date_source', 'trust_tier', 'body_generation', 'chunker_version', 'knowledge_revision', 'text_projection_revision', 'page_readers'] as const;/** Raw rows the index walk orders per window slot, so page filters can drop some and still fill the window. */export const INDEX_WALK_OVERFETCH = 2;diff --git a/test/member-read-access.test.ts b/test/member-read-access.test.tsindex 9507709c0c..c8a5d269e2 100644--- a/test/member-read-access.test.ts+++ b/test/member-read-access.test.ts@@ -227,6 +227,13 @@ for (const kind of testBackends()) {for (const label of CORE) expect({ label, keys: bob[label] }).toEqual({ label, keys: ['team'] });}, 240_000);+ test('a member\'s hybrid search keeps its vector arm (the index walk projects page_readers)', async () => {+ for (const who of ['alice', 'bob', 'unbound']) {+ const { isError, text } = await call(who, 'search', { query: 'harbor ledger planning notes', fields: 'full', limit: 20 });+ expect({ who, isError, armFailed: text.includes('vector_arm_failed') }).toEqual({ who, isError: false, armFailed: false });+ }+ }, 240_000);+test('readers never relax visibility: private; a private_pages grant opens it to a listed member only', async () => {expect(Object.values(await visibleTo('alice', ['privateAlice'])).flat()).toEqual([]);const granted = await visibleTo('alice-granted', ['privateAlice']);diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 656e674bff..140e1fe0a2 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -11,6 +11,7 @@ import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, INDEX_WALK_PAGEimport { _resetVectorLegacyGuardForTests, readVectorLegacyGuard, resolveVectorLegacyGuard } from '../../src/core/search/vector-legacy-guard.ts';import { withEnv } from '../helpers/with-env.ts';import { TRUST_TIERS } from '../../src/core/trust/tier.ts';+import { withCallerAccess } from '../../src/core/search/private-visibility.ts';const MD5 = 'md5(cc.chunk_text)';const indexedColumn = { name: 'embedding', type: 'vector' as const, dimensions: 1536, embeddingModel: 'openai:text-embedding-3-large' };@@ -130,8 +131,8 @@ describe('vector index walk statement', () => {{ exclude_slug_prefixes: ['x/'] }, { include_slug_prefixes: ['y/'] }, { detail: 'low' as const }, { language: 'typescript', symbolKind: 'function' }, { minTrust: TRUST_TIERS[TRUST_TIERS.length - 1] }, { suppressFlagged: true },{ excludePrivate: true, sourceIds: ['a', 'b'], exclude_slug_prefixes: ['x/'], detail: 'low' as const }];const read = new Set<string>();- for (const dialect of ['postgres', 'pglite'] as const) for (const v of variants) {- const walk = build(v, dialect).indexWalkSql!;+ for (const dialect of ['postgres', 'pglite'] as const) for (const v of variants) for (const identity of [[], ['member:alice-example', 'group:team-a']]) {+ const walk = withCallerAccess({ identity, hidePrivate: true, applyRemoteReadPolicy: true }, () => build(v, dialect).indexWalkSql!);const candidates = walk.slice(walk.indexOf('hnsw_candidates AS ('), walk.indexOf('ORDER BY ann.distance'));for (const m of candidates.matchAll(/\bp\.(\w+)/g)) read.add(m[1]!);}@@ -229,7 +230,10 @@ describe('source scope strategy: walk overfetch, walk skip and scope scan', () =const stmt = build({ sourceIds: ['a'], exclude_slugs: ['x'], language: 'typescript', detail: 'low', excludePrivate: true, type: 'note' }, 'postgres', 0.01, 500);const scan = stmt.scopeScanSql!;const cte = scan.slice(scan.indexOf('WITH scope_scan AS MATERIALIZED ('), scan.indexOf('hnsw_candidates AS ('));- const pagesSubquery = cte.slice(cte.indexOf('ANY(ARRAY('), cte.indexOf('))'));+ const open = cte.indexOf('ANY(ARRAY(');+ let close = open + 'ANY('.length;+ for (let depth = 0; close < cte.length; close++) if (cte[close] === '(') depth++; else if (cte[close] === ')' && --depth === 0) break;+ const pagesSubquery = cte.slice(open, close);expect(cte).toContain('SELECT cc.id\n FROM content_chunks cc\n WHERE cc.page_id = ANY(ARRAY(');for (const filter of ['AND p.type = $2', 'AND p.slug != ALL($3::text[])', 'AND p.source_id = ANY($5::text[])', `COALESCE(p.frontmatter->>'visibility'`, "AND NOT (p.slug LIKE 'test/%'"]) {expect(pagesSubquery).toContain(filter);