Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(visibility): honor_aliases adds no SQL while off; classify the repair writer; connector label read stays light

garrytan178cc31a1794
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index f93699fd3a..dac5445d2d 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -266,4 +266,5 @@ src/core/belief/purge.ts 1 engine_guard bumpPurgeEpoch updates only sources.purg
src/core/belief/purge-mirror.ts 4 engine_guard W1 restore replay (BELIEF_LEDGER.md 8) of purges newer than the archive: runs only inside the backup restore's single transaction before the restored root is published, granting gbrain.write_sources for that one source in that transaction; its fact, take and page deletes repeat what purge_fact and purgePageInTransaction removed.
src/core/persistence/links-extraction-holds.ts 2 engine_guard GBRA-130 A-1: records and clears only the derived pages.links_extract_failure column (a stale-extraction failure record outside the managed writer guard tracked set, like the attendance marker); it touches no canonical body, title, type, tag or frontmatter column.
src/core/repair/url-clone-fences.ts 3 engine_guard GBRA-130 C-2: unmanaged brains only (refused on managed). Keeps the fence rows the database already holds database-only in a maintenance transaction, then imports the clone file's HEAD bytes through importFromContent before restoring the file; preview-bound (--expect) with destructive consent and a file backup.
+src/core/repair/visibility.ts 1 coordinator `gbrain repair visibility --apply` (GBRA-159) only tightens database-only active facts from world to private when their source page is private. On a managed brain the UPDATE runs only inside the managed_maintenance_tighten_fact_visibility publication (owner-checked by maintenancePreflight, page key locked); an unmanaged brain runs it in one maintenanceTransaction. The UPDATE rechecks visibility='world', row_num IS NULL and expired_at IS NULL under the row lock. Fenced rows are never updated here: they change in the page through a revision-bound put_page.
src/core/facts/file-body-guard.ts 1 engine_guard #6982 replaceStoredBody mirrors a checkout file body over the page row only inside its caller's maintenanceTransaction, after re-reading the row under a row lock and confirming it still equals the body the caller compared, and saves a page_versions row first; on a managed brain the canonical table trigger refuses the write outside the coordinator.
diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.ts
index 50a8a37826..df0e58bd6c 100644
--- a/src/core/google/sweep-shared.ts
+++ b/src/core/google/sweep-shared.ts
@@ -130,8 +130,9 @@ export async function importRendered(
): 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);
+ const [labels] = await deps.engine.executeRaw<{ type: string; frontmatter: unknown }>(
+ 'SELECT type, frontmatter FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [deps.sourceId, slug]);
+ if (labels && isPrivatePage(labels)) markdown = withPrivateVisibility(markdown);
if (deps.managed) {
const result = await deps.managed.importMarkdown(relPath, markdown);
if (result.status === 'imported') {
@@ -146,6 +147,7 @@ export async function importRendered(
}
const filePath = join(deps.cfg.dir, relPath);
assertContained(deps.cfg.dir, filePath);
+ 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/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 097db5ed33..2e0b3062d6 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -94,7 +94,7 @@ function declaredLineagePrivateSql(p: string): string {
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 (${alias}.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql(alias)} AND ${HONOR_ALIASES_SQL}))`;
+ ${honorAliasEngines.size > 0 ? `AND NOT (${alias}.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql(alias)})` : ''})`;
}
/**
@@ -161,9 +161,14 @@ export function privacyAliasSql(alias: string): string {
`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'))`;
+/**
+ * Brains in this process whose operator set `visibility.honor_aliases`, as last
+ * read by resolveExcludePrivatePages (the resolver every remote read runs before
+ * it builds SQL). The fragments are synchronous, so the flag is process-wide:
+ * one opted-in brain makes every brain in the process hide alias-only pages,
+ * which only ever hides more. Off (the default), the SQL carries no alias test.
+ */
+const honorAliasEngines = new Set<BrainEngine>();
/** 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 {
@@ -283,6 +288,7 @@ let cache = new WeakMap<BrainEngine, { at: number; expose: boolean }>();
/** Test helper: drop the per-engine config cache. */
export function __resetPrivateVisibilityCacheForTests(): void {
cache = new WeakMap();
+ honorAliasEngines.clear();
}
/**
@@ -308,6 +314,12 @@ export async function resolveExcludePrivatePages(
} catch {
expose = false; // config unreadable → enforce (fail-closed)
}
+ try {
+ const honor = (await engine.getConfig(HONOR_ALIASES_KEY))?.trim().toLowerCase() ?? '';
+ if (['true', '1', 'on', 'yes'].includes(honor)) honorAliasEngines.add(engine); else honorAliasEngines.delete(engine);
+ } catch {
+ // unreadable: keep the last value read
+ }
cache.set(engine, { at: Date.now(), expose });
}
return !expose;
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index c4d9fc5beb..8956f59ff7 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -67,6 +67,7 @@ const EXEMPT: Record<string, string> = {
'src/core/repair/atoms-restore.ts': 'restores an owner-approved retired atom to its own earlier version (lifecycle); no new text',
'src/core/repair/take-supersession.ts': 'owner repair of take supersession pointers',
'src/core/repair/timeline-comments.ts': 'owner repair of timeline comment markup',
+ 'src/core/repair/visibility.ts': 'owner repair behind a preview: only tightens existing fact rows from world to private (no new text); fenced rows and page labels publish through put_page, which runs the gate',
'src/core/schema-pack/page-to-alias.ts': 'schema-pack retype of existing pages',
'src/core/schema-pack/page-to-link.ts': 'schema-pack retype of existing pages',
'src/core/schema-pack/retype.ts': 'schema-pack retype of existing pages',
diff --git a/test/visibility-fail-closed-derived-writes.test.ts b/test/visibility-fail-closed-derived-writes.test.ts
index 9c88b24fa4..224150514e 100644
--- a/test/visibility-fail-closed-derived-writes.test.ts
+++ b/test/visibility-fail-closed-derived-writes.test.ts
@@ -36,7 +36,7 @@ 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 { __resetPrivateVisibilityCacheForTests, 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';
@@ -250,8 +250,9 @@ describe('privacy aliases (access, confidentiality) count for everything derived
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');
+ __resetPrivateVisibilityCacheForTests();
try { expect(await read()).toBe(false); }
- finally { await engine.executeRaw("DELETE FROM config WHERE key='visibility.honor_aliases'"); }
+ finally { await engine.executeRaw("DELETE FROM config WHERE key='visibility.honor_aliases'"); __resetPrivateVisibilityCacheForTests(); }
expect(await read()).toBe(true);
});
}, 120_000);