Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(privacy): semantic cache key carries the private-readable set; subject inference keeps the plain predicate (GBRA-156)
garrytan4467ed9c7d7a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex db6c8efd29..e65aea211a 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -41,7 +41,7 @@ src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlistedsrc/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)-src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)+src/core/search/mode.ts 1709 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156: append-only xpr= knobsHash part (private-readable set)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex ca97ea8375..a6bb9e484f 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -30,7 +30,7 @@ import { slugifySegment } from '../sync.ts';const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonical = async (...args) =>(await import('../mentions/siblings.ts')).siblingCanonical(...args);import { isMissingSchemaObject } from '../utils.ts';-import { privatePagesFilterForCaller } from '../search/private-visibility.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { rankingLinkSql } from '../link-ranking-policy.ts';/**@@ -490,7 +490,7 @@ export async function resolveStrictEntityReference(): Promise<StrictResolution> {const trimmed = raw.trim();if (!trimmed) return { slug: null, miss: 'no_page' };- const privacy = opts.excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';const live = async (slugs: string[]) => slugs.length === 0 ? [] : engine.executeRaw<{ slug: string; type: string | null }>(`SELECT p.slug, p.type FROM pages pWHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug = ANY($2::text[]) ${privacy}`,@@ -572,7 +572,7 @@ export async function entityReferenceCandidates(const trimmed = raw.trim();const token = slugify(trimmed);if (!token) return [];- const privacy = opts.excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';const aliases = await aliasHitSlugs(engine, source_id, trimmed).catch(() => [] as string[]);const prefixed = (await findPrefixCandidates(engine, source_id, token)).map(c => c.slug);const named = await engine.executeRaw<{ slug: string }>(diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.tsindex 5a50e1c22b..07a16b599f 100644--- a/src/core/facts/subject-infer.ts+++ b/src/core/facts/subject-infer.ts@@ -24,7 +24,7 @@import type { BrainEngine } from '../engine.ts';import { extractCandidates, isCommonCapitalizedWord } from '../context/entity-salience.ts';import { isFactEntityPage, resolveStrictEntityReference, type StrictResolution } from '../entities/resolve.ts';-import { privatePagesFilterForCaller } from '../search/private-visibility.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';export type InferredVia = 'page' | 'mention';export type InferMissReason = 'ambiguous' | 'unverified_match' | 'no_mention' | 'no_page';@@ -224,7 +224,7 @@ function onlyExampleUses(fact: string, query: string): boolean {}async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {- const privacy = excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';+ const privacy = excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';const [row] = await engine.executeRaw<{ slug: string; type: string | null }>(`SELECT p.slug, p.type FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL ${privacy} LIMIT 1`,[sourceId, slug],diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 341f038a1f..1e0b51ef0a 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -27,6 +27,7 @@ import { normalizeChainSlots } from './relational-chain.ts';import { createHash } from 'crypto';import { CR_MODES, type CRMode } from '../types.ts';import { getFtsLanguage } from '../fts-language.ts';+import { privateReadableSources } from './private-visibility.ts';import { loadConfigSnapshot, type BulkConfigReader } from '../config-snapshot.ts';import { pickDecideConfig } from '../ai/decide/config.ts';import { getRecipe } from '../ai/recipes/index.ts';@@ -1300,6 +1301,10 @@ export function knobsHash(// #5691 (append-only, no version bump): only a non-empty query prefix adds// a part, so every row written without one keeps its key.if (ctx?.queryPrefix) parts.push(`qp=${createHash('sha256').update(ctx.queryPrefix).digest('hex').slice(0, 16)}`);+ // GBRA-156 (append-only, no bump): a read granted private pages keys on its sorted private-readable+ // set (read here so every knobsHash() caller is covered); an empty set adds no part and keeps the key.+ const privateReadable = ctx?.excludePrivate === true ? privateReadableSources() : [];+ if (privateReadable.length) parts.push(`xpr=${[...privateReadable].sort().join(',')}`);const h = createHash('sha256');h.update(parts.join('|'));return h.digest('hex').slice(0, 16);diff --git a/test/private-pages-grant.test.ts b/test/private-pages-grant.test.tsindex e8ee028885..40a6038606 100644--- a/test/private-pages-grant.test.ts+++ b/test/private-pages-grant.test.ts@@ -32,7 +32,11 @@ import { parseClientRescopeArgs } from '../src/core/grants/cli.ts';import { readClientGrant, rescopeClientGrant } from '../src/core/grants/service.ts';import { noGrantFederatedScope } from '../src/core/source-resolver.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';-import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { __resetPrivateVisibilityCacheForTests, withPrivateReadableSources } from '../src/core/search/private-visibility.ts';+import { SemanticQueryCache } from '../src/core/search/query-cache.ts';+import { prepareSemanticCache, resolveCacheSearchMode } from '../src/core/search/hybrid/cache-stages.ts';+import { cacheScopeKey } from '../src/core/search/hybrid.ts';+import type { HybridSearchMeta, SearchResult } from '../src/core/types.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -262,6 +266,34 @@ for (const kind of testBackends()) {expect((await call(tokens['alice-example'], 'get_page', { slug: PRIVATE_SLUG })).text).toContain(SECRET[ALICE]);}, 120_000);+ test('the semantic result cache keys on the private-readable set: a granted caller\'s stored private result never serves an ungranted caller with the same scope and query', async () => {+ const query = 'renewal thoughts for the quarter';+ const opts = { excludePrivate: true, sourceIds: [ALICE, TEAM] };+ const scope = cacheScopeKey(opts);+ const [{ atttypmod: dims }] = await engine.executeRaw<{ atttypmod: number }>(+ "SELECT atttypmod FROM pg_attribute WHERE attrelid = 'query_cache'::regclass AND attname = 'embedding'");+ const embedding = new Float32Array(dims).fill(1 / Math.sqrt(dims));+ const keyFor = async () => {+ const { resolvedForCache, knobsHash } = await resolveCacheSearchMode(engine, opts);+ return (await prepareSemanticCache(engine, query, opts, resolvedForCache, knobsHash)).cacheKnobsHash;+ };+ const granted = await withPrivateReadableSources([ALICE, TEAM], keyFor);+ const ungranted = await keyFor();+ const cache = new SemanticQueryCache(engine, { enabled: true });+ const row = { slug: PRIVATE_SLUG, page_id: 1, title: 'Renewal thoughts', type: 'note', chunk_text: SECRET[ALICE], chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0, score: 1, stale: false, source_id: ALICE } as SearchResult;+ await engine.executeRaw('DELETE FROM query_cache');+ try {+ await cache.store(query, embedding, [row], { vector_enabled: true, detail_resolved: 'medium', expansion_applied: false, intent: 'general' } as HybridSearchMeta, { sourceId: scope, knobsHash: granted });+ expect((await cache.lookup(embedding, { sourceId: scope, knobsHash: granted, queryText: query })).hit).toBe(true);+ const served = await cache.lookup(embedding, { sourceId: scope, knobsHash: ungranted, queryText: query });+ expect({ hit: served.hit, leaked: JSON.stringify(served).includes(SECRET[ALICE]) }).toEqual({ hit: false, leaked: false });+ expect(await withPrivateReadableSources([], keyFor)).toBe(ungranted);+ expect(await withPrivateReadableSources([TEAM, ALICE], keyFor)).toBe(granted);+ } finally {+ await engine.executeRaw('DELETE FROM query_cache');+ }+ });+test('concurrent calls from two members never cross', async () => {const calls: Array<Promise<void>> = [];for (let round = 0; round < 6; round++) {