Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

A visibility repair makes a more trusted fenced fact private in place instead of leaving a world copy (GST-2487)

garrytan9de6a8693335
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index 2b2f90f0a2..95dcc97a72 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -256,11 +256,14 @@ export async function prepareFactVisibilityTighten(engine: BrainEngine, row: Wri
/**
* One fact item: a fenced row gets `private` in its page's `## Facts` fence by a
- * revision-bound label write (labelWrite; 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. A fenced row that stays world and live is
- * reported, never as done: `fact_left_readable` when remote callers can read it now, `fact_left_world` when only its
- * page's privacy hides it (worldFactsFromPrivateSources `readable`).
+ * revision-bound label write (labelWrite; the projection then stores it private, and a
+ * more trusted row turns private in place, trust/fence-guard.ts); a database-only row is
+ * updated in place (a database-only maintenance request on a managed brain). On a brain
+ * without managed persistence the page import does not re-project the fence, so the fenced
+ * row is made private in place there too, keeping its id and tier (GST-2487). A page stored
+ * in segments is left for the owner. A fenced row that stays world and live is reported,
+ * never as done: `fact_left_readable` when remote callers can read it now, `fact_left_world`
+ * when only its page's privacy hides it (worldFactsFromPrivateSources `readable`).
*/
const leftWorld = (fact: { id: number; readable: boolean }, why: string): RepairItemOutcome => fact.readable
? { applied: false, outcome: 'fact_left_readable', detail: { fact_id: Number(fact.id) }, reason: `${why}; the fact row is still world, so remote callers can still read it` }
@@ -290,6 +293,9 @@ async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: R
if (held) return held;
const [stored] = await ctx.engine.executeRaw<{ visibility: string; live: boolean }>('SELECT visibility, expired_at IS NULL AS live FROM facts WHERE id=$1', [factId]);
if (!stored || stored.visibility === 'private' || !stored.live) return true;
+ if (!await managedPersistenceEnabled(ctx.engine) && (await maintenanceTransaction(ctx.engine, tx => tx.executeRaw(
+ `UPDATE facts SET visibility='private' WHERE source_id=$1 AND id=$2 AND row_num=$3 AND visibility='world' AND expired_at IS NULL RETURNING id`,
+ [item.source_id, factId, fact.row_num]))).length > 0) return true;
return leftWorld(fact, 'its fence row was written private, but the original row is more trusted than the repair and was kept beside it');
}
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index 438cdeb2d1..452b815f52 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -8,7 +8,9 @@
* - Guarded supersession: a row more trusted than the writer is never expired
* by it. The row is detached from its fence position and stays active; when
* the writer only renumbered it (same claim and visibility elsewhere in the
- * fence, free slot) it moves there instead. Otherwise the new row at its old
+ * fence, free slot) it moves there instead, and when the writer only made it
+ * private (same claim, world to private, GST-2487) it moves there and turns
+ * private in place, keeping its id and tier. Otherwise the new row at its old
* position is inserted contested with a `supersede_fact` proposal, or, when
* the writer removed it, a `forget` proposal asks the owner.
* - Row gate (ENG-1): every new fence row is gated like other fact writers at
@@ -66,16 +68,17 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
.map(r => Number(r.row_num)));
let rows = input.rows;
const contested: typeof guarded = [];
- const moves: Array<{ id: number; row_num: number }> = [];
+ const moves: Array<{ id: number; row_num: number; visibility: string }> = [];
for (const g of guarded) {
- const target = rows.find(r => r.fact === g.fact && r.visibility === g.visibility && !occupied.has(r.row_num));
+ const target = rows.find(r => r.fact === g.fact && !occupied.has(r.row_num)
+ && (r.visibility === g.visibility || (g.visibility === 'world' && r.visibility === 'private')));
if (!target) { contested.push(g); continue; }
- moves.push({ id: Number(g.id), row_num: target.row_num });
+ moves.push({ id: Number(g.id), row_num: target.row_num, visibility: target.visibility ?? g.visibility });
occupied.add(target.row_num);
rows = rows.filter(r => r !== target);
}
// #6574: every guarded row moves in one statement; each starts detached (row_num NULL), so no move collides with another.
- if (moves.length) await tx.executeRaw(`UPDATE facts f SET row_num = m.row_num FROM jsonb_to_recordset($1::text::jsonb) AS m(id bigint, row_num integer)
+ if (moves.length) await tx.executeRaw(`UPDATE facts f SET row_num = m.row_num, visibility = m.visibility FROM jsonb_to_recordset($1::text::jsonb) AS m(id bigint, row_num integer, visibility text)
WHERE f.id = m.id`, [JSON.stringify(moves)]);
const gated: Array<{ row: T; decision: GatedRowDecision }> = [];
const inserted: T[] = [];
diff --git a/test/label-only-repairs.test.ts b/test/label-only-repairs.test.ts
index 06611a4fc0..01a92e9ba6 100644
--- a/test/label-only-repairs.test.ts
+++ b/test/label-only-repairs.test.ts
@@ -120,7 +120,7 @@ for (const backend of testBackends()) describe('[' + backend + '] label-only ope
expect(onDisk(root, slug)).toBe(withLine(before, 'visibility: private'));
}, { databaseUrl, setup }), 180_000);
- test('repair visibility facts: the page keeps its tier, files no lower_page proposal, and its file changes only in the fact row', () => managedBrain(async ({ engine, root }) => {
+ test('repair visibility facts: the fence row turns private in place, the page keeps its tier, and its file changes only in the fact row', () => managedBrain(async ({ engine, root }) => {
const slug = 'notes/fact-example';
const header = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |' + NL
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|' + NL;
@@ -128,19 +128,19 @@ for (const backend of testBackends()) describe('[' + backend + '] label-only ope
+ '<!--- gbrain:facts:begin -->' + NL + NL + header + '| 1 | Alice Example works at acme-example. | fact | 1.0 | ' + visibility + ' | medium | 2026-10-01 | | test | |' + NL
+ '<!--- gbrain:facts:end -->' + NL);
await seed(engine, root, { [slug]: withFacts('world') });
+ const live = "SELECT id, visibility, trust_tier::text AS tier FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL ORDER BY id";
+ const [before] = await engine.executeRaw<{ id: number; visibility: string; tier: string }>(live, [slug]);
+ expect(before).toMatchObject({ visibility: 'world', tier: 'operator_curated' });
const { applied } = await previewApply(engine, ['visibility', '--class', 'facts']);
await settleManagedGitEffects(engine);
- // The original world row is more trusted than the repair and stays live (GST-2487): the apply must say so, never "done".
- expect(applied.applied).toBe(0);
- // The page is private, so only its privacy hides the row today: the apply says "still world", not "readable".
- expect(applied.outcomes).toMatchObject({ fact_left_world: 1 });
- expect(applied.outcomes.fact_left_readable).toBeUndefined();
- expect(applied.outcome_items).toEqual([expect.objectContaining({ item: 'default:' + slug, outcome: 'fact_left_world' })]);
- expect(renderRepairResult(applied)).toContain('NOT CLOSED: 1 fact row(s) could not be made private and are still world');
- expect(await engine.executeRaw("SELECT visibility FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL AND visibility='world'", [slug])).toEqual([{ visibility: 'world' }]);
+ // GST-2487: the more trusted row is the one made private, in place: no world copy stays live and no contest is filed.
+ expect(applied.applied).toBe(1);
+ expect(applied.outcomes ?? {}).toEqual({});
+ expect(await engine.executeRaw(live, [slug])).toEqual([{ id: before!.id, visibility: 'private', tier: 'operator_curated' }]);
expect((await page(engine, slug)).tier).toBe('operator_curated');
- expect(await engine.executeRaw("SELECT id FROM trust_proposals WHERE action='lower_page'")).toEqual([]);
+ expect(await proposals(engine)).toEqual([]);
expect(onDisk(root, slug)).toBe(withFacts('private'));
+ expect((await repair(engine, ['visibility', '--class', 'facts'])).listing ?? []).toEqual([]);
}, { databaseUrl, setup }), 180_000);
test('repair visibility --slug on a database-only page (a db_only path) writes only the label: tier and provenance kept, no file', () => managedBrain(async ({ engine, root, ctx }) => {
@@ -241,6 +241,37 @@ for (const backend of testBackends()) describe('[' + backend + '] label-only ope
} finally { rmSync(home, { recursive: true, force: true }); }
}, 180_000);
+ test('repair visibility facts turns a more trusted fence row private in place: no world copy, tier kept, no contest', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-label-repoless-facts-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const slug = 'notes/fact-example';
+ const fence = '## Facts' + NL + NL + '<!--- gbrain:facts:begin -->' + NL + NL
+ + '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |' + NL
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|' + NL
+ + '| 1 | Alice Example works at acme-example. | fact | 1.0 | world | medium | 2026-10-01 | | test | |' + NL + '<!--- gbrain:facts:end -->' + NL;
+ const content = file(slug, 'visibility: private').replace('Second paragraph.' + NL, 'Second paragraph.' + NL + NL + fence);
+ expect((await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' })).status).toBe('imported');
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => withTrustBackfill(tx, async () => {
+ await tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE source_id='default' AND slug=$1", [slug]);
+ await tx.executeRaw("INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, valid_from, trust_tier) VALUES ('default', NULL, 'Alice Example works at acme-example.', 'fact', 'world', 'medium', 'test', $1, 1, '2026-10-01', 'operator_curated')", [slug]);
+ }), TEST_WRITE_ATTRIBUTION));
+ const live = "SELECT id, visibility, trust_tier::text AS tier FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL ORDER BY id";
+ const [before] = await engine.executeRaw<{ id: number; visibility: string; tier: string }>(live, [slug]);
+ expect(before).toMatchObject({ visibility: 'world', tier: 'operator_curated' });
+ const { applied } = await previewApply(engine, ['visibility', '--source', 'default', '--class', 'facts']);
+ expect(applied.applied).toBe(1);
+ expect(applied.outcomes ?? {}).toEqual({});
+ expect(await engine.executeRaw(live, [slug])).toEqual([{ id: before!.id, visibility: 'private', tier: 'operator_curated' }]);
+ expect((await page(engine, slug)).tier).toBe('operator_curated');
+ expect(await proposals(engine)).toEqual([]);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 180_000);
+
/** A brain without managed persistence whose source `source-b` has a checkout holding the page's file. */
async function checkoutBrain(fn: (brain: { engine: BrainEngine; slug: string; path: string; before: string; row: () => Promise<{ tier: string; frontmatter: Record<string, unknown> }> }) => Promise<void>) {
const home = mkdtempSync(join(tmpdir(), 'gbrain-label-checkout-'));