Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(visibility): derived and retried writes never land wider than their source

garrytane21e0eccd828
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 90db81e826..992a2d2b51 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -289,7 +289,10 @@ Save ONE fact with mandatory attribution.
(local CLI reads only; session hooks push world facts only, so a private
fact never reaches a new agent session, and a local private save carries the
`private_fact_not_pushed` notice saying so). The init quickstart carries the
- consent line.
+ consent line. An omitted `visibility` saves `private` when the target page is
+ private (by `visibility` or a privacy alias such as `access: private`) or the
+ operator set `facts.default_visibility` to private; a save never lands wider
+ than the page it is written into.
Response: `{ id, status, status_text, entity_slug, valid_until,
protocol_version }` (+ `degraded_dedup: true` when no embedding provider —
diff --git a/skills/bulk-ingestion/SKILL.md b/skills/bulk-ingestion/SKILL.md
index 2ceb59db49..f052a2103e 100644
--- a/skills/bulk-ingestion/SKILL.md
+++ b/skills/bulk-ingestion/SKILL.md
@@ -113,6 +113,7 @@ created: YYYY-MM-DD
updated: YYYY-MM-DD
tags: []
access: <per your brain's access policy>
+visibility: <private for anything remote agents must not read; omit for world>
---
# Title
diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.ts
index 84551cbc75..1083ab62bc 100644
--- a/src/commands/doctor/checks/derived-visibility.ts
+++ b/src/commands/doctor/checks/derived-visibility.ts
@@ -4,19 +4,29 @@
* origin (a transcript or missing origin counts as private, as in the repair).
* Remote reads treat unstamped rows as private; the warning names the
* tighten-only backfill `gbrain repair visibility` that stamps the stored rows.
- * One indexed aggregate query; counts are exact.
+ *
+ * It also counts what is labelled wider than a private source: Life Chronicle
+ * events whose origin is private, pages that carry a privacy alias
+ * (`access: private`, ...) but no `visibility`, and active `world` facts held
+ * in or extracted from a private page. Facts a remote caller can recall today
+ * are listed by id (first 50); slugs stay out of the check, which remote
+ * callers may run. `gbrain repair visibility` previews every row.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { privateSnapshotFilterFragment } from '../../../core/search/private-visibility.ts';
+import { derivationPrivateSql, privateSnapshotFilterFragment } from '../../../core/search/private-visibility.ts';
+import { aliasOnlyPagesSql, worldFactsFromPrivateSources } from '../../../core/repair/visibility.ts';
+
+const FACT_SAMPLE = 50;
export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: string): Promise<Check> {
const name = 'derived_visibility';
try {
- const [row] = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number }>(
+ const [row] = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number; looser_events: number; alias_pages_without_visibility: number }>(
`WITH derived AS (
SELECT p.* FROM pages p WHERE p.deleted_at IS NULL ${sourceId ? 'AND p.source_id=$1' : ''}
- AND (p.type='atom' OR (p.type='concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)))
+ AND (p.type='atom' OR (p.type='concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)
+ OR (p.type='event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%')))
SELECT
COUNT(*) FILTER (WHERE d.type='atom' AND d.frontmatter->>'visibility' IS NULL)::int AS unstamped_atoms,
COUNT(*) FILTER (WHERE d.type='concept' AND d.frontmatter->>'visibility' IS NULL)::int AS unstamped_concepts,
@@ -26,15 +36,30 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
COUNT(*) FILTER (WHERE d.type='concept' AND d.frontmatter->>'visibility'='world' AND EXISTS (SELECT 1 FROM links l
JOIN pages a ON a.id=l.to_page_id WHERE l.from_page_id=d.id AND l.link_source='concept-provenance' AND l.link_type='synthesized_from'
AND (COALESCE(a.frontmatter->>'visibility','private')='private' OR EXISTS (SELECT 1 FROM pages ao WHERE ao.source_id=a.source_id
- AND ao.slug=a.frontmatter->>'source_slug' AND ao.frontmatter->>'visibility'='private'))))::int AS looser_concepts
+ AND ao.slug=a.frontmatter->>'source_slug' AND ao.frontmatter->>'visibility'='private'))))::int AS looser_concepts,
+ COUNT(*) FILTER (WHERE d.type='event' AND COALESCE(d.frontmatter->>'visibility','world')<>'private' AND EXISTS (SELECT 1 FROM pages o
+ WHERE o.source_id=d.source_id AND o.slug=d.frontmatter->'event'->>'depth' AND o.deleted_at IS NULL
+ AND ${derivationPrivateSql('o')}))::int AS looser_events,
+ (SELECT COUNT(*)::int FROM pages ap WHERE ${aliasOnlyPagesSql('ap')} ${sourceId ? 'AND ap.source_id=$1' : ''}) AS alias_pages_without_visibility
FROM derived d`, sourceId ? [sourceId] : []);
- const details = { ...row, count: 'exact', truncated: false, repair: 'visibility' };
+ const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources')).map(s => s.id);
+ const facts = await worldFactsFromPrivateSources(engine, sources);
+ const readable = facts.filter(f => f.readable);
+ const details = { ...row, world_facts_from_private_sources: facts.length, world_facts_remotely_readable: readable.length,
+ remotely_readable_fact_ids: readable.slice(0, FACT_SAMPLE).map(f => String(f.id)), fact_ids_truncated: readable.length > FACT_SAMPLE,
+ count: 'exact', truncated: false, repair: 'visibility' };
const unstamped = row.unstamped_atoms + row.unstamped_concepts;
- const looser = row.looser_atoms + row.looser_concepts;
- if (unstamped + looser === 0) return { name, status: 'ok', details, message: 'Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.' };
- return { name, status: 'warn', details, message: `${unstamped} derived page(s) have no explicit visibility (${row.unstamped_atoms} atoms, ${row.unstamped_concepts} concepts) `
- + `and ${looser} are stored looser than their origin; remote reads treat the unstamped ones as private. `
- + `Preview: gbrain repair visibility — apply: gbrain repair visibility --apply` };
+ const looser = row.looser_atoms + row.looser_concepts + row.looser_events;
+ if (unstamped + looser + row.alias_pages_without_visibility + facts.length === 0) {
+ return { name, status: 'ok', details, message: 'Every derived page and fact carries a visibility no looser than its source, and no page relies on a privacy alias alone.' };
+ }
+ const parts: string[] = [];
+ if (unstamped + looser) parts.push(`${unstamped} derived page(s) have no explicit visibility (${row.unstamped_atoms} atoms, ${row.unstamped_concepts} concepts) `
+ + `and ${looser} are stored looser than their origin (${row.looser_events} chronicle events); remote reads treat the unstamped ones as private.`);
+ if (row.alias_pages_without_visibility) parts.push(`${row.alias_pages_without_visibility} page(s) mark themselves private with a privacy alias (access, confidentiality) but carry no visibility, so remote page reads treat them as world.`);
+ if (facts.length) parts.push(`${facts.length} active world fact(s) are held in or were extracted from a private page; ${readable.length} of them are readable by remote callers (ids in details.remotely_readable_fact_ids).`);
+ parts.push('Preview: gbrain repair visibility — apply after the user agrees: gbrain repair visibility --apply');
+ return { name, status: 'warn', details, message: parts.join(' ') };
} catch (e) {
return { name, status: 'warn', message: `derived visibility check skipped: ${e instanceof Error ? e.message : String(e)}`,
details: { count: 'lower_bound', truncated: true, health: 'unknown' } };
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 989009600b..6f264d42ad 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -104,7 +104,7 @@ import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';
import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';
import { ALLOWED_TYPES, ALLOWED_TYPE_ALIASES, isConversationFactsEligiblePage, pageTypesForAllowed, requireParseableConversationFlag, type AllowedType } from '../core/facts/conversation-types.ts';
import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, stampExtractorVersion } from '../core/facts/audit-sources.ts';
-import { resolveDefaultVisibility, type FactVisibility } from '../core/facts/visibility.ts';
+import { resolveDefaultVisibility, tightenToPage, type FactVisibility } from '../core/facts/visibility.ts';
import {
emptySaveTimeResolutionCounts,
formatSaveTimeResolutionCounts,
@@ -1014,7 +1014,8 @@ async function processPage(
let segmentsThisPage = 0;
const pageRows: Array<NewFact & { row_num: number; source_markdown_slug: string }> = [];
const pageResolution = emptySaveTimeResolutionCounts();
- const entityHints = await conversationEntityHints(state.engine, state.sourceId, page.slug, state.factVisibility); // #6731
+ const factVisibility = tightenToPage(state.factVisibility, page);
+ const entityHints = await conversationEntityHints(state.engine, state.sourceId, page.slug, factVisibility); // #6731
for (const seg of segments) {
if (state.segmentLimit > 0 && segmentsThisPage >= state.segmentLimit) break;
@@ -1076,8 +1077,8 @@ async function processPage(
// (above) ran every fact through the shipped resolver cascade (#3729/#4052),
// so master's per-row resolveEntitySlug mapper (#4567's independent fix for
// the same issue) is superseded rather than layered on top.
- const rows = await inferConversationSubjects(state.engine, state.sourceId, state.factVisibility, extracted.map((fact, i) => ({ // #6764
- ...fact, visibility: state.factVisibility,
+ const rows = await inferConversationSubjects(state.engine, state.sourceId, factVisibility, extracted.map((fact, i) => ({ // #6764
+ ...fact, visibility: factVisibility,
row_num: rowNum + i,
source_markdown_slug: page.slug,
source: PER_SEGMENT_SOURCE_PREFIX,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index cda8c94855..cb3247ab35 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1053,6 +1053,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },
{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },
{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },
+ // GBRA-159 visibility hotfix.
+ { since: 'TBD', text: 'Nothing derived from a private page is stored wider than the page. Facts extracted from a `visibility: private` page are private even when `facts.default_visibility` is world (before, a fact with no fence page was then returned to remote callers by recall and the entity card), and a page marked private only by `access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted` counts as private for its facts, chronicle events, timeline rows and remember saves. `remember` without a `visibility` now saves private when its target page is private or `facts.default_visibility` is explicitly private; otherwise the default stays world. Google Calendar events marked private or confidential sync as `visibility: private` pages, and a connector re-render keeps a page\'s private label. Remote page reads honor the privacy aliases only after `gbrain config set visibility.honor_aliases true`.' },
+ { since: 'TBD', text: 'Doctor `derived_visibility` also reports pages that carry a privacy alias but no `visibility`, chronicle events of a private origin, and world facts held in or extracted from a private page (fact ids a remote caller can read today are listed). `gbrain repair visibility` previews all of them and, with `--apply` only, makes them private; nothing runs on upgrade.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index 36747deede..4fec96fab1 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1509,6 +1509,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// didn't specify one: 'private' (default) | 'world'. Resolved by
// src/core/facts/visibility.ts; explicit caller values always win.
'facts.default_visibility',
+ // Remote page reads honor the privacy aliases (`access`, `confidentiality`) on pages without `visibility`; default off (search/private-visibility.ts).
+ 'visibility.honor_aliases',
'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)
'facts.candidate_fusion', // C2: 'rrf_free' (default, cosine arm) | 'interleave' (cosine + keyword; facts/single-prepare.ts)
'facts.supersession_thresholds', // JSON {"provider:model@dims": number | "off"} (facts/supersession-threshold.ts)
diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.ts
index 599183e69a..8ad64e95eb 100644
--- a/src/core/extract-timeline-from-meetings.ts
+++ b/src/core/extract-timeline-from-meetings.ts
@@ -15,7 +15,7 @@ import { buildGazetteer, findMentionedEntities, type Gazetteer } from './by-ment
import { isCrossSourceLinksEnabled } from './link-extraction.ts';
import { computeEffectiveDate } from './effective-date.ts';
import { parseFrontmatter } from './backfill-effective-date.ts';
-import { isPrivatePage } from './search/private-visibility.ts';
+import { isDerivationPrivate } from './search/private-visibility.ts';
import { quarantineFilterFragment } from './quarantine.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
import { derivedWriteTrust } from './trust/taint.ts';
@@ -213,7 +213,7 @@ export async function extractTimelineFromMeetings(
// timelines: the row carries no event_page_id (the (event_page_id, date)
// unique index allows one row per event, not one per attendee), so the
// remote private-event filter could never hide it. Fail closed: skip.
- if (isPrivatePage({ frontmatter })) { privateSkipped++; continue; }
+ if (isDerivationPrivate({ frontmatter })) { privateSkipped++; continue; }
// put_page-written pages never get effective_date computed (column stays
// NULL); derive it exactly as `gbrain backfill effective_date` would —
// same filename recipe (import_filename, else the slug tail) — so a later
@@ -469,7 +469,7 @@ export async function prepareMeetingTimeline(engine: BrainEngine, row: WriteRequ
[[...new Set(queued.map(r => r.meeting_id))]])).map(m => [Number(m.id), m]));
const current = queued.filter(r => {
const meeting = meetings.get(r.meeting_id);
- return meeting && !isPrivatePage({ frontmatter: parseFrontmatter(meeting.frontmatter) })
+ return meeting && !isDerivationPrivate({ frontmatter: parseFrontmatter(meeting.frontmatter) })
&& r.source === `${MEETING_SOURCE_PREFIX}${meeting.slug}` && r.summary === `Discussed in ${meeting.title}`;
});
const tiers = new Map([...meetings.values()].map(m => [Number(m.id), m.trust_tier]));
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 9e832869a8..35f54d4c42 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -367,6 +367,9 @@ export async function runFactsBackstop(
? { mode: 'queue', enqueued: false, queueDepth: 0, skipped }
: { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped };
}
+ // Facts extracted from a private page stay private, whatever the caller or the brain default says.
+ const { tightenToPage } = await import('./visibility.ts');
+ if (tightenToPage('world', parsedPage) === 'private') ctx = { ...ctx, visibility: 'private' };
const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');
if (await managedPersistenceEnabled(ctx.engine)) {
if (mode !== 'inline') {
diff --git a/src/core/facts/visibility.ts b/src/core/facts/visibility.ts
index 84fdfeb14b..067de14b4d 100644
--- a/src/core/facts/visibility.ts
+++ b/src/core/facts/visibility.ts
@@ -20,6 +20,7 @@
*/
import type { BrainEngine } from '../engine.ts';
+import { isDerivationPrivate } from '../search/private-visibility.ts';
export type FactVisibility = 'private' | 'world';
@@ -60,3 +61,30 @@ export async function resolveVisibilityParam(
if (value == null) return resolveDefaultVisibility(engine);
return 'private';
}
+
+/**
+ * Facts derived from a page never take a broader visibility than that page: a
+ * `visibility: private` page, a derived page that reads as private, or a page
+ * carrying a privacy marker (`access: private`, a private `confidentiality`)
+ * yields private facts whatever the caller or the brain default asked for.
+ */
+export function tightenToPage(visibility: FactVisibility, page: { type?: string | null; frontmatter?: unknown } | null | undefined): FactVisibility {
+ return page && isDerivationPrivate(page) ? 'private' : visibility;
+}
+
+/**
+ * `remember` without a `visibility`: the v1 default is `world`, except where
+ * that would widen what the caller is saving into. A private target page, an
+ * operator's explicit private `facts.default_visibility` (any non-empty value
+ * other than `world`, as the writeback posture reads it) or an unreadable
+ * config resolve `private`.
+ */
+export async function resolveRememberVisibility(engine: BrainEngine, page: { type?: string | null; frontmatter?: unknown } | null | undefined): Promise<FactVisibility> {
+ if (page && isDerivationPrivate(page)) return 'private';
+ try {
+ const raw = (await engine.getConfig(FACTS_DEFAULT_VISIBILITY_KEY))?.trim().toLowerCase() ?? '';
+ return raw === '' || raw === 'world' ? 'world' : 'private';
+ } catch {
+ return 'private';
+ }
+}
diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.ts
index efb91f1b6a..f1ab4e460f 100644
--- a/src/core/google/google-clients.ts
+++ b/src/core/google/google-clients.ts
@@ -570,6 +570,7 @@ interface RawCalendarEvent {
location?: string;
hangoutLink?: string;
htmlLink?: string;
+ visibility?: string;
}
function calendarEvent(e: RawCalendarEvent, account: string): CalendarEventData {
@@ -593,6 +594,7 @@ function calendarEvent(e: RawCalendarEvent, account: string): CalendarEventData
htmlLink: e.htmlLink ?? null,
status: e.status ?? 'confirmed',
account,
+ private: e.visibility === 'private' || e.visibility === 'confidential',
};
}
diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.ts
index 8a8352a1f5..08da399d8c 100644
--- a/src/core/google/google-render.ts
+++ b/src/core/google/google-render.ts
@@ -306,6 +306,18 @@ export function renderThreadPage(thread: GmailThreadData): RenderedPage | null {
return { relPath: threadRelPath(thread), markdown: fm.join('\n') + body.join('\n') + '\n' };
}
+/**
+ * The rendered page with `visibility: private` in its frontmatter (any other
+ * `visibility` line replaced). A re-render of a page that is private today
+ * keeps it private: tighten-only, whoever set the label.
+ */
+export function withPrivateVisibility(markdown: string): string {
+ const match = /^---\n([\s\S]*?)\n---(\n|$)/.exec(markdown);
+ if (!match) return `---\nvisibility: private\n---\n${markdown}`;
+ const lines = match[1]!.split('\n').filter((line) => !/^visibility\s*:/.test(line));
+ return `---\n${[...lines, 'visibility: private'].join('\n')}\n---${markdown.slice(match[0].length - match[2]!.length)}`;
+}
+
// ── Calendar event page ──────────────────────────────────────────────────────
export function calendarRelPath(ev: CalendarEventData): string {
@@ -333,6 +345,7 @@ export function renderCalendarEventPage(ev: CalendarEventData): RenderedPage | n
`attendees: ${yamlList(attendees.map((a) => a.email))}`,
...(ev.location ? [`location: ${yamlStr(ev.location)}`] : []),
...(ev.htmlLink ? [`url: ${yamlStr(ev.htmlLink)}`] : []),
+ ...(ev.private ? ['visibility: private'] : []),
'---',
];
const body: string[] = [
diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.ts
index 12281cbd77..50a8a37826 100644
--- a/src/core/google/sweep-shared.ts
+++ b/src/core/google/sweep-shared.ts
@@ -17,6 +17,8 @@ import { replaceableFile } from '../facts/file-body-guard.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import { OperationError } from '../ops/contract.ts';
import { slugifyPath } from '../sync.ts';
+import { isPrivatePage } from '../search/private-visibility.ts';
+import { withPrivateVisibility } from './google-render.ts';
import { isWriteThroughDisabled } from '../write-through.ts';
import { isSourceDbOnlySlug } from '../persistence/source-storage.ts';
import type { GoogleSourceConfig, GoogleSourceState } from './types.ts';
@@ -127,6 +129,9 @@ export async function importRendered(
identity: Record<string, string | readonly string[]> = {},
): Promise<string> {
markdown = connectorRender(markdown, { path: relPath, account: deps.cfg.account, ...identity });
+ const slug = slugifyPath(relPath);
+ const existing = await deps.engine.getPage(slug, { sourceId: deps.sourceId });
+ if (existing && isPrivatePage(existing)) markdown = withPrivateVisibility(markdown);
if (deps.managed) {
const result = await deps.managed.importMarkdown(relPath, markdown);
if (result.status === 'imported') {
@@ -141,8 +146,6 @@ export async function importRendered(
}
const filePath = join(deps.cfg.dir, relPath);
assertContained(deps.cfg.dir, filePath);
- const slug = slugifyPath(relPath);
- const existing = await deps.engine.getPage(slug, { sourceId: deps.sourceId });
if (existing) assertInlineBody(existing, 'Google connector materialization');
const databaseOnly = await isWriteThroughDisabled(deps.engine) || isSourceDbOnlySlug(deps.cfg.dir, slug, 'refuse');
const guard = databaseOnly ? null : await replaceableFile(deps.engine, deps.sourceId, slug, filePath);
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index ba553e3e84..8ecdebde11 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -353,6 +353,8 @@ export interface CalendarEventData {
htmlLink: string | null;
status: string;
account: string;
+ /** Google marks the event `private` or `confidential`: its page is `visibility: private`. */
+ private?: boolean;
}
export interface ContactData {
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 37985096a7..2eb9da4a2a 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -90,7 +90,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"world",
"private"
],
- "description": "world (default) or private (local CLI)."
+ "description": "world (default) or private (local CLI). Omitted on a private target page or brain default: private."
},
"replaces": {
"type": "string",
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index f25730af08..dd78d94582 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -109,8 +109,8 @@ const extract_facts: Operation = {
// [ENG-8] Explicit caller value wins; UNSET resolves through the shared
// facts.default_visibility helper (the old ternary coerced unset →
// 'private' before any config default could run). Garbage stays 'private'.
- const { resolveVisibilityParam } = await import('../facts/visibility.ts');
- const visibility: 'private' | 'world' = await resolveVisibilityParam(ctx.engine, p.visibility);
+ const { resolveVisibilityParam, tightenToPage } = await import('../facts/visibility.ts');
+ let visibility: 'private' | 'world' = await resolveVisibilityParam(ctx.engine, p.visibility);
// #4206: optional event-time + provenance threading. An unparseable
// valid_from fails LOUD — silently defaulting to now() is exactly the
@@ -129,6 +129,11 @@ const extract_facts: Operation = {
typeof p.source_slug === 'string' && p.source_slug.trim().length > 0
? p.source_slug.trim()
: undefined;
+ // A turn taken from a private page yields private facts, even when the caller asked for world.
+ if (visibility === 'world' && sourceSlug) {
+ const origin = await ctx.engine.readPageSnapshot(sourceSlug.replace(/\.md$/, ''), { sourceId });
+ visibility = tightenToPage(visibility, origin?.page);
+ }
const r = await runFactsPipeline(p.turn_text as string, {
engine: ctx.engine,
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index e19517ccf6..d9edb4720c 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -12,7 +12,7 @@ import { rebuildPendingPageProjections } from '../page-state/projections.ts';
import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';
import { parseFactsFence } from '../facts-fence.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
-import { segmentedRememberRefusal } from './verb-errors.ts';
+import { segmentedRememberRefusal, type RememberCarry } from './verb-errors.ts';
import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';
import { excludesPrivateWrites } from './page-visibility.ts';
import { emitFenceNotice, initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';
@@ -78,7 +78,7 @@ class InferredTargetRejected extends Error { constructor(readonly warning: Entit
* malformed fences and any owner claim, so it can fall back instead.
*/
async function planRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, entitySlug: string | null,
- inferred: { fact: string; visibility: string } | null) {
+ inferred: { fact: string; visibility: string } | null, call: RememberCall) {
const slug = entitySlug ?? 'memory/unattributed';
validatePageSlug(slug);
enforceClientSlugFence(ctx, slug, 'remember'); enforceSubagentSlugFence(ctx, slug, 'remember');
@@ -92,7 +92,9 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');
// Wave B: a segmented entity page over the single-string ceiling cannot take a fence row; named or inferred, the save refuses
// before admission instead of misfiling it. Below the ceiling an inferred target's checks read the page back whole, as preparation does.
- if (entitySlug !== null && snapshot && segmentedOverCeiling(snapshot.page)) throw segmentedRememberRefusal(slug, sourceId, inferred !== null);
+ if (entitySlug !== null && snapshot && segmentedOverCeiling(snapshot.page)) {
+ throw segmentedRememberRefusal(slug, sourceId, inferred !== null, await rememberCarry(ctx, call, snapshot.page));
+ }
const whole = inferred && snapshot && isSegmentedPage(snapshot.page) ? await materializedPage(ctx.engine, snapshot.page) : snapshot?.page;
if (inferred && (await isFactWithdrawn(ctx.engine, sourceId, inferred.visibility, inferred.fact, slug)
|| parseFactsFence(whole!.compiled_truth).warnings.length)) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
@@ -132,21 +134,39 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
return { slug, authority, snapshot, fence, binding, writeThrough };
}
+/** The caller's remember parameters and whether it named a visibility (the verb fills the v1 default otherwise). */
+interface RememberCall { p: Record<string, unknown>; visibilityDefaulted: boolean }
+type PageLabel = { type?: string | null; frontmatter?: unknown };
+
+/** The visibility a remember saves into `page`: the caller's own, or the resolved default that never widens a private target. */
+async function rememberVisibility(ctx: OperationContext, call: RememberCall, page: PageLabel | null | undefined): Promise<'world' | 'private'> {
+ if (!call.visibilityDefaulted) return call.p.visibility === 'private' ? 'private' : 'world';
+ const { resolveRememberVisibility } = await import('../facts/visibility.ts');
+ return resolveRememberVisibility(ctx.engine, page);
+}
+
+async function rememberCarry(ctx: OperationContext, call: RememberCall, page: PageLabel): Promise<RememberCarry> {
+ const { p } = call;
+ return { visibility: await rememberVisibility(ctx, call, page), ...(typeof p.kind === 'string' ? { kind: p.kind } : {}),
+ ...(typeof p.ttl === 'string' ? { ttl: p.ttl } : {}), ...(typeof p.valid_from === 'string' ? { valid_from: p.valid_from } : {}) };
+}
+
/**
* #5836: a fact saved without an entity names its subject from an exact
* mention, before admission. Any check the inferred target fails falls back
* to the unattributed save; `warning` is ENTITY_LINK_FAILED only once the
* target passed every scope and readability check, so a hidden page is never revealed.
*/
-async function inferRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, p: Record<string, unknown>):
+async function inferRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, call: RememberCall):
Promise<{ target: Awaited<ReturnType<typeof planRememberTarget>>; via: InferredVia } | { warning: EntityWarning } | null> {
+ const { p } = call;
if (p.infer_entity === false || !(await isEntityInferenceEnabled(ctx.engine))) return null;
const fact = String(p.fact).trim();
const inferred = await inferFactSubject(ctx.engine, sourceId,
{ fact, mode: 'write', excludePrivate: await excludesPrivateWrites(ctx.engine, ctx.remote !== false) });
if (inferred.slug === null) return null;
try {
- const target = await planRememberTarget(ctx, sourceId, source, inferred.slug, { fact, visibility: String(p.visibility ?? 'world') });
+ const target = await planRememberTarget(ctx, sourceId, source, inferred.slug, { fact, visibility: String(p.visibility ?? 'world') }, call);
return { target, via: inferred.via };
} catch (error) {
if (error instanceof InferredTargetRejected) return { warning: error.warning };
@@ -156,7 +176,8 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sour
}
}
-export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {
+export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number,
+ opts: { visibilityDefaulted?: boolean } = {}): Promise<Record<string, unknown>> {
registerMutationPreparer('remember', prepareMemoryMutation);
const sub = await submission(ctx, 'remember', params);
if (sub.prior) return throwIfHeld(writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs)));
@@ -169,14 +190,16 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;
const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const resolved = entity ? await resolveEntitySlugWithSource(ctx.engine, sourceId, entity) : null;
- const inference = entity === null ? await inferRememberTarget(ctx, sourceId, source, p) : null;
+ const call: RememberCall = { p, visibilityDefaulted: opts.visibilityDefaulted === true };
+ const inference = entity === null ? await inferRememberTarget(ctx, sourceId, source, call) : null;
const linked = inference && 'target' in inference ? inference : null;
const entitySlug = linked?.target.slug ?? resolved?.slug ?? null;
// A source-scoped absent identity serializes subjectless facts. Bound writers
// cannot use it to escape their namespace grant.
- const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null);
+ const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null, call);
const { assertFactNotWithdrawn, decideReplacement } = await import('../facts/single-prepare.ts');
- const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility: (p.visibility ?? 'world') as never, entity_slug: entitySlug };
+ const visibility = await rememberVisibility(ctx, call, snapshot?.page);
+ const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility, entity_slug: entitySlug };
// Fail fast on an invalid target or a withdrawn claim; the coordinator re-checks both under its locks before publishing.
if (p.replaces !== undefined && p.replaces !== null) {
// Fail fast on an invalid target; the coordinator re-checks it under the row lock before publishing.
@@ -189,6 +212,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records
// it, so recall's session_id filter finds single facts too. Identity only — never a trust surface.
intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: typeof p.valid_from === 'string' ? new Date(p.valid_from).toISOString() : new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
+ visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}),
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),
session_id: ctx.sessionId ?? null },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index cc6bcd9af4..c42e54a892 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -29,6 +29,7 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';
import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';
import { withPageTierKept } from '../trust/fence-append.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { tightenToPage } from '../facts/visibility.ts';
import { noteBelief } from '../belief/ledger.ts';
function receiptFix(row: WriteRequest): Action {
@@ -84,6 +85,8 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null };
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');
+ // A defaulted visibility never lands broader than the target page as it stands at publication.
+ if (p.visibility_defaulted === true && snapshot) input.visibility = tightenToPage(input.visibility, snapshot.page);
if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));
const observedRevision = snapshot?.revision ?? null;
const excludePrivate = await resolveExcludePrivatePages(engine, row.authority.remote === true);
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 86c78a3d1a..deb04ca82c 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -503,6 +503,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);
if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);
if (row.intent?.kind === 'managed_maintenance_restore_redacted_facts') return (await import('../repair/redacted-facts.ts')).prepareRedactedFactsRestore(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_tighten_fact_visibility') return (await import('../repair/visibility.ts')).prepareFactVisibilityTighten(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_label_retire') return (await import('../repair/conversation-labels.ts')).prepareConversationLabelRetirement(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_relink') return (await import('../facts/conversation-relink.ts')).prepareConversationRelink(engine, row);
if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 7a7257b2a8..c1d17a5227 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -148,20 +148,31 @@ const SEGMENTED_WRITE_SUGGESTION = 'The target page stores its body in segments
+ 'For remember: save the claim without an entity (omit entity, infer_entity: false); it is filed under memory/unattributed, and remembering it with entity once that page accepts fact rows replaces that copy. '
+ "Read the page with get_page body: 'auto' or a window.";
-/** The next step of a `remember` refused because its entity page stores its body in segments: save the claim unattributed. */
-export function segmentedRememberFix(): Action {
- return { argv: ['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false'],
- mcp: { tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false } },
- inputs: [{ name: 'FACT', how: 'The claim you tried to remember, unchanged.' }, { name: 'PROVENANCE', how: 'The same provenance you passed.' }],
+/** What the unattributed retry must keep from the refused call, so the retry is never broader than the original. */
+export interface RememberCarry { visibility: 'world' | 'private'; kind?: string; ttl?: string; valid_from?: string }
+
+/**
+ * The next step of a `remember` refused because its entity page stores its body in segments: save the claim unattributed.
+ * With `carry` the retry names the refused call's resolved visibility, kind, ttl and valid_from; without it (a receipt-only
+ * refusal) visibility is an input the caller must fill, never left to the world default.
+ */
+export function segmentedRememberFix(carry?: RememberCarry): Action {
+ const extra: Record<string, string> = carry ? { visibility: carry.visibility, ...(carry.kind ? { kind: carry.kind } : {}),
+ ...(carry.ttl ? { ttl: carry.ttl } : {}), ...(carry.valid_from ? { valid_from: carry.valid_from } : {}) } : { visibility: '<VISIBILITY>' };
+ return { argv: ['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false',
+ ...Object.entries(extra).flatMap(([key, value]) => [`--${key.replace('_', '-')}`, value])],
+ mcp: { tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false, ...extra } },
+ inputs: [{ name: 'FACT', how: 'The claim you tried to remember, unchanged.' }, { name: 'PROVENANCE', how: 'The same provenance you passed.' },
+ ...(carry ? [] : [{ name: 'VISIBILITY', how: 'The visibility you passed. If you passed none: private when the entity page is private or you are unsure, else world.' }])],
consent: [], actor: 'agent', requires_exclusive: false,
why: "Saves the claim without an entity: the entity page's facts fence cannot take a row while its body is stored in segments over 24 MiB. Remembering it with entity later replaces this copy." };
}
/** A `remember` whose entity (named or inferred) stores its body in segments: refused before admission with the unattributed-save fix. */
-export function segmentedRememberRefusal(slug: string, sourceId: string, inferred: boolean): OperationError {
+export function segmentedRememberRefusal(slug: string, sourceId: string, inferred: boolean, carry?: RememberCarry): OperationError {
return opError('page_body_segmented',
`remember: the entity page ${slug} (source ${sourceId})${inferred ? ', inferred from a mention in the fact,' : ''} stores its body in segments over the 24 MiB limit up to which remember reads it whole, so remember cannot add a row to its facts fence. Nothing was saved.`,
- SEGMENTED_WRITE_SUGGESTION, { fix: segmentedRememberFix() });
+ SEGMENTED_WRITE_SUGGESTION, { fix: segmentedRememberFix(carry) });
}
const PURGED_SUGGESTION = 'Do not retry the same content. If it is still true, write it in new words; only the owner can clear a purge tombstone on the brain host.';
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index ff66887c66..a914d4f07e 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -60,7 +60,7 @@ import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersess
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
const REPLAYABLE = ['put_page', 'add_timeline_entry', 'remember'];
-const REMEMBER_PREPARED_KEYS = ['entity_slug', 'fence', 'valid_from', 'valid_until', 'entity_inferred', 'entity_warning'];
+const REMEMBER_PREPARED_KEYS = ['entity_slug', 'fence', 'valid_from', 'valid_until', 'entity_inferred', 'entity_warning', 'visibility_defaulted'];
const REMOTE_PREPARED_KEYS = ['source_kind', 'source_uri', 'ingested_via'];
const PAGE_REMOVALS = PAGE_REMOVAL_OPERATIONS;
const GUARD_REFUSAL = `(r.state='failed' AND (r.error_code='writer_coordinator_required'
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 75722b75f7..e73a2a3a1f 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -118,7 +118,9 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
},
visibility: {
handler: visibilityRepair, embeds: 'effect', checks: ['derived_visibility'],
- summary: 'Stamp explicit visibility on extracted atoms and synthesized concepts, tighten-only (#5525). Transcript and missing origins become private; nothing is ever loosened. Each repaired page is re-embedded by its publication.',
+ summary: 'Stamp explicit visibility on extracted atoms and synthesized concepts, tighten-only (#5525). Transcript and missing origins become private; nothing is ever loosened. '
+ + 'Also makes private the chronicle events of a private origin, the pages that carry a privacy alias (access: private, ...) but no visibility, and the world facts held in or extracted from a private page. '
+ + 'Each repaired page is re-embedded by its publication.',
},
'safe-chunks': {
handler: safeChunksRepair, embeds: 'inline', checks: ['safe_index_pending'],
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index 69db7278d4..d47935d251 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -6,6 +6,14 @@
* concept strictest visibility of its input atoms (provenance edges + atoms' `concepts:`);
* a member without a provenance edge counts as private
*
+ * event a Life Chronicle event whose meeting/conversation origin is private now (by its
+ * `visibility`, lineage or a privacy alias) becomes private; a missing origin is
+ * left unchanged and counted (remote reads already hide it)
+ * alias a page that carries a privacy alias (`access: private`, ...) but no `visibility`
+ * is stamped `visibility: private`
+ * fact an active world fact held in or extracted from such a private page becomes
+ * private: in its page's facts fence when fenced, in place when database-only
+ *
* An item is only ever made stricter than it is now: explicit `private` stays,
* explicit `world` becomes `private` when its origin is stricter, and a missing
* field (read as private) is stamped with the origin's value. A concept with no
@@ -15,14 +23,26 @@
import type { BrainEngine } from '../engine.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
-import { effectiveVisibility, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
+import { derivationPrivateSql, effectiveVisibility, privacyAliasSql, privateSnapshotFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
+import { strikeFenceRow } from '../facts/forget.ts';
+import { opError } from '../ops/contract.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import { digest } from '../persistence/digest.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';
interface DerivedRow { id: number; source_id: string; slug: string; type: string; visibility: string | null; chars: number }
interface AtomRow extends DerivedRow { source_slug: string | null; origin_id: number | null; origin_type: string | null; origin_frontmatter: Record<string, unknown> | null }
interface InputRow { concept_id: number; atom_id: number; linked: boolean }
-export interface VisibilityChange { id: number; source_id: string; slug: string; phase: 0 | 1; from: string | null; to: Visibility }
+interface EventRow extends DerivedRow { origin_id: number | null; origin_type: string | null; origin_frontmatter: Record<string, unknown> | null }
+
+export interface VisibilityChange { id: number; source_id: string; slug: string; phase: 0 | 1 | 2 | 3; from: string | null; to: Visibility }
/** Tighten-only: never loosen an explicit value; stamp a missing one. */
function tightened(current: string | null, target: Visibility): Visibility | null {
@@ -39,6 +59,7 @@ function tightened(current: string | null, target: Visibility): Visibility | nul
export async function planVisibilityRepair(engine: BrainEngine, sourceIds: string[], only?: number) {
const [kind] = only === undefined ? [] : await engine.executeRaw<{ type: string }>('SELECT type FROM pages WHERE id=$1', [only]);
const conceptIds = only === undefined ? null : kind?.type === 'concept' ? [only] : [];
+ const eventIds = only === undefined ? null : kind?.type === 'event' ? [only] : [];
const concepts = await engine.executeRaw<DerivedRow>(`SELECT c.id,c.source_id,c.slug,c.type,c.frontmatter->>'visibility' AS visibility,
length(c.compiled_truth) AS chars
FROM pages c WHERE c.type='concept' AND c.frontmatter->>'synthesized_by' IS NOT NULL AND c.deleted_at IS NULL
@@ -83,21 +104,134 @@ export async function planVisibilityRepair(engine: BrainEngine, sourceIds: strin
const next = tightened(concept.visibility, strictestVisibility(members));
if (next) changes.push({ id: Number(concept.id), source_id: concept.source_id, slug: concept.slug, phase: 1, from: concept.visibility, to: next });
}
- const chars = new Map([...atoms, ...concepts].map(row => [Number(row.id), Number(row.chars)]));
- return { changes, chars, residuals: { atoms_origin_gone_to_private: originGone, concepts_without_lineage: noLineage } };
+ const events = await engine.executeRaw<EventRow>(`SELECT e.id,e.source_id,e.slug,e.type,e.frontmatter->>'visibility' AS visibility,
+ length(e.compiled_truth) AS chars,o.id AS origin_id,o.type AS origin_type,o.frontmatter AS origin_frontmatter
+ FROM pages e LEFT JOIN pages o ON o.source_id=e.source_id AND o.slug=e.frontmatter->'event'->>'depth' AND o.deleted_at IS NULL
+ WHERE e.type='event' AND e.frontmatter->>'captured_via' LIKE 'life-chronicle:%' AND e.deleted_at IS NULL
+ AND COALESCE(e.frontmatter->>'visibility','world')<>'private'
+ AND e.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR e.id=ANY($2::integer[])) ORDER BY e.id`, [sourceIds, eventIds]);
+ let eventsOriginGone = 0;
+ for (const event of events) {
+ if (event.origin_id == null) { eventsOriginGone++; continue; }
+ if (effectiveVisibility({ kind: 'page', page: { type: event.origin_type, frontmatter: event.origin_frontmatter } }) !== 'private') continue;
+ changes.push({ id: Number(event.id), source_id: event.source_id, slug: event.slug, phase: 2, from: event.visibility, to: 'private' });
+ }
+ const aliased = await engine.executeRaw<DerivedRow>(`SELECT p.id,p.source_id,p.slug,p.type,NULL::text AS visibility,length(p.compiled_truth) AS chars
+ FROM pages p WHERE ${aliasOnlyPagesSql('p')} AND p.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR p.id=ANY($2::integer[])) ORDER BY p.id`,
+ [sourceIds, only === undefined ? null : [only]]);
+ for (const page of aliased) changes.push({ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 3, from: null, to: 'private' });
+ const chars = new Map([...atoms, ...concepts, ...events, ...aliased].map(row => [Number(row.id), Number(row.chars)]));
+ return { changes, chars, residuals: { atoms_origin_gone_to_private: originGone, concepts_without_lineage: noLineage,
+ events_origin_gone: eventsOriginGone } };
+}
+
+/**
+ * The page a fact says it came from (not the page holding it): the page-write
+ * session (`put_page:<slug>`, `sync:<slug>`), else the slug a page-write or
+ * extract_facts lane records first in `context`.
+ */
+function factProvenanceSlugSql(f: string): string {
+ return `regexp_replace(COALESCE(
+ CASE WHEN ${f}.source_session ~ '^(put_page|sync):' THEN regexp_replace(${f}.source_session, '^(put_page|sync):', '') END,
+ CASE WHEN ${f}.source IN ('mcp:put_page','sync:import','file_upload','code_import','hook:writeback','mcp:extract_facts')
+ THEN NULLIF(split_part(btrim(COALESCE(${f}.context,'')), ' ', 1), '') END), '\\.md$', '')`;
+}
+
+/**
+ * Active `world` facts held in, or extracted from, a page that is private by
+ * its `visibility`, its declared lineage or a privacy alias. `readable` says a
+ * remote caller can recall the row today: its holding page does not hide it
+ * through the provenance filter.
+ */
+export async function worldFactsFromPrivateSources(engine: BrainEngine, sourceIds: string[], ids?: number[]) {
+ return engine.executeRaw<{ id: number; source_id: string; row_num: number | null; source_markdown_slug: string | null; entity_slug: string | null; readable: boolean }>(
+ `SELECT f.id,f.source_id,f.row_num,f.source_markdown_slug,f.entity_slug,
+ (f.source_markdown_slug IS NULL OR NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id=f.source_id
+ AND pp.slug=f.source_markdown_slug AND NOT ${privateSnapshotFilterFragment('pp')})) AS readable
+ FROM facts f WHERE f.visibility='world' AND f.expired_at IS NULL AND f.source_id=ANY($1::text[])
+ AND ($2::bigint[] IS NULL OR f.id=ANY($2::bigint[]))
+ AND EXISTS (SELECT 1 FROM pages o WHERE o.source_id=f.source_id AND o.deleted_at IS NULL
+ AND (o.slug=f.source_markdown_slug OR o.slug=${factProvenanceSlugSql('f')}) AND ${derivationPrivateSql('o')})
+ ORDER BY f.id`, [sourceIds, ids ?? null]);
+}
+
+/** Pages that carry a privacy alias but no `visibility` (derived atoms, concepts and chronicle events have their own phases). */
+export function aliasOnlyPagesSql(p: string): string {
+ return `(${p}.deleted_at IS NULL AND ${p}.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql(p)}
+ AND ${p}.type <> 'atom' AND NOT (${p}.type = 'concept' AND ${p}.frontmatter->>'synthesized_by' IS NOT NULL)
+ AND NOT (${p}.type = 'event' AND ${p}.frontmatter->>'captured_via' LIKE 'life-chronicle:%'))`;
+}
+
+export const FACT_VISIBILITY_INTENT = 'managed_maintenance_tighten_fact_visibility';
+
+/** Database-only rows still world and unfenced become private; the compare runs in the UPDATE, which locks the row. */
+const tightenDatabaseFacts = (tx: BrainEngine, sourceId: string, ids: number[]) => tx.executeRaw<{ id: number | string }>(
+ `UPDATE facts SET visibility='private' WHERE source_id=$1 AND id=ANY($2::bigint[]) AND visibility='world' AND row_num IS NULL AND expired_at IS NULL RETURNING id`,
+ [sourceId, ids]);
+
+/** Preparer for `managed_maintenance_tighten_fact_visibility`: makes the named database-only world facts private. */
+export async function prepareFactVisibilityTighten(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const ids = (row.intent as { fact_ids?: unknown } | null)?.fact_ids;
+ if (!Array.isArray(ids) || !ids.every(id => Number.isSafeInteger(id))) {
+ throw opError('invalid_params', 'The fact visibility intent does not name its facts.',
+ `Request ${row.request_id} in source ${row.source_id} does not name the facts to make private, so nothing changed. Preview gbrain repair visibility again and apply it after the user approves.`);
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ return { observedRevision: snapshot?.revision ?? null, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => ({ status: 'completed', tightened: (await tightenDatabaseFacts(tx, row.source_id, ids as number[])).map(r => Number(r.id)) }) };
+}
+
+/**
+ * One fact item: a fenced row gets `private` in its page's `## Facts` fence by a
+ * revision-bound put_page (the projection then stores it private); a
+ * database-only row is updated in place (a database-only maintenance request
+ * on a managed brain). A page stored in segments is left for the owner.
+ */
+async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem): Promise<boolean> {
+ const factId = item.cursor.id;
+ const [fact] = await worldFactsFromPrivateSources(ctx.engine, [item.source_id], [factId]);
+ if (!fact) return false;
+ if (fact.row_num === null) {
+ if (!await managedPersistenceEnabled(ctx.engine)) {
+ return (await maintenanceTransaction(ctx.engine, tx => tightenDatabaseFacts(tx, item.source_id, [factId]))).length > 0;
+ }
+ const authority = (await maintenancePreflight(ctx.engine, item.source_id))!;
+ const holder = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
+ const h = digest(['fact-visibility-v1', item.source_id, item.slug, factId, holder?.revision ?? null]);
+ const receipt = await submitDatabaseMaintenanceIntent(ctx.engine, authority, item.slug,
+ { kind: FACT_VISIBILITY_INTENT, expected_revision: holder?.revision ?? null, fact_ids: [factId] },
+ `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`);
+ return ((receipt.tightened as number[] | undefined) ?? []).includes(factId);
+ }
+ const snapshot = fact.source_markdown_slug ? await ctx.engine.readPageSnapshot(fact.source_markdown_slug, { sourceId: item.source_id }) : null;
+ if (!snapshot || isSegmentedPage(snapshot.page)) return false;
+ const body = strikeFenceRow(snapshot.page.compiled_truth ?? '', fact.row_num, row => ({ ...row, visibility: 'private' }));
+ if (body === null) return false;
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: snapshot.page.slug, source_id: item.source_id,
+ content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: snapshot.revision,
+ request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });
+ const [stored] = await ctx.engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [factId]);
+ return stored?.visibility === 'private';
}
export const visibilityRepair: RepairHandler = {
kind: 'visibility',
async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {
const { changes, chars, residuals } = await planVisibilityRepair(engine, scope.source_ids);
- const items: RepairItem[] = changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, source_id: change.source_id,
+ const facts = await worldFactsFromPrivateSources(engine, scope.source_ids);
+ const items: RepairItem[] = [...changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, source_id: change.source_id,
slug: change.slug, chars: chars.get(change.id) ?? 0, action: `visibility ${change.from ?? '(none)'} -> ${change.to}`,
- change: { from: change.from, to: change.to } }))
+ change: { from: change.from, to: change.to } })),
+ ...facts.map(fact => ({ cursor: { phase: 4, id: Number(fact.id) }, source_id: fact.source_id,
+ slug: fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed', chars: 0,
+ action: `fact ${fact.id} visibility world -> private${fact.readable ? ' (remotely readable now)' : ''}`, change: { from: 'world', to: 'private' } }))]
.filter(item => afterCursor(item.cursor, after));
- return { items, residuals };
+ return { items, residuals: { ...residuals, world_facts_remotely_readable: facts.filter(fact => fact.readable).length } };
},
async apply(ctx, item) {
+ if (item.cursor.phase === 4) return applyFactItem(ctx, item);
const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
if (!snapshot || !item.change) return false;
// Re-decide against current origins and inputs; a changed decision waits for the next run.
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 9506c49fb6..097db5ed33 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -51,12 +51,13 @@ export function privatePagesFilterFragment(pageAlias: string): string {
/**
* `privatePagesFilterFragment` with a cheap first test: a page with no
- * `visibility` or `derived_from` key whose type is not atom, concept or event
- * is visible by every rule above, so only the remaining pages run the full
+ * `visibility`, `derived_from` or privacy-alias key whose type is not atom,
+ * concept or event is visible by every rule above, so only the remaining pages run the full
* check. For scans over thousands of candidate pages (an entity's referrers).
*/
export function privatePagesFilterFragmentFast(pageAlias: string): string {
return `((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL
+ AND ${pageAlias}.frontmatter->'access' IS NULL AND ${pageAlias}.frontmatter->'confidentiality' IS NULL
AND ${pageAlias}.type NOT IN ('atom', 'concept', 'event'))
OR ${privatePagesFilterFragment(pageAlias)})`;
}
@@ -85,11 +86,15 @@ function declaredLineagePrivateSql(p: string): string {
* as `page_versions` that have no page identity to follow to an origin. Callers
* pair it with privatePagesFilterFragment on the live page. A page carrying the
* `pinned_question` marker is private whatever its `visibility` says (pinned
- * questions are owner-private, src/core/questions/pages.ts).
+ * questions are owner-private, src/core/questions/pages.ts). A page with no
+ * `visibility` but a privacy alias is private here only while the operator has
+ * set `visibility.honor_aliases`; the row-side isPrivatePage re-check that some
+ * readers run after this SQL filter does not consult the flag.
*/
export function privateSnapshotFilterFragment(alias: string): string {
return `(COALESCE(${alias}.frontmatter->>'visibility', CASE WHEN ${derivedPageSql(alias)} THEN 'private' ELSE 'world' END) <> 'private'
- AND NOT COALESCE(${alias}.frontmatter ? 'pinned_question', false))`;
+ AND NOT COALESCE(${alias}.frontmatter ? 'pinned_question', false)
+ AND NOT (${alias}.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql(alias)} AND ${HONOR_ALIASES_SQL}))`;
}
/**
@@ -130,13 +135,55 @@ function chronicleOriginNotVisibleSql(p: string): string {
export type Visibility = 'private' | 'world';
/**
- * #5525 — the visibility a derived page takes from its origin under the
- * read-side rule: transcripts and missing origins are private, and a page
- * origin is private exactly when remote readers cannot see it.
+ * Privacy aliases: keys a page may carry instead of `visibility` (the
+ * bulk-ingestion template's `access`, a `confidentiality` field), with the
+ * values that mean private. Matching is case-insensitive on the trimmed value.
+ * Everything derived from an aliased page (facts, chronicle events, timeline
+ * rows, remember saves into it) is private. Remote page reads honor the aliases
+ * only when the operator sets `visibility.honor_aliases` (default off).
+ */
+export const PRIVACY_ALIASES: Readonly<Record<string, readonly string[]>> = {
+ access: ['private', 'restricted', 'confidential'],
+ confidentiality: ['confidential', 'secret', 'private', 'restricted'],
+};
+export const HONOR_ALIASES_KEY = 'visibility.honor_aliases';
+
+function hasPrivacyAlias(frontmatter: Record<string, unknown>): boolean {
+ return Object.entries(PRIVACY_ALIASES).some(([key, values]) => {
+ const value = frontmatter[key];
+ return typeof value === 'string' && values.includes(value.trim().toLowerCase());
+ });
+}
+
+/** SQL twin of hasPrivacyAlias on a page alias (a code-provided literal). */
+export function privacyAliasSql(alias: string): string {
+ return `(${Object.entries(PRIVACY_ALIASES).map(([key, values]) =>
+ `lower(btrim(${alias}.frontmatter->>'${key}')) IN (${values.map(v => `'${v}'`).join(',')})`).join(' OR ')})`;
+}
+
+/** True in SQL when the operator opted remote page reads into honoring the privacy aliases. */
+const HONOR_ALIASES_SQL = `EXISTS (SELECT 1 FROM config honor_aliases WHERE honor_aliases.key='${HONOR_ALIASES_KEY}'
+ AND lower(btrim(honor_aliases.value)) IN ('true','1','on','yes'))`;
+
+/** A page whatever is derived from it must not outrank: private to remote readers, or carrying a privacy alias. */
+export function isDerivationPrivate(page: { type?: string | null; frontmatter?: unknown }): boolean {
+ if (isPrivatePage(page)) return true;
+ return typeof page.frontmatter === 'object' && page.frontmatter !== null && hasPrivacyAlias(page.frontmatter as Record<string, unknown>);
+}
+
+/** SQL twin of isDerivationPrivate. */
+export function derivationPrivateSql(alias: string): string {
+ return `(NOT ${privateSnapshotFilterFragment(alias)} OR ${privacyAliasSql(alias)})`;
+}
+
+/**
+ * #5525 — the visibility a derived page takes from its origin: transcripts and
+ * missing origins are private, and a page origin is private when remote
+ * readers cannot see it or it carries a privacy alias.
*/
export function effectiveVisibility(origin: { kind: 'transcript' } | { kind: 'page'; page: { type?: string | null; frontmatter?: unknown } | null }): Visibility {
if (origin.kind === 'transcript' || !origin.page) return 'private';
- return isPrivatePage(origin.page) ? 'private' : 'world';
+ return isDerivationPrivate(origin.page) ? 'private' : 'world';
}
/** Derived outputs take the strictest visibility of their inputs. */
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index de9e1b05fb..53b3fb6b84 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -102,7 +102,7 @@ const remember: Operation = {
visibility: {
type: 'string',
enum: ['world', 'private'],
- description: 'world (default) or private (local CLI).',
+ description: 'world (default) or private (local CLI). Omitted on a private target page or brain default: private.',
},
replaces: { type: 'string', description: 'fact_id this fact replaces (same entity, or none).', fullSurfaceOnly: true },
},
@@ -196,7 +196,8 @@ const remember: Operation = {
const { submitRememberMutation } = await import('./persistence/memory-mutations.ts');
const { runMemoryWrite } = await import('./persistence/verb-errors.ts');
- const result = await runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility, ...(replaces !== undefined ? { replaces } : {}) }));
+ const result = await runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility, ...(replaces !== undefined ? { replaces } : {}) },
+ undefined, { visibilityDefaulted: typeof p.visibility !== 'string' }));
// F8: the explanation the CLI formatter prints, as a model-visible notice.
if ((result as { degraded_dedup?: boolean } | null)?.degraded_dedup) {
const { degradedDedupNotice } = await import('./interop-notices.ts');
diff --git a/test/derived-visibility-repair.test.ts b/test/derived-visibility-repair.test.ts
index 5449e01b71..d94d8c6a1f 100644
--- a/test/derived-visibility-repair.test.ts
+++ b/test/derived-visibility-repair.test.ts
@@ -276,7 +276,8 @@ describe('#5525 tighten-only visibility backfill', () => {
const scope = await resolveRepairScope(engine);
const preview = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: false });
expect(preview.affected).toBe(4);
- expect(preview.residuals).toEqual({ atoms_origin_gone_to_private: 1, concepts_without_lineage: 1 });
+ expect(preview.residuals).toEqual({ atoms_origin_gone_to_private: 1, concepts_without_lineage: 1, events_origin_gone: 0,
+ world_facts_remotely_readable: 0 });
expect(await visibilityOf(engine, 'atoms/unstamped-world')).toBeNull();
const applied = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: true });
expect(applied).toMatchObject({ applied: 4, complete: true });
diff --git a/test/google-clients.test.ts b/test/google-clients.test.ts
index 0e9771287a..cf48f601b4 100644
--- a/test/google-clients.test.ts
+++ b/test/google-clients.test.ts
@@ -1085,3 +1085,19 @@ describe('PeopleClient', () => {
expect((thrown as GoogleCursorExpiredError).status).toBe(410);
});
});
+
+// ── Calendar event privacy (fail closed) ─────────────────────────────────────
+
+describe('CalendarClient event privacy', () => {
+ test('Google private and confidential events map to private; default and public do not', async () => {
+ const h = makeHarness(() => json({
+ items: ['private', 'confidential', 'default', 'public', undefined].map((visibility, i) => ({
+ id: `ev${i}`, summary: `Event ${i}`, start: { dateTime: '2026-10-01T10:00:00Z' }, end: { dateTime: '2026-10-01T11:00:00Z' },
+ ...(visibility ? { visibility } : {}),
+ })),
+ nextSyncToken: 'sync-1',
+ }));
+ const { events } = await new CalendarClient(h.tokens, h.fetchImpl).listEvents('[email protected]', { timeMinIso: '2026-09-01T00:00:00Z' });
+ expect(events.map((e) => [e.id, e.private])).toEqual([['ev0', true], ['ev1', true], ['ev2', false], ['ev3', false], ['ev4', false]]);
+ });
+});
diff --git a/test/large-pages/segmented-remember-refusal.test.ts b/test/large-pages/segmented-remember-refusal.test.ts
index 6354b2c5ec..1092e8ab77 100644
--- a/test/large-pages/segmented-remember-refusal.test.ts
+++ b/test/large-pages/segmented-remember-refusal.test.ts
@@ -102,8 +102,8 @@ for (const kind of testBackends()) {
expect(e.canonicalCode).toBe('page_body_segmented');
expect(e.writeError).toBe('page_body_segmented');
expect(e.message).toContain(slug);
- expect(e.fix?.mcp).toEqual({ tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false } });
- expect(e.fix?.argv).toEqual(['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false']);
+ expect(e.fix?.mcp).toEqual({ tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false, visibility: 'world', kind: 'fact' } });
+ expect(e.fix?.argv).toEqual(['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false', '--visibility', 'world', '--kind', 'fact']);
const render: RenderContext = { transport: 'stdio', surface: 'full', isCallable: () => true, preapproved: () => false, routing: { brain: 'host', source: sourceId } };
const envelope = toAgentError(e, { transport: 'stdio', op: 'remember', mutating: true, idempotent: true, render }) as unknown as Record<string, any>;
expect(envelope.code).toBe('page_body_segmented');
diff --git a/test/visibility-fail-closed-derived-writes.test.ts b/test/visibility-fail-closed-derived-writes.test.ts
new file mode 100644
index 0000000000..1e58f683e1
--- /dev/null
+++ b/test/visibility-fail-closed-derived-writes.test.ts
@@ -0,0 +1,330 @@
+/**
+ * Derived and retried writes never land broader than their source (fail closed).
+ *
+ * - Facts auto-extracted from a `visibility: private` page were stamped with the
+ * brain default; with `facts.default_visibility=world` they came out world, and
+ * a fact with no fence page was then returned to remote callers by recall and the
+ * entity card. They are private now, on the page-write backstop and on
+ * extract_facts with a private `source_slug`.
+ * - `remember` with no visibility hard-defaulted to world: a reworded retry that
+ * dropped the parameter widened a private save. It now resolves private for a
+ * private target page or an explicit private brain default, and stays world
+ * otherwise (the v1 contract).
+ * - A page marked private only by a privacy alias (`access`, `confidentiality`)
+ * counts as private for everything derived from it; remote page reads honor the
+ * aliases only behind `visibility.honor_aliases` (default off).
+ * - Connector re-renders keep a page's private label; Google private events render private.
+ * - The doctor check lists what is already labelled wider than its source, and the
+ * visibility repair previews it and changes it only with --apply.
+ *
+ * PGLite and Postgres (DATABASE_URL); stub transports, zero model calls; synthetic names.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { runFactsBackstop } from '../src/core/facts/backstop.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { derivedVisibilityCheck } from '../src/commands/doctor/checks/derived-visibility.ts';
+import { visibilityRepair } from '../src/core/repair/visibility.ts';
+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+import { effectiveVisibility, isDerivationPrivate } from '../src/core/search/private-visibility.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { renderCalendarEventPage, withPrivateVisibility } from '../src/core/google/google-render.ts';
+import { importRendered } from '../src/core/google/sweep-shared.ts';
+import type { CalendarEventData } from '../src/core/google/types.ts';
+import { segmentedRememberRefusal } from '../src/core/persistence/verb-errors.ts';
+
+const DIMS = 1536;
+const PERSON = 'people/alice-example';
+const PRIVATE_PERSON = 'people/dana-example';
+const NOTE = 'notes/private-session-example';
+const BODY = 'Alice Example shared the confidential acquisition terms of the example company during a private session. '.repeat(2);
+const CLAIM = 'Alice Example shared the confidential acquisition terms';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push(engine);
+ } else {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(isolated.engine);
+ closePostgres = isolated.close;
+ }
+ }
+}, 120_000);
+afterAll(async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ resetGateway();
+});
+
+function stubExtraction(fact: string) {
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({ facts: [{ fact, kind: 'fact', entity: PERSON, confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' }));
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({
+ embeddings: values.map(() => Array.from({ length: DIMS }, (_, i) => (i === 0 ? 1 : 0))) })) as never);
+}
+
+const ctxFor = (engine: BrainEngine, sourceId: string, remote: boolean) => ({ engine, config: { engine: engine.kind }, remote, sourceId, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;
+
+/** A fresh source holding a world person page, a private person page and a private note mentioning the world person. */
+async function source(engine: BrainEngine, managed: boolean) {
+ const sourceId = `vis-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [managed]);
+ const put = (slug: string, type: string, title: string, body: string, frontmatter: Record<string, unknown>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.putPage(slug, { type, title, compiled_truth: body, timeline: '', frontmatter }, { sourceId }), TEST_WRITE_ATTRIBUTION));
+ await put(PERSON, 'person', 'Alice Example', 'Alice Example is a person.', {});
+ await put(PRIVATE_PERSON, 'person', 'Dana Example', 'Dana Example is a person.', { visibility: 'private' });
+ await put(NOTE, 'note', 'Session notes', BODY, { visibility: 'private' });
+ return { sourceId, local: ctxFor(engine, sourceId, false), remote: ctxFor(engine, sourceId, true) };
+}
+
+async function factRows(engine: BrainEngine, sourceId: string) {
+ return engine.executeRaw<{ id: number; fact: string; visibility: string }>('SELECT id,fact,visibility FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY id', [sourceId]);
+}
+
+/** What a remote (MCP) caller can read about the world person: recall's facts and the entity card's recent facts. */
+async function remoteReadable(remote: OperationContext) {
+ const recall = await operationsByName.recall!.handler(remote, { entity: PERSON }) as { facts: Array<{ fact: string }> };
+ const card = await operationsByName.entity!.handler(remote, { name: PERSON }) as { card?: { recent_facts?: Array<{ fact: string }> } };
+ return [...recall.facts.map(f => f.fact), ...(card.card?.recent_facts ?? []).map(f => f.fact)];
+}
+
+async function onEachEngine(body: (engine: BrainEngine) => Promise<void>) {
+ for (const engine of engines) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-visibility-'));
+ try { await withEnv({ GBRAIN_HOME: home }, () => body(engine)); }
+ finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw("DELETE FROM config WHERE key='facts.default_visibility'");
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+ }
+}
+
+describe('facts extracted from a private page stay private', () => {
+ test('page-write backstop on a world-default brain: the fact is private and remote callers cannot read it', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, false);
+ await engine.setConfig('facts.default_visibility', 'world');
+ stubExtraction(CLAIM);
+ const result = await runFactsBackstop({ slug: NOTE, type: 'note', compiled_truth: BODY, frontmatter: { visibility: 'private' } },
+ { engine, config: { engine: engine.kind } as never, sourceId: s.sourceId, sessionId: null, source: 'mcp:put_page', mode: 'inline', visibility: 'world' });
+ expect((result as { inserted?: number }).inserted).toBe(1);
+ expect((await factRows(engine, s.sourceId)).map(r => [r.fact, r.visibility])).toEqual([[CLAIM, 'private']]);
+ expect(await remoteReadable(s.remote)).not.toContain(CLAIM);
+ expect((await derivedVisibilityCheck(engine, s.sourceId)).details).toMatchObject({ world_facts_from_private_sources: 0 });
+ });
+ }, 120_000);
+
+ test('a world page still yields world facts under a world default (no over-tightening)', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, false);
+ await engine.setConfig('facts.default_visibility', 'world');
+ stubExtraction(CLAIM);
+ await runFactsBackstop({ slug: 'notes/open-example', type: 'note', compiled_truth: BODY, frontmatter: {} },
+ { engine, config: { engine: engine.kind } as never, sourceId: s.sourceId, sessionId: null, source: 'mcp:put_page', mode: 'inline', visibility: 'world' });
+ expect((await factRows(engine, s.sourceId)).map(r => r.visibility)).toEqual(['world']);
+ });
+ }, 120_000);
+
+ test('extract_facts on a managed brain with a private source_slug writes private even when world was asked for', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, true);
+ stubExtraction(CLAIM);
+ const r = await operationsByName.extract_facts!.handler(s.local, { turn_text: BODY, visibility: 'world', source_slug: NOTE }) as { inserted: number };
+ expect(r.inserted).toBe(1);
+ expect((await factRows(engine, s.sourceId)).map(row => [row.fact, row.visibility])).toEqual([[CLAIM, 'private']]);
+ expect(await remoteReadable(s.remote)).not.toContain(CLAIM);
+ });
+ }, 120_000);
+});
+
+describe('remember without a visibility never widens', () => {
+ const remember = (ctx: OperationContext, params: Record<string, unknown>) =>
+ operationsByName.remember!.handler(ctx, { provenance: 'synthetic test', infer_entity: false, ...params }) as Promise<{ id: string; status: string }>;
+ const visibilityOf = async (engine: BrainEngine, id: string) =>
+ (await engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [Number(id)]))[0]?.visibility;
+
+ test('onto a private entity page it saves private; an explicit world is honored; a world page keeps the world default', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, true);
+ const onPrivate = await remember(s.local, { fact: 'Dana Example prefers morning meetings', entity: PRIVATE_PERSON });
+ expect(await visibilityOf(engine, onPrivate.id)).toBe('private');
+ const onWorld = await remember(s.local, { fact: 'Alice Example prefers morning meetings', entity: PERSON });
+ expect(await visibilityOf(engine, onWorld.id)).toBe('world');
+ const explicit = await remember(s.local, { fact: 'Dana Example uses a standing desk', entity: PRIVATE_PERSON, visibility: 'world' });
+ expect(await visibilityOf(engine, explicit.id)).toBe('world');
+ });
+ }, 120_000);
+
+ test('an explicit private brain default applies to remember; the same request_id replays the same private fact', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, true);
+ await engine.setConfig('facts.default_visibility', 'private');
+ const request_id = randomUUID();
+ const first = await remember(s.local, { fact: 'Alice Example signed the renewal', entity: PERSON, request_id });
+ expect(await visibilityOf(engine, first.id)).toBe('private');
+ const replay = await remember(s.local, { fact: 'Alice Example signed the renewal', entity: PERSON, request_id });
+ expect(replay.id).toBe(first.id);
+ expect((await factRows(engine, s.sourceId)).filter(r => r.fact === 'Alice Example signed the renewal')).toHaveLength(1);
+ expect(await remoteReadable(s.remote)).not.toContain('Alice Example signed the renewal');
+ });
+ }, 120_000);
+});
+
+describe('privacy aliases (access, confidentiality) count for everything derived', () => {
+ const putAliased = (engine: BrainEngine, sourceId: string, slug: string, type: string, frontmatter: Record<string, unknown>, body = 'Synthetic body.') =>
+ engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.putPage(slug, { type, title: slug, compiled_truth: body, timeline: '', frontmatter },
+ { sourceId }), TEST_WRITE_ATTRIBUTION));
+
+ test('the shared helper reads the alias values case-insensitively and nothing else', () => {
+ for (const fm of [{ access: 'private' }, { access: ' Restricted ' }, { access: 'CONFIDENTIAL' }, { confidentiality: 'secret' }, { confidentiality: 'Private' }]) {
+ expect(isDerivationPrivate({ type: 'meeting', frontmatter: fm })).toBe(true);
+ expect(effectiveVisibility({ kind: 'page', page: { type: 'meeting', frontmatter: fm } })).toBe('private');
+ }
+ for (const fm of [{ access: 'work' }, { access: 'public' }, { confidentiality: 'internal' }, {}]) {
+ expect(isDerivationPrivate({ type: 'meeting', frontmatter: fm })).toBe(false);
+ }
+ });
+
+ test('remember onto an aliased entity page and extraction from an aliased page both write private', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, true);
+ await putAliased(engine, s.sourceId, 'people/erin-example', 'person', { access: 'private', confidentiality: 'confidential' });
+ const saved = await operationsByName.remember!.handler(s.local, { fact: 'Erin Example agreed to the term sheet', entity: 'people/erin-example',
+ provenance: 'synthetic test', infer_entity: false }) as { id: string };
+ expect((await engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [Number(saved.id)]))[0]!.visibility).toBe('private');
+ await putAliased(engine, s.sourceId, 'meetings/session-example', 'meeting', { access: 'restricted' }, BODY);
+ stubExtraction(CLAIM);
+ await operationsByName.extract_facts!.handler(s.local, { turn_text: BODY, visibility: 'world', source_slug: 'meetings/session-example' });
+ expect((await factRows(engine, s.sourceId)).find(r => r.fact === CLAIM)?.visibility).toBe('private');
+ });
+ }, 120_000);
+
+ test('remote page reads honor the aliases only with visibility.honor_aliases on', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, false);
+ await putAliased(engine, s.sourceId, 'meetings/aliased-example', 'meeting', { access: 'private' });
+ const read = () => operationsByName.get_page!.handler(s.remote, { slug: 'meetings/aliased-example' }).then(() => true, () => false);
+ expect(await read()).toBe(true);
+ await engine.setConfig('visibility.honor_aliases', 'true');
+ try { expect(await read()).toBe(false); }
+ finally { await engine.executeRaw("DELETE FROM config WHERE key='visibility.honor_aliases'"); }
+ expect(await read()).toBe(true);
+ });
+ }, 120_000);
+});
+
+describe('already-affected rows: listed by doctor, previewed by the repair, changed only with --apply', () => {
+ test('aliased page, its world chronicle event and a world fact extracted from it', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, false);
+ const meeting = 'meetings/aliased-session-example';
+ await engine.transaction(tx => withCoordinatedWrite(tx, [s.sourceId], async () => {
+ await tx.putPage(meeting, { type: 'meeting', title: 'Session', compiled_truth: 'A session.', timeline: '', frontmatter: { access: 'private' } }, { sourceId: s.sourceId });
+ await tx.putPage('chronicle/2026/10/session-example', { type: 'event', title: 'Session', compiled_truth: 'A session.', timeline: '',
+ frontmatter: { captured_via: 'life-chronicle:auto', visibility: 'world', event: { depth: meeting } } }, { sourceId: s.sourceId });
+ }, TEST_WRITE_ATTRIBUTION));
+ const [fact] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, fact, kind, entity_slug, visibility, source, context, valid_from)
+ VALUES ($1, $2, 'fact', $3, 'world', 'mcp:put_page', $4, now()) RETURNING id`, [s.sourceId, CLAIM, PERSON, meeting]);
+ expect(await remoteReadable(s.remote)).toContain(CLAIM);
+
+ const check = await derivedVisibilityCheck(engine, s.sourceId);
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ alias_pages_without_visibility: 1, looser_events: 1, world_facts_from_private_sources: 1,
+ world_facts_remotely_readable: 1, remotely_readable_fact_ids: [String(fact!.id)] });
+ expect(check.message).not.toContain(meeting);
+
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-visibility-repair-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const ctx = { ...s.local, config: { engine: engine.kind, embedding_disabled: true } } as OperationContext;
+ const scope = await resolveRepairScope(engine, s.sourceId);
+ const preview = await runRepair(ctx, visibilityRepair, scope, { apply: false });
+ expect(preview.affected).toBe(3);
+ expect((await engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [fact!.id]))[0]!.visibility).toBe('world');
+ expect((await engine.readPageSnapshot(meeting, { sourceId: s.sourceId }))!.page.frontmatter.visibility).toBeUndefined();
+ const applied = await runRepair(ctx, visibilityRepair, scope, { apply: true });
+ expect(applied).toMatchObject({ applied: 3, complete: true });
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ expect((await engine.readPageSnapshot(meeting, { sourceId: s.sourceId }))!.page.frontmatter.visibility).toBe('private');
+ expect((await engine.readPageSnapshot('chronicle/2026/10/session-example', { sourceId: s.sourceId }))!.page.frontmatter.visibility).toBe('private');
+ expect((await engine.executeRaw<{ visibility: string }>('SELECT visibility FROM facts WHERE id=$1', [fact!.id]))[0]!.visibility).toBe('private');
+ expect(await remoteReadable(s.remote)).not.toContain(CLAIM);
+ expect((await derivedVisibilityCheck(engine, s.sourceId)).status).toBe('ok');
+ });
+ }, 120_000);
+});
+
+describe('connector pages keep a private label', () => {
+ const event: CalendarEventData = { id: 'ev-example', summary: 'Private appointment', description: '', startIso: '2026-10-01T10:00:00Z',
+ endIso: '2026-10-01T11:00:00Z', allDay: false, organizer: null, attendees: [], location: null, hangoutLink: null, htmlLink: null,
+ status: 'confirmed', account: '[email protected]' };
+
+ test('a Google private event renders visibility: private; a default one renders no label', () => {
+ expect(renderCalendarEventPage({ ...event, private: true })!.markdown).toContain('\nvisibility: private\n---');
+ expect(renderCalendarEventPage(event)!.markdown).not.toContain('visibility:');
+ expect(withPrivateVisibility('---\ntitle: x\nvisibility: world\n---\n\nbody\n')).toBe('---\ntitle: x\nvisibility: private\n---\n\nbody\n');
+ });
+
+ test('a re-render of a page the owner made private keeps it private (tighten-only)', async () => {
+ await onEachEngine(async engine => {
+ const s = await source(engine, false);
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-connector-'));
+ try {
+ const deps = { engine, sourceId: s.sourceId, cfg: { account: '[email protected]', dir }, opts: {}, log() {}, tick() {} } as never;
+ const summary = { pagesAffected: [], chunksCreated: 0, added: 0, modified: 0 } as never;
+ const rendered = renderCalendarEventPage(event)!;
+ const slug = await importRendered(deps, rendered.relPath, rendered.markdown, undefined as never, summary, new Set());
+ const page = (await engine.readPageSnapshot(slug, { sourceId: s.sourceId }))!.page;
+ expect(page.frontmatter.visibility).toBeUndefined();
+ await engine.transaction(tx => withCoordinatedWrite(tx, [s.sourceId], () => tx.putPage(slug, { ...page, frontmatter: { ...page.frontmatter, visibility: 'private' } },
+ { sourceId: s.sourceId }), TEST_WRITE_ATTRIBUTION));
+ const moved = renderCalendarEventPage({ ...event, summary: 'Private appointment (moved)' })!;
+ await importRendered(deps, rendered.relPath, moved.markdown, undefined as never, summary, new Set());
+ const after = (await engine.readPageSnapshot(slug, { sourceId: s.sourceId }))!.page;
+ expect(after.title).toBe('Private appointment (moved)');
+ expect(after.frontmatter.visibility).toBe('private');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ });
+ }, 120_000);
+});
+
+describe('the segmented-entity retry keeps the original call', () => {
+ test('its fix carries the resolved visibility, kind and ttl; without them visibility is an input, never the world default', () => {
+ const carried = segmentedRememberRefusal(PRIVATE_PERSON, 'default', false, { visibility: 'private', kind: 'preference', ttl: '30d' }).fix!;
+ expect(carried.mcp!.arguments).toMatchObject({ visibility: 'private', kind: 'preference', ttl: '30d', infer_entity: false });
+ expect(carried.argv).toEqual(expect.arrayContaining(['--visibility', 'private']));
+ const bare = segmentedRememberRefusal(PRIVATE_PERSON, 'default', false).fix!;
+ expect(bare.mcp!.arguments).toMatchObject({ visibility: '<VISIBILITY>' });
+ expect(bare.inputs!.map(i => i.name)).toContain('VISIBILITY');
+ });
+});