Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: apply the private-provenance filter to remote fact list reads

garrytanedb0d8e9b99a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0aa5303372..7e81a8ef59 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A visibility filter fix for remote fact reads.**
+
+This release ships a visibility filter fix for remote fact reads. Reads from the trusted local CLI are unchanged, and nothing needs doing after you upgrade.
+
+### Itemized changes
+
+- A visibility filter fix for remote fact reads (`FactListOpts.excludePrivate`, `TrajectoryOpts.excludePrivate`).
+
+### For contributors
+
+- `test/remote-fact-list-private-provenance.test.ts` covers the fix on PGLite, and on Postgres through `test/e2e/remote-fact-list-private-provenance-postgres.test.ts`.
+
## [0.60.149.0] - 2026-10-10
**A keyword search from an MCP or other remote caller that hits a common term now takes about 0.2 s of database time on a 50k-page Postgres brain instead of about 1 s. Full `gbrain doctor` is 1.4–1.6 s faster at 50k on both engines. Import issues about 6% fewer statements per page. Results, doctor output and imported content are unchanged.**
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index c30d607cb9..ba23e36bf1 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -54,7 +54,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` is on in every mode unless explicitly disabled, 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. Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
+- `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 (`source_markdown_slug`) is private; the fact-list reads in `engine-sql/facts.ts` (by entity, since, keyset, session, supersessions, trajectory) apply it behind `FactListOpts.excludePrivate` / `TrajectoryOpts.excludePrivate`, which every remote fact surface resolves with `resolveExcludePrivatePages` (`test/remote-fact-list-private-provenance.test.ts`, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index cc2353a1cb..035cb2e399 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -65,6 +65,7 @@ const VETTED_BUILDERS: Record<string, string> = {
privateLinkOriginFilterFragment: 'src/core/search/private-visibility.ts: constant link-origin visibility predicate over a caller alias',
privateTimelineEventFilterFragment: 'src/core/search/private-visibility.ts: constant timeline-event visibility predicate over a caller alias',
privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',
+ privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance 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)',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4d90649045..5e4871803e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 514 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3293 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts)
src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
-src/core/engine.ts 2751 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts)
+src/core/engine.ts 2755 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move)
src/core/import-file.ts 2049 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 342 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index eab37c6217..83eb269aad 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -733,10 +733,12 @@ async function assembleDelta(
try {
const after = opts.factsAfter ?? (since ? { at: since, id: null } : null);
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(engine, remote ? undefined : false);
const rows = await engine.listFactsKeyset(
opts.sourceId,
after ? { createdAt: after.at, id: after.id } : null,
- { activeOnly: true, limit: DELTA_FACT_FETCH_LIMIT + 1, visibility, fingerprint: true, eligibility: { floor: policy.floor } },
+ { activeOnly: true, limit: DELTA_FACT_FETCH_LIMIT + 1, visibility, excludePrivate, fingerprint: true, eligibility: { floor: policy.floor } },
);
const kept = rows.slice(0, DELTA_FACT_FETCH_LIMIT);
const probe = rows.length > DELTA_FACT_FETCH_LIMIT ? rows[DELTA_FACT_FETCH_LIMIT] : null;
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 8f7d76bee6..cc3a7ebc99 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -27,6 +27,7 @@ import type { LegacyUnscopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
import { compileRowNormalizer } from './normalize.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
import { storedTrustTier } from '../trust/tier.ts';
export type EmbeddingCast = '::vector' | '::halfvec';
@@ -53,6 +54,10 @@ function eligibilityClause(opts: FactListOpts | undefined) {
return opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``;
}
+function privacyClause(opts: { excludePrivate?: boolean } | undefined) {
+ return opts?.excludePrivate ? sqlFragment` AND ${trustedSql(privateProvenanceFilterFragment('facts'))}` : sqlFragment``;
+}
+
function grepPattern(opts: FactListOpts | undefined): string | null {
return (opts?.grep && opts.grep.trim()) ? '%' + escapeLikePattern(opts.grep.trim()) + '%' : null;
}
@@ -363,7 +368,7 @@ export async function listFactsByEntity(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
${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 DESC
@@ -398,7 +403,7 @@ export async function listFactsSince(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
${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 DESC
@@ -439,7 +444,7 @@ export async function listFactsKeyset(
WHERE source_id = ${source_id}
${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)}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${eligibilityClause(opts)}
ORDER BY created_at ASC, id ASC
LIMIT ${limit}
`)).rows;
@@ -467,7 +472,7 @@ export async function listFactsBySession(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
${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 DESC
@@ -479,7 +484,7 @@ export async function listFactsBySession(
export async function listSupersessions(
exec: LegacyUnscopedRead,
source_id: string,
- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('../engine.ts').FactListOpts['eligibility'] },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('../engine.ts').FactListOpts['eligibility']; excludePrivate?: boolean },
): Promise<FactRow[]> {
const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
const since = opts?.since ?? null;
@@ -495,7 +500,7 @@ export async function listSupersessions(
WHERE source_id = ${source_id}
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``}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``}
ORDER BY COALESCE(expired_at, valid_until) DESC, id DESC
LIMIT ${limit}
`)).rows;
@@ -612,7 +617,7 @@ export async function findTrajectory(exec: LegacyUnscopedRead, opts: import('../
WHERE ${useArray ? sqlFragment`source_id = ANY(${sourceIds}::text[])` : sqlFragment`source_id = ${sourceId}`}
AND entity_slug = ${opts.entitySlug}
AND expired_at IS NULL
- ${remoteFilter ? sqlFragment`AND visibility = 'world'` : sqlFragment``}
+ ${remoteFilter ? sqlFragment`AND visibility = 'world'` : sqlFragment``}${privacyClause(opts)}
${metric !== null ? sqlFragment`AND claim_metric = ${metric}` : sqlFragment``}
${kind === 'metric' ? sqlFragment`AND claim_metric IS NOT NULL` : sqlFragment``}
${kind === 'event' ? sqlFragment`AND event_type IS NOT NULL` : sqlFragment``}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 8911820503..58486934e3 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -660,6 +660,8 @@ export interface FactListOpts {
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;
+ /** Hide facts whose provenance page (`source_markdown_slug`) is private. Resolved by the trusted operation layer (resolveExcludePrivatePages), never from MCP parameters. */
+ excludePrivate?: boolean;
}
/** Per-source operational health snapshot consumed by `gbrain doctor`. */
@@ -703,6 +705,8 @@ export interface TrajectoryOpts {
* `remote: false` explicitly.
*/
remote?: boolean;
+ /** Same as FactListOpts.excludePrivate: hide points whose provenance page is private. */
+ excludePrivate?: boolean;
/** Metric filter. When set, only facts with this canonical metric label participate. */
metric?: string;
/**
@@ -2272,7 +2276,7 @@ export interface BrainEngine {
*/
listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number; visibility?: FactVisibility[]; eligibility?: FactListOpts['eligibility'] },
+ opts?: { since?: Date; limit?: number; visibility?: FactVisibility[]; eligibility?: FactListOpts['eligibility']; excludePrivate?: boolean },
): Promise<FactRow[]>;
/**
diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.ts
index 40ee5bbe69..3f23507c04 100644
--- a/src/core/facts/meta-hook.ts
+++ b/src/core/facts/meta-hook.ts
@@ -38,6 +38,7 @@ import { proactiveEligibility } from '../eligibility/registry.ts';
import { partitionForActivation, suppressionSummary } from '../eligibility/activation.ts';
import { trustFields } from '../eligibility/labels.ts';
import { eligibilityCacheField, readTrustGeneration } from '../eligibility/generation.ts';
+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
const DEFAULT_TTL_MS = 30_000;
const DEFAULT_TOP_K = 10;
@@ -135,7 +136,10 @@ export async function getBrainHotMemoryMeta(
// private included) warms the cache and a later remote/world-only call with
// the same source+session+allowList is SERVED the private payload — a
// cross-tier leak through the cache, not through the query.
- const tier = ctx.remote === false ? 'all' : 'world';
+ // The operator opt-out (search.remote_private_pages) changes what a world
+ // read returns, so it is part of the tier too.
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const tier = ctx.remote === false ? 'all' : excludePrivate ? 'world' : 'world+private-pages';
// encodeCacheField (F5): source_id / session_id are caller-controlled and
// may contain the '::' delimiter; percent-encode ':' so bumpHotMemoryCache's
// split('::') can never mis-slice a component.
@@ -191,13 +195,13 @@ export async function getBrainHotMemoryMeta(
let fetched: FactRow[] = [];
if (sessionId) {
fetched = await ctx.engine.listFactsBySession(sourceId, sessionId, {
- activeOnly: true, limit: topK * 3, visibility, fingerprint: true, eligibility,
+ activeOnly: true, limit: topK * 3, visibility, excludePrivate, fingerprint: true, eligibility,
});
}
// If no session-scoped rows, fall back to recent across the source.
if (fetched.length === 0) {
fetched = await ctx.engine.listFactsSince(sourceId, new Date(Date.now() - 24 * 60 * 60 * 1000), {
- activeOnly: true, limit: topK * 3, visibility, fingerprint: true, eligibility,
+ activeOnly: true, limit: topK * 3, visibility, excludePrivate, fingerprint: true, eligibility,
});
}
if (fetched.length === 0) {
diff --git a/src/core/ops/attribution.ts b/src/core/ops/attribution.ts
index 7456a41096..70dc363268 100644
--- a/src/core/ops/attribution.ts
+++ b/src/core/ops/attribution.ts
@@ -18,6 +18,7 @@ import type { McpCall } from '../agent-output.ts';
import { opTransport, paramUse, readFix } from './op-fix.ts';
import { readHolders, readPolicyOpts } from './context.ts';
import { storedTrustTier, type TrustTier, type WriteOrigin } from '../trust/tier.ts';
+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
const DOCS = 'docs/mcp/ADMIN.md#write-attribution';
@@ -174,7 +175,7 @@ const get_write_attribution: Operation = {
let created: StoredAttribution;
let last: StoredAttribution;
let trust: StoredTrust = { trust_tier: live?.trust_tier ?? null, write_origin: live?.write_origin ?? null };
- const row = rowTarget(ctx, page.id, page.slug, sourceId, { fact, take, timeline });
+ const row = rowTarget(ctx, page.id, page.slug, sourceId, { fact, take, timeline }, policy.excludePrivate === true);
if (row) {
const [found] = await ctx.engine.executeRaw<{ id: number; w_req: string | null; w_kind: string | null; w_id: string | null; created_at: Date | string | null;
l_req: string | null; l_kind: string | null; l_id: string | null; last_written_at: Date | string | null } & StoredTrust>(row.sql, row.params);
@@ -213,14 +214,14 @@ const get_write_attribution: Operation = {
};
function rowTarget(ctx: OperationContext, pageId: number, slug: string, sourceId: string,
- ids: { fact?: number; take?: number; timeline?: number }): RowTarget | undefined {
+ ids: { fact?: number; take?: number; timeline?: number }, excludePrivate: boolean): RowTarget | undefined {
const cols = `write_request_id::text AS w_req, write_principal_kind AS w_kind, write_principal_id AS w_id, created_at,
last_write_request_id::text AS l_req, last_write_principal_kind AS l_kind, last_write_principal_id AS l_id, last_written_at,
trust_tier, write_origin`;
if (ids.fact !== undefined) {
return { kind: 'fact', label: `fact #${ids.fact}`, list: { tool: 'recall', arguments: { entity: slug } },
sql: `SELECT id, ${cols} FROM facts WHERE id = $1 AND source_id = $2 AND (entity_slug = $3 OR source_markdown_slug = $3)
- ${ctx.remote === false ? '' : "AND visibility = 'world'"}`, params: [ids.fact, sourceId, slug] };
+ ${ctx.remote === false ? '' : "AND visibility = 'world'"} ${excludePrivate ? `AND ${privateProvenanceFilterFragment('facts')}` : ''}`, params: [ids.fact, sourceId, slug] };
}
if (ids.take !== undefined) {
const holders = readHolders(ctx);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 3b4bd13ce9..6546f0e053 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -284,6 +284,8 @@ const recall: Operation = {
ctx.remote === false
? undefined
: ['world'] as ('private' | 'world')[];
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote); // #4352: fact and page arms alike
const eligibility = await resolveReadEligibility(ctx, { minTrust: p.min_trust }); // #5575 floor + quarantine/rederive hiding
type FactRows = Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>;
@@ -337,7 +339,7 @@ const recall: Operation = {
const listOpts = {
activeOnly: !includeExpired,
limit,
- visibility,
+ visibility, excludePrivate,
grep: grep ?? undefined,
excludeAuditRows: true, eligibility,
};
@@ -348,7 +350,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, eligibility }),
+ ctx.engine.listSupersessions(src, { since: since ?? undefined, limit, visibility, excludePrivate, eligibility }),
)),
// v0.46 (#3014): matches the engine's ORDER BY COALESCE(expired_at,
// valid_until) — ontology supersessions carry valid_until only.
@@ -452,9 +454,7 @@ const recall: Operation = {
// source was invisible to recall while visible to every sibling read op.
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');
- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ // untrusted callers with the excludePrivate resolved above.
const keywordOnly = await recallKeywordOnlyReason(ctx);
if (keywordOnly) {
searchResults = await keylessRecallRows(ctx, queryText, limit, excludePrivate, searchScope);
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
index 6d4f1fe4ca..b5e65d697c 100644
--- a/src/core/ops/insights.ts
+++ b/src/core/ops/insights.ts
@@ -326,6 +326,7 @@ const find_trajectory: Operation = {
const until = typeof p.until === 'string' ? p.until : undefined;
const limit = typeof p.limit === 'number' ? p.limit : undefined;
const scope = sourceScopeOpts(ctx);
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
// D-CDX-1: thread ctx.remote into the engine so visibility filtering
// happens at SQL level. Mirrors recall's posture for untrusted callers.
@@ -333,6 +334,7 @@ const find_trajectory: Operation = {
entitySlug: p.entity_slug,
...scope,
remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
+ excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote),
metric,
kind,
since,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 42c89cd2da..dddb9a0a97 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2440,7 +2440,7 @@ export class PGLiteEngine implements BrainEngine {
async listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility'] },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility']; excludePrivate?: boolean },
): 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.ts
index ea665d7953..174c17214c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2209,7 +2209,7 @@ export class PostgresEngine implements BrainEngine {
async listSupersessions(
source_id: string,
- opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility'] },
+ opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[]; eligibility?: import('./engine.ts').FactListOpts['eligibility']; excludePrivate?: boolean },
): Promise<FactRow[]> {
return factsImpl.listSupersessions(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, opts);
}
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 710e2e5b8b..62abefeac5 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -694,6 +694,7 @@ export async function runThink(
const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const { formatTrajectoryBlock } = await import('../trajectory-format.ts');
const sourceIdScalar = opts.sourceId ?? 'default';
+ const excludePrivate = opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote);
// Per-candidate trajectory fetch. Concurrency cap = 3; each call
// has its own 5s timeout via Promise.race. allSettled prevents
// one error from killing the others (Codex Problem 13: timeout
@@ -719,6 +720,7 @@ export async function runThink(
...(opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),
...(opts.allowedSources !== undefined ? { sourceIds: opts.allowedSources } : {}),
...(opts.remote !== undefined ? { remote: opts.remote } : {}),
+ excludePrivate,
kind: 'all',
limit: 100,
}),
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 2413f42efd..b066566e10 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -359,7 +359,7 @@ async function assembleCard(
): Promise<EntityCard> {
const pageSlug = row.slug;
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
- const { privatePagesFilterFragment, privateLinkOriginFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateProvenanceFilterFragment } = await import('../search/private-visibility.ts');
const inboundPrivacy = excludePrivate
? ` AND ${privatePagesFilterFragment('f')} AND ${privateLinkOriginFilterFragment('l')}`
: '';
@@ -418,6 +418,7 @@ async function assembleCard(
activeOnly: true,
limit: FACT_FETCH_CAP,
...(visibility ? { visibility } : {}),
+ excludePrivate,
eligibility,
})
.catch(() => [] as FactRow[]),
@@ -431,7 +432,7 @@ async function assembleCard(
`SELECT COUNT(*) AS n
FROM facts
WHERE source_id = $1 AND entity_slug = $2
- AND expired_at IS NULL${remote ? ` AND visibility = 'world'` : ''}`,
+ AND expired_at IS NULL${remote ? ` AND visibility = 'world'` : ''}${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`,
[sourceId, pageSlug],
)
.then(rs => Number(rs[0]?.n ?? 0))
diff --git a/test/e2e/remote-fact-list-private-provenance-postgres.test.ts b/test/e2e/remote-fact-list-private-provenance-postgres.test.ts
new file mode 100644
index 0000000000..88c0a7daa3
--- /dev/null
+++ b/test/e2e/remote-fact-list-private-provenance-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../remote-fact-list-private-provenance.test.ts'));
diff --git a/test/remote-fact-list-private-provenance.test.ts b/test/remote-fact-list-private-provenance.test.ts
new file mode 100644
index 0000000000..e272380915
--- /dev/null
+++ b/test/remote-fact-list-private-provenance.test.ts
@@ -0,0 +1,211 @@
+/**
+ * Remote fact-list reads follow the page-visibility policy on the provenance
+ * page (#4352 class). A `visibility = 'world'` fact whose
+ * `source_markdown_slug` page is `visibility: private` stays out of every
+ * untrusted fact-list read: recall (entity, since, session, supersessions,
+ * no filter), the entity card, delta, hot memory, find_trajectory, think's
+ * trajectory block and get_write_attribution. Trusted local callers
+ * (`remote: false`) see exactly the rows they saw before, and the operator
+ * opt-out (`search.remote_private_pages=visible`) restores the old remote view.
+ *
+ * Both engines: PGLite always, Postgres through
+ * test/e2e/remote-fact-list-private-provenance-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+import { REMOTE_PRIVATE_PAGES_KEY, __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type R = Record<string, any>;
+const ENTITY = 'people/alice-example';
+const SESSION = 'sess-provenance';
+const noopLogger = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} };
+
+/** Sorted unique fact markers in a payload: every fact text starts with one. */
+function markers(payload: unknown): string[] {
+ const text = JSON.stringify(payload) ?? '';
+ return [...new Set(text.match(/(?:SECRETPROV|OPENPROV|PRIVVIS)-[a-z]+/g) ?? [])].sort();
+}
+
+const ACTIVE_LOCAL = ['OPENPROV-beta', 'OPENPROV-epsilon', 'PRIVVIS-gamma', 'SECRETPROV-alpha'];
+const ACTIVE_REMOTE = ['OPENPROV-beta', 'OPENPROV-epsilon'];
+
+function stubThinkClient(): { client: ThinkLLMClient; prompts: string[] } {
+ const prompts: string[] = [];
+ const client: ThinkLLMClient = {
+ create: async (params) => {
+ const content = params.messages[0]?.content;
+ prompts.push(typeof content === 'string' ? content : JSON.stringify(content));
+ return {
+ id: 'stub', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', stop_sequence: null,
+ usage: { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },
+ content: [{ type: 'text', text: JSON.stringify({ answer: 'stub', citations: [], gaps: [] }) }],
+ } as never;
+ },
+ };
+ return { client, prompts };
+}
+
+for (const kind of testBackends()) {
+ describe(`remote fact-list reads hide private-provenance facts (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let seededAt = '';
+ const ids: Record<string, number> = {};
+
+ const ctxOf = (remote: boolean | undefined, extra: Partial<OperationContext> = {}): OperationContext => ({
+ engine, config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote: remote as boolean,
+ transport: 'stdio', sourceId: 'default', ...extra,
+ } as OperationContext);
+ const local = (extra: Partial<OperationContext> = {}) => ctxOf(false, extra);
+ // remote UNDEFINED is the fail-closed `ctx.remote !== false` shape.
+ const untrusted = (extra: Partial<OperationContext> = {}) => [ctxOf(true, extra), ctxOf(undefined, extra)];
+
+ async function fact(name: string, f: {
+ text: string; kind?: string; visibility: 'world' | 'private'; provenance: string; hoursAgo: number;
+ metric?: number; supersededBy?: number;
+ }): Promise<void> {
+ const [row] = await engine.executeRaw<{ id: string | number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source, source_session,
+ source_markdown_slug, claim_metric, claim_value, expired_at, superseded_by)
+ VALUES ('default', $1, $2, $3, $4, now() - ($5 || ' hours')::interval, 'test', $6, $7,
+ $8, $9, $10::timestamptz, $11)
+ RETURNING id`,
+ [ENTITY, f.text, f.kind ?? 'fact', f.visibility, String(f.hoursAgo), SESSION, f.provenance,
+ f.metric === undefined ? null : 'mrr', f.metric ?? null,
+ f.supersededBy === undefined ? null : new Date(Date.now() - 30 * 60_000).toISOString(), f.supersededBy ?? null],
+ );
+ ids[name] = Number(row.id);
+ }
+
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ seededAt = new Date(Date.now() - 60_000).toISOString();
+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: 'Alice is a founder.' });
+ await engine.putPage('meetings/open-sync', { type: 'meeting', title: 'open sync', compiled_truth: 'An open meeting.' });
+ await engine.putPage('meetings/secret-sync', {
+ type: 'meeting', title: 'secret sync', compiled_truth: 'A private meeting.', frontmatter: { visibility: 'private' },
+ });
+ // World facts are the leak shape: only the provenance page's privacy can hide them.
+ await fact('alpha', { text: 'SECRETPROV-alpha commits to ship the launch', kind: 'commitment', visibility: 'world', provenance: 'meetings/secret-sync', hoursAgo: 2, metric: 100 });
+ await fact('beta', { text: 'OPENPROV-beta commits to review the plan', kind: 'commitment', visibility: 'world', provenance: 'meetings/open-sync', hoursAgo: 3, metric: 200 });
+ await fact('gamma', { text: 'PRIVVIS-gamma private note', visibility: 'private', provenance: 'meetings/open-sync', hoursAgo: 4, metric: 300 });
+ await fact('epsilon', { text: 'OPENPROV-epsilon current role', visibility: 'world', provenance: 'meetings/open-sync', hoursAgo: 1 });
+ await fact('delta', { text: 'SECRETPROV-delta earlier role', visibility: 'world', provenance: 'meetings/secret-sync', hoursAgo: 5, supersededBy: ids.epsilon });
+ await fact('zeta', { text: 'OPENPROV-zeta earlier title', visibility: 'world', provenance: 'meetings/open-sync', hoursAgo: 6, supersededBy: ids.epsilon });
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(() => {
+ __resetHotMemoryCacheForTests();
+ __resetPrivateVisibilityCacheForTests();
+ });
+
+ const recall = async (ctx: OperationContext, p: R) => (await operationsByName.recall.handler(ctx, p)) as R;
+
+ const recallArms: Array<[string, R, string[], string[]]> = [
+ ['entity', { entity: ENTITY }, ACTIVE_LOCAL, ACTIVE_REMOTE],
+ ['since', { since: '2d' }, ACTIVE_LOCAL, ACTIVE_REMOTE],
+ ['since + entity', { since: '2d', entity: ENTITY }, ACTIVE_LOCAL, ACTIVE_REMOTE],
+ ['session_id', { session_id: SESSION }, ACTIVE_LOCAL, ACTIVE_REMOTE],
+ ['no filter', {}, ACTIVE_LOCAL, ACTIVE_REMOTE],
+ ['supersessions', { supersessions: true }, ['OPENPROV-zeta', 'SECRETPROV-delta'], ['OPENPROV-zeta']],
+ ];
+ for (const [arm, params, localExpected, remoteExpected] of recallArms) {
+ test(`recall ${arm}: local unchanged, remote hides the private-provenance world fact`, async () => {
+ expect(markers((await recall(local(), params)).facts)).toEqual(localExpected);
+ for (const c of untrusted()) {
+ expect(markers((await recall(c, params)).facts)).toEqual(remoteExpected);
+ }
+ });
+ }
+
+ test('entity card: commitments and the active fact count skip private-provenance facts remotely', async () => {
+ const card = async (ctx: OperationContext) => ((await operationsByName.entity.handler(ctx, { name: ENTITY })) as R).card;
+ const localCard = await card(local());
+ expect(markers(localCard.open_threads)).toEqual(['OPENPROV-beta', 'SECRETPROV-alpha']);
+ expect(localCard.active_fact_count).toBe(4);
+ for (const c of untrusted()) {
+ const remoteCard = await card(c);
+ expect(markers(remoteCard.open_threads)).toEqual(['OPENPROV-beta']);
+ expect(remoteCard.active_fact_count).toBe(2);
+ }
+ });
+
+ test('delta facts arm: include_private local unchanged, remote hides private-provenance facts', async () => {
+ const del = async (ctx: OperationContext, p: R) => (await operationsByName.delta.handler(ctx, p)) as R;
+ expect(markers((await del(local(), { since: seededAt, include_private: true })).facts)).toEqual(ACTIVE_LOCAL);
+ for (const c of untrusted()) {
+ expect(markers((await del(c, { since: seededAt })).facts)).toEqual(ACTIVE_REMOTE);
+ }
+ });
+
+ test('hot memory (session and recent windows): local unchanged, remote hides private-provenance facts', async () => {
+ for (const extra of [{ sessionId: SESSION }, {}]) {
+ __resetHotMemoryCacheForTests();
+ const hot = async (ctx: OperationContext) => ((await getBrainHotMemoryMeta('search', ctx))?.brain_hot_memory as R | undefined)?.facts;
+ expect(markers(await hot(local(extra)))).toEqual(ACTIVE_LOCAL);
+ for (const c of untrusted(extra)) expect(markers(await hot(c))).toEqual(ACTIVE_REMOTE);
+ }
+ });
+
+ test('find_trajectory: local unchanged, remote hides private-provenance points', async () => {
+ const traj = async (ctx: OperationContext) => ((await operationsByName.find_trajectory.handler(ctx, { entity_slug: ENTITY })) as R).points;
+ expect(markers(await traj(local()))).toEqual(ACTIVE_LOCAL);
+ for (const c of untrusted()) {
+ const points = await traj(c);
+ expect(markers(points)).toEqual(ACTIVE_REMOTE);
+ expect(JSON.stringify(points)).not.toContain('meetings/secret-sync');
+ }
+ });
+
+ test('think trajectory block: local unchanged, remote omits private-provenance points', async () => {
+ const prompt = async (remote: boolean | undefined) => {
+ const { client, prompts } = stubThinkClient();
+ await runThink(engine, { remote: remote as boolean, question: 'When did Alice Example last switch jobs?', client });
+ expect(prompts.length).toBe(1);
+ expect(prompts[0]).toContain('<trajectory entity="people/alice-example"');
+ return prompts[0].slice(prompts[0].indexOf('<trajectory'));
+ };
+ expect(markers(await prompt(false))).toEqual(expect.arrayContaining(['OPENPROV-beta', 'SECRETPROV-alpha']));
+ for (const remote of [true, undefined]) {
+ const block = await prompt(remote);
+ expect(markers(block)).toContain('OPENPROV-beta');
+ expect(block).not.toContain('SECRETPROV');
+ }
+ });
+
+ test('get_write_attribution: a private-provenance fact is not visible remotely', async () => {
+ const attr = (ctx: OperationContext, id: number) => operationsByName.get_write_attribution.handler(ctx, { slug: ENTITY, fact: id }) as Promise<R>;
+ expect((await attr(local(), ids.alpha)).target.id).toBe(ids.alpha);
+ for (const c of untrusted()) {
+ expect((await attr(c, ids.beta)).target.id).toBe(ids.beta);
+ await expect(attr(c, ids.alpha)).rejects.toMatchObject({ code: 'fact_not_found' });
+ }
+ });
+
+ test('operator opt-out restores the previous remote view', async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ try {
+ __resetPrivateVisibilityCacheForTests();
+ expect(markers((await recall(ctxOf(true), { entity: ENTITY })).facts)).toEqual(['OPENPROV-beta', 'OPENPROV-epsilon', 'SECRETPROV-alpha']);
+ } finally {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, '');
+ __resetPrivateVisibilityCacheForTests();
+ }
+ });
+ });
+}