Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): guarded ontology supersession in mergeOntologyFact (both engines) with a contested proposal; ontology observations declare agent_written (#5575 A5)

garrytan021d42080f54
diff --git a/src/core/chronicle/ontology.ts b/src/core/chronicle/ontology.ts
index 2d9e271f37..13da21b32f 100644
--- a/src/core/chronicle/ontology.ts
+++ b/src/core/chronicle/ontology.ts
@@ -2,6 +2,7 @@
// The ontology rides the `facts` table; these are the deterministic bits the
// engine methods (mergeOntologyFact / getOntology / …) lean on.
import { computeContentHash } from '../ingestion/types.ts';
+import { trustRankSql } from '../trust/tier.ts';
/**
* Deterministic dedup key for an ontology value. Normalized (trim + lowercase +
@@ -54,3 +55,11 @@ export function isBackdatedObservation(validFrom: string | null, currentValidFro
return validFrom != null && currentValidFrom != null
&& new Date(validFrom).getTime() < new Date(currentValidFrom).getTime();
}
+
+/**
+ * #5575 A5: a new observation closes the current open stint only when its
+ * writer is at least as trusted as that stint (the transaction's declared
+ * tier, `unknown` when undeclared). Appended to the closing UPDATE in both
+ * engines; a guarded stint stays open and the caller files a contested proposal.
+ */
+export const ONTOLOGY_SUPERSEDE_GUARD = ` AND ${trustRankSql('trust_tier')} <= ${trustRankSql(`COALESCE(NULLIF(current_setting('gbrain.write_trust_tier', true), ''), 'unknown')`)}`;
diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.ts
index f0e4d5ea77..60aed64545 100644
--- a/src/core/ops/chronicle.ts
+++ b/src/core/ops/chronicle.ts
@@ -208,8 +208,16 @@ const ontology_propose: Operation = {
});
// A managed brain commits the observation as a coordinated database-only
// write serialized on the entity's page key; unmanaged brains write directly.
- const managed = await coordinatedDatabaseWrite(ctx, 'ontology_propose', entitySlug, [entitySlug], merge);
- return managed ? managed.value : merge(ctx.engine, ctx.sourceId);
+ // #5575: an agent observation never closes a more trusted stint; it is stored contested for the owner (A5).
+ const { ontologyWriteTrust, contestOntologySupersession } = await import('../trust/supersede-handlers.ts');
+ const { maintenanceTransaction } = await import('../persistence/attribution.ts');
+ const trust = ontologyWriteTrust(ctx);
+ const guarded = async (engine: typeof ctx.engine, sourceId: string | undefined) => {
+ const result = await merge(engine, sourceId);
+ return { ...result, ...await contestOntologySupersession(engine, sourceId ?? 'default', entitySlug, String(p.dimension), result) };
+ };
+ const managed = await coordinatedDatabaseWrite(ctx, 'ontology_propose', entitySlug, [entitySlug], guarded, trust);
+ return managed ? managed.value : maintenanceTransaction(ctx.engine, tx => guarded(tx, ctx.sourceId), trust);
},
cliHints: { name: 'ontology-add', positional: ['entity', 'dimension', 'value'] },
};
diff --git a/src/core/persistence/database-write.ts b/src/core/persistence/database-write.ts
index 2011e95228..8fff2ee3f6 100644
--- a/src/core/persistence/database-write.ts
+++ b/src/core/persistence/database-write.ts
@@ -7,6 +7,7 @@ import { managedPersistenceEnabled } from './ownership.ts';
import { initializeLocalPersistence } from './page-mutations.ts';
import { withCoordinatedWrite } from './context.ts';
import { principalAttribution } from './attribution.ts';
+import type { WriteTrust } from '../trust/tier.ts';
/**
* A coordinated, database-only write on a managed brain: rows with no
@@ -18,7 +19,7 @@ import { principalAttribution } from './attribution.ts';
* brain; the caller keeps its legacy path.
*/
export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operation: string, authoritySlug: string,
- lockSlugs: readonly string[], write: (engine: BrainEngine, sourceId: string) => Promise<T>): Promise<{ value: T } | null> {
+ lockSlugs: readonly string[], write: (engine: BrainEngine, sourceId: string) => Promise<T>, trust?: WriteTrust): Promise<{ value: T } | null> {
if (!await managedPersistenceEnabled(ctx.engine)) return null;
assertPersistenceAccepting(ctx.engine);
const sourceId = ctx.sourceId ?? 'default';
@@ -42,6 +43,6 @@ export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operati
await authorizeWrite(tx, authority, operation, authoritySlug, true);
await tx.lockPageKeys(lockSlugs.map(slug => ({ sourceId, slug })));
return write(tx, sourceId);
- }, principalAttribution(authority.principal)));
+ }, { ...principalAttribution(authority.principal), ...(trust ? { trust } : {}) }));
return { value };
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index d073d63031..596656201e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -68,7 +68,7 @@ import {
import {
valueHash,
normalizeDimension,
- isNovelDimension, isBackdatedObservation,
+ isNovelDimension, isBackdatedObservation, ONTOLOGY_SUPERSEDE_GUARD,
} from './chronicle/ontology.ts';
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
import { runMigrations } from './migrate.ts';
@@ -2112,11 +2112,11 @@ export class PGLiteEngine implements BrainEngine {
const forward = validFrom == null || current.valid_from == null
|| new Date(validFrom).getTime() >= new Date(current.valid_from).getTime();
if (forward) {
- await this.db.query(
- `UPDATE facts SET valid_until = COALESCE($1::timestamptz, now()), superseded_by = $2 WHERE id = $3 AND valid_until IS NULL`,
+ const closed = await this.db.query(
+ `UPDATE facts SET valid_until = COALESCE($1::timestamptz, now()), superseded_by = $2 WHERE id = $3 AND valid_until IS NULL${ONTOLOGY_SUPERSEDE_GUARD} RETURNING id`,
[validFrom, newId, current.id],
);
- supersededId = current.id;
+ supersededId = closed.rows.length ? current.id : null;
}
}
return { action: supersededId ? 'superseded_prior' : 'inserted', factId: newId, supersededId };
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index d92ca200f5..bf603aa22a 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -46,7 +46,7 @@ import { CheckoutGauge, PoisonedDiscardCounter, type PoolGaugeSnapshot } from '.
import {
valueHash,
normalizeDimension,
- isNovelDimension, isBackdatedObservation,
+ isNovelDimension, isBackdatedObservation, ONTOLOGY_SUPERSEDE_GUARD,
} from './chronicle/ontology.ts';
import { logDbDisconnect } from './audit/db-disconnect-audit.ts';
import { logPoolRecovery } from './audit/pool-recovery-audit.ts';
@@ -1815,9 +1815,9 @@ export class PostgresEngine implements BrainEngine {
|| new Date(validFrom).getTime() >= new Date(current.valid_from).getTime();
if (forward) {
// Close the prior row's valid window at the new fact's valid_from (or now()).
- await sql`UPDATE facts SET valid_until = COALESCE(${validFrom}::timestamptz, now()), superseded_by = ${newId}
- WHERE id = ${current.id} AND valid_until IS NULL`;
- supersededId = Number(current.id);
+ const closed = await sql`UPDATE facts SET valid_until = COALESCE(${validFrom}::timestamptz, now()), superseded_by = ${newId}
+ WHERE id = ${current.id} AND valid_until IS NULL${sql.unsafe(ONTOLOGY_SUPERSEDE_GUARD)} RETURNING id`;
+ supersededId = closed.length ? Number(current.id) : null;
}
}
return { action: supersededId ? 'superseded_prior' : 'inserted', factId: newId, supersededId };
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index d050beb7f9..ca33392838 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -15,7 +15,8 @@ import type { BrainEngine } from '../engine.ts';
import {
applyProposalAction, registerPairProposalStore, type PairProposal, type PairProposalStore, type ProposalActionResult,
} from '../facts/proposal-supersede.ts';
-import { withTrustPromotion, withWriteAttribution } from '../persistence/context.ts';
+import { currentWriteTrust, withTrustPromotion, withWriteAttribution } from '../persistence/context.ts';
+import { normalizeDimension } from '../chronicle/ontology.ts';
import { verbError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import {
@@ -23,7 +24,7 @@ import {
type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,
} from './proposals.ts';
import { tierRaiseFix } from './confirm.ts';
-import { compareTrust, storedTrustTier, type TrustTier } from './tier.ts';
+import { compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
/** I3: a write at `writer` may supersede, expire or forget a row at `target` only when it is at least as trusted. */
export function supersessionGuarded(writer: TrustTier | null | undefined, target: unknown): boolean {
@@ -87,6 +88,29 @@ export function remoteForgetRaced(factId: number): OperationError {
return error;
}
+/** The declared tier of an `ontology_propose` observation: an agent write (remote or local CLI). */
+export function ontologyWriteTrust(ctx: { remote?: boolean }): WriteTrust {
+ return effectiveWriteTrust({ channel: 'agent_written', origin: { channel: `${ctx.remote === false ? 'cli' : 'mcp'}:ontology_propose` } });
+}
+
+/**
+ * After mergeOntologyFact inserted a new stint without closing the current one
+ * (the engines' ONTOLOGY_SUPERSEDE_GUARD refused because it is more trusted),
+ * files the supersede_fact proposal and returns the additive `contested` field.
+ */
+export async function contestOntologySupersession(tx: BrainEngine, sourceId: string, entitySlug: string, dimension: string,
+ result: { action: string; factId: number | null }): Promise<{ contested?: { proposal_ref: string } }> {
+ if (result.action !== 'inserted' || result.factId === null) return {};
+ const writer = (await currentWriteTrust(tx))?.tier ?? 'unknown';
+ const [current] = await tx.executeRaw<{ id: number; trust_tier: string }>(
+ `SELECT id, trust_tier FROM facts WHERE source_id = $1 AND entity_slug = $2 AND dimension = $3 AND id <> $4
+ AND expired_at IS NULL AND valid_until IS NULL AND (dim_status IS NULL OR dim_status = 'active')
+ ORDER BY valid_from DESC NULLS LAST, confidence DESC, id DESC LIMIT 1`, [sourceId, entitySlug, normalizeDimension(dimension), result.factId]);
+ if (!current || !supersessionGuarded(writer, current.trust_tier)) return {};
+ return { contested: await recordContestedFact(tx, { sourceId, oldId: Number(current.id), oldTier: storedTrustTier(current.trust_tier),
+ newId: result.factId, newTier: writer, guard: 'ontology' }) };
+}
+
// ---------------------------------------------------------------------------
// trust_proposals as a checked-supersede store
// ---------------------------------------------------------------------------
diff --git a/test/trust-guarded-supersession.test.ts b/test/trust-guarded-supersession.test.ts
index 48876d0220..1d6bf0c6ea 100644
--- a/test/trust-guarded-supersession.test.ts
+++ b/test/trust-guarded-supersession.test.ts
@@ -247,3 +247,26 @@ describe('guarded takes supersession and the takes gate', () => {
}
}), 90_000);
});
+
+describe('guarded ontology supersession (mergeOntologyFact, both engines)', () => {
+ test('an agent observation does not close a confirmed stint: it is inserted contested; an equal-tier observation closes as before', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ await run(b.local, 'put_page', { slug: 'people/gina-example', content: page('Gina', 'Gina.') });
+ const first = await run(b.local, 'ontology_propose', { entity: 'people/gina-example', dimension: 'role', value: 'founder', visibility: 'world' });
+ expect(first.action).toBe('inserted');
+ await confirmFact(b, Number(first.factId));
+ const second = await run(b.remote, 'ontology_propose', { entity: 'people/gina-example', dimension: 'role', value: 'advisor', visibility: 'world', valid_from: '2030-01-01' });
+ expect(second.action).toBe('inserted');
+ expect(second.supersededId).toBeNull();
+ expect(second.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ const [old] = await engine.executeRaw<{ valid_until: unknown; superseded_by: number | null }>('SELECT valid_until, superseded_by FROM facts WHERE id=$1', [Number(first.factId)]);
+ expect(old).toMatchObject({ valid_until: null, superseded_by: null });
+ await run(b.local, 'put_page', { slug: 'people/hank-example', content: page('Hank', 'Hank.') });
+ const third = await run(b.remote, 'ontology_propose', { entity: 'people/hank-example', dimension: 'role', value: 'engineer', visibility: 'world' });
+ const fourth = await run(b.remote, 'ontology_propose', { entity: 'people/hank-example', dimension: 'role', value: 'manager', visibility: 'world', valid_from: '2030-01-01' });
+ expect(fourth.supersededId).toBe(Number(third.factId));
+ expect(fourth.contested).toBeUndefined();
+ }
+ }), 90_000);
+});