Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ontology): world-only remote reads, coordinated managed writes, per-stint dedup (eval wave N1-1/N1-2/N1-3)
garrytan982a77eb8c68
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex f853f42803..0ea5851b84 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -423,7 +423,12 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/ops/chronicle.ts": ["test/e2e/ontology-merge-parity.test.ts","test/e2e/chronicle-event-projection-parity.test.ts",+ "test/e2e/managed-ontology-propose-postgres.test.ts",],+ // Eval-category wave lane C: coordinated database-only writes (manual links,+ // ontology observations) and the per-stint ontology dedup key.+ "src/core/persistence/database-write.ts": ["test/e2e/managed-ontology-propose-postgres.test.ts", "test/e2e/managed-writers-w3.test.ts"],+ "src/core/schema-migrations/v189-facts-ontology-stint-dedup.ts": ["test/e2e/ontology-merge-parity.test.ts", "test/e2e/schema-drift.test.ts"],// Schema source of truth: any change must pass the cross-engine drift gate."src/schema.sql": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],diff --git a/src/core/context/chronicle-context.ts b/src/core/context/chronicle-context.tsindex 040256f006..6afc3f02b4 100644--- a/src/core/context/chronicle-context.ts+++ b/src/core/context/chronicle-context.ts@@ -14,7 +14,7 @@ export interface ChronicleContextOpts extends PageReadScope {entities?: string[];/** Cap on timeline rows (default 50). */limit?: number;- /** Untrusted caller → diary-sourced ontology is redacted. */+ /** Untrusted caller → only world-visibility ontology, diary-sourced rows redacted. */remote?: boolean;sourceId?: string;sourceIds?: string[];@@ -44,7 +44,7 @@ export async function loadChronicleContext(const ontologies: Record<string, OntologyValue[]> = {};for (const slug of opts.entities ?? []) {- let vals = await engine.getOntology(slug, { ...scope, excludePrivate: opts.excludePrivate });+ let vals = await engine.getOntology(slug, { ...scope, excludePrivate: opts.excludePrivate, visibility: opts.remote ? ['world'] : undefined });if (opts.remote) vals = vals.filter((v) => !(v.source ?? '').startsWith('life/diary/'));if (vals.length) ontologies[slug] = vals;}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 2d69022eb1..0a2378553c 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1785,7 +1785,7 @@ export interface BrainEngine {/** Meta-ontology: which dimensions exist across the brain, and how widely. */discoverOntologyDimensions(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<OntologyDimensionStat[]>;/** Dimensions with ≥2 distinct current-open values from ≥2 provenances. */- findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]>;+ findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts['visibility'] }): Promise<OntologyConflict[]>;// Raw data/**diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.tsindex 334a481293..8450c91222 100644--- a/src/core/ops/chronicle.ts+++ b/src/core/ops/chronicle.ts@@ -142,9 +142,11 @@ const ontology_get: Operation = {asof: typeof p.asof === 'string' ? p.asof : undefined,minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,includeQuarantined: p.include_quarantined === true,+ visibility: ctx.remote === false ? undefined : ['world'],...await readPolicyOpts(ctx),});- // Remote redaction: never surface diary-sourced ontology to untrusted callers.+ // Remote redaction: world-visibility rows only (as recall), resolved before+ // DISTINCT ON; never surface diary-sourced ontology to untrusted callers.return ctx.remote !== false ? rows.filter((r) => !(r.source ?? '').startsWith('life/diary/')) : rows;},cliHints: { name: 'ontology', positional: ['entity'] },@@ -172,17 +174,24 @@ const ontology_propose: Operation = {// [ENG-8] Same unset-vs-explicit ladder as extract_facts: explicit// caller visibility wins; unset resolves facts.default_visibility.const { resolveVisibilityParam } = await import('../facts/visibility.ts');- return ctx.engine.mergeOntologyFact({- entitySlug: String(p.entity),+ const { coordinatedDatabaseWrite } = await import('../persistence/database-write.ts');+ const entitySlug = String(p.entity);+ const visibility = await resolveVisibilityParam(ctx.engine, p.visibility);+ const merge = (engine: typeof ctx.engine, sourceId: string | undefined) => engine.mergeOntologyFact({+ entitySlug,dimension: String(p.dimension),value: String(p.value),confidence: typeof p.confidence === 'number' ? p.confidence : undefined,source: typeof p.source === 'string' && p.source ? p.source : 'manual',validFrom: typeof p.valid_from === 'string' ? p.valid_from : undefined,validTo: typeof p.valid_to === 'string' ? p.valid_to : undefined,- visibility: await resolveVisibilityParam(ctx.engine, p.visibility),- sourceId: ctx.sourceId,+ visibility,+ sourceId,});+ // 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);},cliHints: { name: 'ontology-add', positional: ['entity', 'dimension', 'value'] },};@@ -210,6 +219,7 @@ const ontology_conflicts: Operation = {handler: async (ctx, p) => {const conflicts = await ctx.engine.findOntologyConflicts({minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,+ visibility: ctx.remote === false ? undefined : ['world'],...await readPolicyOpts(ctx),});if (ctx.remote === false) return conflicts;diff --git a/src/core/persistence/database-write.ts b/src/core/persistence/database-write.tsnew file mode 100644index 0000000000..b9af502fde--- /dev/null+++ b/src/core/persistence/database-write.ts@@ -0,0 +1,39 @@+import type { BrainEngine } from '../engine.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { assertPersistenceAccepting } from './service.ts';+import { authorizeWrite, submissionAuthority } from './authority.ts';+import { managedPersistenceEnabled } from './ownership.ts';+import { initializeLocalPersistence } from './page-mutations.ts';+import { withCoordinatedWrite } from './context.ts';++/**+ * A coordinated, database-only write on a managed brain: rows with no+ * canonical file (manual links, ontology observations) and no receipt. The+ * caller's durable write authority is checked for `authoritySlug`, then+ * `write` runs inside a source-scoped coordinated transaction that revalidates+ * the source incarnation and holds every `lockSlugs` page key, so it+ * serializes with publications of those pages. Returns null on an unmanaged+ * 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> {+ if (!await managedPersistenceEnabled(ctx.engine)) return null;+ assertPersistenceAccepting(ctx.engine);+ const sourceId = ctx.sourceId ?? 'default';+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>(+ 'SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');+ await initializeLocalPersistence(ctx);+ const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, authoritySlug);+ const value = await ctx.engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ const [current] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(+ 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);+ if (!current || current.archived || current.incarnation !== source.incarnation) {+ throw new OperationError('source_changed', 'The write source changed before the write.');+ }+ await authorizeWrite(tx, authority, operation, authoritySlug, true);+ await tx.lockPageKeys(lockSlugs.map(slug => ({ sourceId, slug })));+ return write(tx, sourceId);+ }));+ return { value };+}diff --git a/src/core/persistence/manual-links.ts b/src/core/persistence/manual-links.tsindex b022374239..fbd51397d6 100644--- a/src/core/persistence/manual-links.ts+++ b/src/core/persistence/manual-links.ts@@ -1,10 +1,6 @@import type { BrainEngine } from '../engine.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';-import { assertPersistenceAccepting } from './service.ts';-import { authorizeWrite, submissionAuthority } from './authority.ts';-import { managedPersistenceEnabled } from './ownership.ts';-import { initializeLocalPersistence } from './page-mutations.ts';-import { withCoordinatedWrite } from './context.ts';+import type { OperationContext } from '../ops/contract.ts';+import { coordinatedDatabaseWrite } from './database-write.ts';/*** `add_link` / `remove_link` on a managed brain (#5280): a coordinated,@@ -17,23 +13,5 @@ import { withCoordinatedWrite } from './context.ts';*/export async function coordinatedManualLinkWrite<T>(ctx: OperationContext, operation: 'add_link' | 'remove_link',from: string, to: string, write: (engine: BrainEngine, sourceId: string) => Promise<T>): Promise<{ value: T } | null> {- if (!await managedPersistenceEnabled(ctx.engine)) return null;- assertPersistenceAccepting(ctx.engine);- const sourceId = ctx.sourceId ?? 'default';- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>(- 'SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);- if (!source || source.archived) throw new OperationError('source_changed', 'The link source is not active.');- await initializeLocalPersistence(ctx);- const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, from);- const value = await ctx.engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- const [current] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(- 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);- if (!current || current.archived || current.incarnation !== source.incarnation) {- throw new OperationError('source_changed', 'The link source changed before the write.');- }- await authorizeWrite(tx, authority, operation, from, true);- await tx.lockPageKeys([{ sourceId, slug: from }, { sourceId, slug: to }]);- return write(tx, sourceId);- }));- return { value };+ return coordinatedDatabaseWrite(ctx, operation, from, [from, to], write);}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex bfab6b4548..079349f0a0 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2282,11 +2282,19 @@ export class PGLiteEngine implements BrainEngine {const current = cur.rows[0] as { id: number; value_hash: string; valid_from: string | null } | undefined;if (current && current.value_hash === vh && !isBackdatedObservation(validFrom, current.valid_from)) {+ // This provenance already observed the value during the current stint.+ const seen = await this.db.query(+ `SELECT 1 FROM facts+ WHERE source_id = $1 AND entity_slug = $2 AND dimension = $3 AND value_hash = $4 AND source_markdown_slug = $5+ AND COALESCE(valid_from,'-infinity'::timestamptz) >= COALESCE($6::timestamptz,'-infinity'::timestamptz) LIMIT 1`,+ [sourceId, obs.entitySlug, dimension, vh, obs.source, current.valid_from],+ );+ if (seen.rows.length) return { action: 'noop', factId: null, supersededId: null };const ins = await this.db.query(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, dimension, value, value_hash, dim_status,confidence, source, source_markdown_slug, valid_from, valid_until, expired_at, consolidated_into)VALUES ($1,$2,$3,'fact',$4,$5,$6,$7,$8,$9,$10,$10,COALESCE($11::timestamptz, now()),$12, now(), $13)- ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug) WHERE dimension IS NOT NULL+ ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE dimension IS NOT NULLDO NOTHING RETURNING id`,[sourceId, obs.entitySlug, factText, visibility, dimension, obs.value, vh, status, conf, obs.source, validFrom, validUntil, current.id],);@@ -2299,7 +2307,7 @@ export class PGLiteEngine implements BrainEngine {`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, dimension, value, value_hash, dim_status,confidence, source, source_markdown_slug, valid_from, valid_until)VALUES ($1,$2,$3,'fact',$4,$5,$6,$7,$8,$9,$10,$10,COALESCE($11::timestamptz, now()),$12)- ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug) WHERE dimension IS NOT NULL+ ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE dimension IS NOT NULLDO NOTHING RETURNING id`,[sourceId, obs.entitySlug, factText, visibility, dimension, obs.value, vh, status, conf, obs.source, validFrom, validUntil],);@@ -2332,12 +2340,14 @@ export class PGLiteEngine implements BrainEngine {// Page-visibility gate on the provenance page, applied BEFORE DISTINCT ON// so the untrusted caller resolves the newest value they may see.const privacy = opts?.excludePrivate ? `AND ${privateProvenanceFilterFragment('facts')}` : '';+ params.push(opts?.visibility ?? null);+ const visibility = `AND ($${params.length}::text[] IS NULL OR visibility = ANY($${params.length}::text[]))`;const r = await this.db.query(`SELECT DISTINCT ON (dimension) dimension, value, confidence,source_markdown_slug AS source, valid_from, valid_until AS valid_to,COALESCE(dim_status,'active') AS status, id AS fact_idFROM facts- WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL ${scope} ${privacy}+ WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL ${scope} ${privacy} ${visibility}AND COALESCE(valid_from,'-infinity'::timestamptz) <= COALESCE($2::timestamptz, now())AND COALESCE(valid_until,'infinity'::timestamptz) > COALESCE($2::timestamptz, now())AND confidence >= $3@@ -2365,7 +2375,7 @@ export class PGLiteEngine implements BrainEngine {});}- async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]> {+ async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts['visibility'] }): Promise<OntologyConflict[]> {const minConf = opts?.minConfidence ?? 0;const params: unknown[] = [minConf];let scope: string;@@ -2374,11 +2384,13 @@ export class PGLiteEngine implements BrainEngine {// Same provenance-page gate as getOntology, inside the CTE so a conflict// that only exists because of a hidden provenance is never reported.const privacy = opts?.excludePrivate ? `AND ${privateProvenanceFilterFragment('facts')}` : '';+ params.push(opts?.visibility ?? null);+ const visibility = `AND ($${params.length}::text[] IS NULL OR visibility = ANY($${params.length}::text[]))`;const r = await this.db.query(`WITH cur AS (SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_idFROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL- AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 ${scope} ${privacy}+ AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 ${scope} ${privacy} ${visibility})SELECT entity_slug, dimension,json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS valuesdiff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9ff9cb0ea5..5626f6b3d9 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -2037,13 +2037,21 @@ export class PostgresEngine implements BrainEngine {const current = cur[0];if (current && current.value_hash === vh && !isBackdatedObservation(validFrom, current.valid_from)) {- // Same value → corroboration (or exact dup → noop via the dedup unique).+ // Same value → corroboration, or noop when this provenance already+ // observed the value during the current stint.+ const seen = await sql`+ SELECT 1 FROM facts+ WHERE source_id = ${sourceId} AND entity_slug = ${obs.entitySlug} AND dimension = ${dimension}+ AND value_hash = ${vh} AND source_markdown_slug = ${obs.source}+ AND COALESCE(valid_from, '-infinity'::timestamptz) >= COALESCE(${current.valid_from}::timestamptz, '-infinity'::timestamptz)+ LIMIT 1`;+ if (seen.length) return { action: 'noop', factId: null, supersededId: null };const ins = await sql<{ id: number }[]>`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, dimension, value, value_hash, dim_status,confidence, source, source_markdown_slug, valid_from, valid_until, expired_at, consolidated_into)VALUES (${sourceId}, ${obs.entitySlug}, ${factText}, 'fact', ${visibility}, ${dimension}, ${obs.value}, ${vh}, ${status},${conf}, ${obs.source}, ${obs.source}, COALESCE(${validFrom}::timestamptz, now()), ${validUntil}, now(), ${current.id})- ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug) WHERE dimension IS NOT NULL+ ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE dimension IS NOT NULLDO NOTHINGRETURNING id`;return ins.length@@ -2056,7 +2064,7 @@ export class PostgresEngine implements BrainEngine {confidence, source, source_markdown_slug, valid_from, valid_until)VALUES (${sourceId}, ${obs.entitySlug}, ${factText}, 'fact', ${visibility}, ${dimension}, ${obs.value}, ${vh}, ${status},${conf}, ${obs.source}, ${obs.source}, COALESCE(${validFrom}::timestamptz, now()), ${validUntil})- ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug) WHERE dimension IS NOT NULL+ ON CONFLICT (source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from) WHERE dimension IS NOT NULLDO NOTHINGRETURNING id`;if (!ins.length) return { action: 'noop', factId: null, supersededId: null };@@ -2087,6 +2095,7 @@ export class PostgresEngine implements BrainEngine {// Page-visibility gate on the provenance page, applied BEFORE DISTINCT ON// so the untrusted caller resolves the newest value they may see.const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privateProvenanceFilterFragment('facts')}`) : sql``;+ const visibility = opts?.visibility ? sql`AND visibility = ANY(${opts.visibility})` : sql``;const rows = await sql<OntologyValue[]>`SELECT DISTINCT ON (dimension)dimension, value, confidence,@@ -2094,7 +2103,7 @@ export class PostgresEngine implements BrainEngine {COALESCE(dim_status, 'active') AS status, id AS fact_idFROM factsWHERE entity_slug = ${entitySlug} AND dimension IS NOT NULL AND expired_at IS NULL- ${scope} ${privacy}+ ${scope} ${privacy} ${visibility}AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE(${asof}::timestamptz, now())AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE(${asof}::timestamptz, now())AND confidence >= ${minConf}@@ -2116,7 +2125,7 @@ export class PostgresEngine implements BrainEngine {return rows.map((r) => ({ dimension: r.dimension, entities: Number(r.entities), observations: Number(r.observations) }));}- async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]> {+ async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts['visibility'] }): Promise<OntologyConflict[]> {const sql = this.sql;const minConf = opts?.minConfidence ?? 0;const scope = opts?.sourceIds && opts.sourceIds.length@@ -2125,13 +2134,14 @@ export class PostgresEngine implements BrainEngine {// Same provenance-page gate as getOntology, inside the CTE so a conflict// that only exists because of a hidden provenance is never reported.const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privateProvenanceFilterFragment('facts')}`) : sql``;+ const visibility = opts?.visibility ? sql`AND visibility = ANY(${opts.visibility})` : sql``;const rows = await sql<{ entity_slug: string; dimension: string; values: OntologyConflict['values'] }[]>`WITH cur AS (SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_idFROM factsWHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULLAND (dim_status IS NULL OR dim_status = 'active')- AND confidence >= ${minConf} ${scope} ${privacy}+ AND confidence >= ${minConf} ${scope} ${privacy} ${visibility})SELECT entity_slug, dimension,json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS valuesdiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 20a45b7625..665c8615f7 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -187,6 +187,7 @@ import { v183 } from './v183-persistence-mode-epoch.ts';import { v184 } from './v184-decision-receipts.ts';import { v185 } from './v185-decide-calibrations.ts';import { v186 } from './v186-decide-proposals.ts';+import { v189 } from './v189-facts-ontology-stint-dedup.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -372,4 +373,5 @@ export const MIGRATIONS: Migration[] = [v184,v185,v186,+ v189,];diff --git a/src/core/schema-migrations/v189-facts-ontology-stint-dedup.ts b/src/core/schema-migrations/v189-facts-ontology-stint-dedup.tsnew file mode 100644index 0000000000..045a098f5e--- /dev/null+++ b/src/core/schema-migrations/v189-facts-ontology-stint-dedup.ts@@ -0,0 +1,20 @@+import type { Migration } from './types.ts';++// Life Chronicle ontology dedup keyed per stint: the observation's valid_from+// joins (source, entity, dimension, value, provenance), so returning to an+// earlier value with the same provenance (A → B → A) records a new interval+// instead of colliding with the first stint. A crash-retry of the same+// observation still conflicts; a same-stint repeat is a noop in+// mergeOntologyFact. The new key is strictly finer than the old one, so+// existing rows always satisfy it.+export const v189: Migration = {+ version: 189,+ name: 'facts_ontology_stint_dedup',+ idempotent: true,+ sql: `+ CREATE UNIQUE INDEX IF NOT EXISTS idx_facts_ontology_stint_dedup+ ON facts(source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from)+ WHERE dimension IS NOT NULL;+ DROP INDEX IF EXISTS idx_facts_ontology_dedup;+ `,+};diff --git a/src/core/types.ts b/src/core/types.tsindex e0470d5050..574d5e170b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1648,6 +1648,8 @@ export interface OntologyReadOpts extends PageReadScope {includeQuarantined?: boolean;sourceId?: string;sourceIds?: string[];+ /** Fact visibility tiers the caller may read; undefined reads every tier. */+ visibility?: Array<'private' | 'world'>;}// Raw datadiff --git a/test/chronicle-context.test.ts b/test/chronicle-context.test.tsindex 5ec691a3be..b1936508a8 100644--- a/test/chronicle-context.test.ts+++ b/test/chronicle-context.test.ts@@ -13,8 +13,8 @@ beforeAll(async () => {await engine.connect({ database_url: '' });await engine.initSchema();// An entity with a public role + a diary-sourced affect.- await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'advisor', source: 'meetings/a' });- await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'affect', value: 'anxious', source: 'life/diary/2026-06-18', status: 'active' });+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'advisor', source: 'meetings/a', visibility: 'world' });+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'affect', value: 'anxious', source: 'life/diary/2026-06-18', status: 'active', visibility: 'world' });});afterAll(async () => { await engine.disconnect(); });diff --git a/test/chronicle-ontology-private-visibility.test.ts b/test/chronicle-ontology-private-visibility.test.tsindex 6c54c4b6de..0760d9aefb 100644--- a/test/chronicle-ontology-private-visibility.test.ts+++ b/test/chronicle-ontology-private-visibility.test.ts@@ -81,21 +81,22 @@ beforeEach(async () => {// newer valid_from, so local resolves the private value; an untrusted caller// must resolve the older world value, not a hole. The same pair is a// two-provenance conflict that only exists with the private side present.+ // Every row is world-visible so only the provenance-page gate can redact.await engine.mergeOntologyFact({entitySlug: 'people/open-person', dimension: 'role', value: 'secretvalue',- source: 'meetings/secret-sync', validFrom: '2026-05-01',+ source: 'meetings/secret-sync', visibility: 'world', validFrom: '2026-05-01',});await engine.mergeOntologyFact({entitySlug: 'people/open-person', dimension: 'role', value: 'openvalue',- source: 'meetings/open-sync', validFrom: '2026-01-01',+ source: 'meetings/open-sync', visibility: 'world', validFrom: '2026-01-01',});await engine.mergeOntologyFact({entitySlug: 'people/conf-person', dimension: 'role', value: 'secretvalue',- source: 'meetings/secret-sync', validFrom: '2026-05-01',+ source: 'meetings/secret-sync', visibility: 'world', validFrom: '2026-05-01',});await engine.mergeOntologyFact({entitySlug: 'people/conf-person', dimension: 'role', value: 'yes',- source: 'meetings/open-sync', validFrom: '2026-01-01',+ source: 'meetings/open-sync', visibility: 'world', validFrom: '2026-01-01',});}, 60_000);diff --git a/test/chronicle-ops-scope.test.ts b/test/chronicle-ops-scope.test.tsindex 6037e2ba58..339c84f99c 100644--- a/test/chronicle-ops-scope.test.ts+++ b/test/chronicle-ops-scope.test.ts@@ -195,14 +195,15 @@ beforeEach(async () => {);if (updated.length !== 1) throw new Error(`CROSS fixture: expected 1 repointed row, got ${updated.length}`);- // ── ontology (volunteer_chronicle arm): one diary-sourced, one public. ──+ // ── ontology (volunteer_chronicle arm): one diary-sourced, one public, both+ // world-visible so only the diary rule can redact. ──await engine.mergeOntologyFact({entitySlug: 'people/alpha-person', dimension: 'affect', value: 'DIARYONLYVALUE',- source: 'life/diary/2026-06-18', sourceId: 'srcalpha',+ source: 'life/diary/2026-06-18', sourceId: 'srcalpha', visibility: 'world',});await engine.mergeOntologyFact({entitySlug: 'people/alpha-person', dimension: 'role', value: 'publicrole',- source: 'meetings/alpha-sync', sourceId: 'srcalpha',+ source: 'meetings/alpha-sync', sourceId: 'srcalpha', visibility: 'world',});}, 60_000);diff --git a/test/e2e/managed-ontology-propose-postgres.test.ts b/test/e2e/managed-ontology-propose-postgres.test.tsnew file mode 100644index 0000000000..3206fc8d9f--- /dev/null+++ b/test/e2e/managed-ontology-propose-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-ontology-propose.test.ts'));diff --git a/test/e2e/ontology-merge-parity.test.ts b/test/e2e/ontology-merge-parity.test.tsindex e69697bd55..79fec112aa 100644--- a/test/e2e/ontology-merge-parity.test.ts+++ b/test/e2e/ontology-merge-parity.test.ts@@ -2,8 +2,8 @@* D7 — mergeOntologyFact matrix parity (Life Chronicle ontology, #2390).** The merge rides the `facts` table with a partial dedup unique index- * ((source_id, entity_slug, dimension, value_hash, source_markdown_slug)- * WHERE dimension IS NOT NULL) and a current-open supersession UPDATE.+ * ((source_id, entity_slug, dimension, value_hash, source_markdown_slug,+ * valid_from) WHERE dimension IS NOT NULL) and a current-open supersession UPDATE.* Postgres binds through postgres.js sql`` (BIGSERIAL ids arrive as strings,* Number()-normalized in the engine); PGLite through positional $N params.* A drift means `gbrain migrate --to supabase` silently changes how an@@ -291,4 +291,33 @@ describeBoth('Engine parity — mergeOntologyFact matrix (D7)', () => {}expect(await dumpFacts(pgEngine, STINT)).toEqual(await dumpFacts(pgliteEngine, STINT));});++ test('same-provenance revert (A → B → A) records a new interval identically', async () => {+ const REVERT = 'people/onto-revert';+ const at = async (eng: BrainEngine, asof?: string) =>+ (await eng.getOntology(REVERT, { sourceId: 'default', asof })).find(r => r.dimension === 'location')?.value ?? null;+ for (const eng of [pgEngine, pgliteEngine]) {+ const actions: string[] = [];+ for (const [value, from] of [['Lisbon', '2020-01-01'], ['Porto', '2022-01-01'], ['Lisbon', '2024-01-01'], ['Lisbon', '2024-01-01']]) {+ actions.push((await eng.mergeOntologyFact({ entitySlug: REVERT, dimension: 'location', value, source: 'manual', validFrom: `${from}T00:00:00.000Z` })).action);+ }+ expect(actions).toEqual(['inserted', 'superseded_prior', 'superseded_prior', 'noop']);+ expect(await at(eng)).toBe('Lisbon');+ expect(await at(eng, '2023-06-01T00:00:00Z')).toBe('Porto');+ }+ expect(await dumpFacts(pgEngine, REVERT)).toEqual(await dumpFacts(pgliteEngine, REVERT));+ });++ test('visibility filter resolves the newest permitted row identically', async () => {+ const VIS = 'people/onto-visibility';+ for (const eng of [pgEngine, pgliteEngine]) {+ await eng.mergeOntologyFact({ entitySlug: VIS, dimension: 'role', value: 'private-founder', source: 'notes/p', validFrom: '2026-01-01T00:00:00.000Z', visibility: 'private' });+ await eng.mergeOntologyFact({ entitySlug: VIS, dimension: 'role', value: 'world-advisor', source: 'notes/w', validFrom: '2025-01-01T00:00:00.000Z', visibility: 'world' });+ expect((await eng.getOntology(VIS, { sourceId: 'default', visibility: ['world'] })).map(r => r.value)).toEqual(['world-advisor']);+ expect((await eng.getOntology(VIS, { sourceId: 'default' })).map(r => r.value)).toEqual(['private-founder']);+ const conflicts = (all: Awaited<ReturnType<BrainEngine['findOntologyConflicts']>>) => all.filter(c => c.entity_slug === VIS);+ expect(conflicts(await eng.findOntologyConflicts({ sourceId: 'default', visibility: ['world'] }))).toEqual([]);+ expect(conflicts(await eng.findOntologyConflicts({ sourceId: 'default' }))).toHaveLength(1);+ }+ });});diff --git a/test/e2e/schema-drift.test.ts b/test/e2e/schema-drift.test.tsindex 8adf92cb46..2b67c7c0d2 100644--- a/test/e2e/schema-drift.test.ts+++ b/test/e2e/schema-drift.test.ts@@ -269,13 +269,14 @@ describe.skipIf(skip)('schema drift: PGLite ↔ Postgres post-initSchema parity],},{- // Facts ontology dedup (migration 122): partial unique keyed on the- // deterministic value_hash, scoped WHERE dimension IS NOT NULL.- name: 'idx_facts_ontology_dedup',+ // Facts ontology dedup (migration 189): partial unique keyed on the+ // deterministic value_hash plus the stint's valid_from, scoped+ // WHERE dimension IS NOT NULL.+ name: 'idx_facts_ontology_stint_dedup',table: 'facts',defMust: ['create unique index',- '(source_id, entity_slug, dimension, value_hash, source_markdown_slug)',+ '(source_id, entity_slug, dimension, value_hash, source_markdown_slug, valid_from)','where (dimension is not null)',],},diff --git a/test/managed-ontology-propose.test.ts b/test/managed-ontology-propose.test.tsnew file mode 100644index 0000000000..56fcab7f1c--- /dev/null+++ b/test/managed-ontology-propose.test.ts@@ -0,0 +1,96 @@+/**+ * ontology_propose on a managed brain (eval wave N1-1).+ *+ * `gbrain init` turns managed persistence on, and the managed writer guard+ * refuses direct `facts` writes. An ontology observation is a database-only+ * fact row, so ontology_propose commits it as a coordinated write holding the+ * source capability and the entity's page key, like manual links. A direct+ * engine write stays refused, and the current-value read and revert chain+ * work through the coordinator.+ *+ * Synthetic data only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-managed-ontology-db-'));+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });+});++const logger = { info() {}, warn() {}, error() {} };+const ctxFor = (engine: BrainEngine, sourceId: string): OperationContext =>+ ({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger });++async function managed(run: (engine: BrainEngine, sourceId: string) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-ontology-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `onto-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run(engine, sourceId);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}++const E = 'people/alice-example';+const propose = (engine: BrainEngine, sourceId: string, p: Record<string, unknown>) =>+ operationsByName.ontology_propose.handler(ctxFor(engine, sourceId), { entity: E, dimension: 'location', visibility: 'world', ...p }) as Promise<{ action: string }>;+const location = async (engine: BrainEngine, sourceId: string, asof?: string) =>+ ((await operationsByName.ontology_get.handler(ctxFor(engine, sourceId), { entity: E, ...(asof ? { asof } : {}) })) as Array<{ dimension: string; value: string }>)+ .find(r => r.dimension === 'location')?.value ?? null;++test('ontology_propose commits through the coordinator on a managed brain; a direct write stays refused', async () => {+ await managed(async (engine, sourceId) => {+ await expect(engine.mergeOntologyFact({ entitySlug: E, dimension: 'location', value: 'Direct', source: 'manual', sourceId }))+ .rejects.toThrow(/writer_coordinator_required/);+ expect((await propose(engine, sourceId, { value: 'Lisbon' })).action).toBe('inserted');+ expect(await location(engine, sourceId)).toBe('Lisbon');+ expect((await propose(engine, sourceId, { value: 'Lisbon' })).action).toBe('noop');+ });+});++test('a same-provenance revert chain resolves through the coordinator', async () => {+ await managed(async (engine, sourceId) => {+ for (const [value, valid_from] of [['Lisbon', '2020-01-01'], ['Porto', '2022-01-01'], ['Lisbon', '2024-01-01']]) {+ await propose(engine, sourceId, { value, valid_from });+ }+ expect(await location(engine, sourceId)).toBe('Lisbon');+ expect(await location(engine, sourceId, '2023-06-01')).toBe('Porto');+ });+});diff --git a/test/ontology-fact-visibility.test.ts b/test/ontology-fact-visibility.test.tsnew file mode 100644index 0000000000..79fb473e2e--- /dev/null+++ b/test/ontology-fact-visibility.test.ts@@ -0,0 +1,77 @@+/**+ * Ontology reads follow fact visibility (eval wave N1-3).+ *+ * An ontology observation is a `facts` row, so an untrusted caller sees only+ * `visibility = 'world'` rows, exactly like recall and the hot-memory block.+ * The filter applies before per-dimension resolution, so a remote caller+ * resolves the newest world value instead of a private one or a hole. Trusted+ * local callers keep every tier.+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+const ALICE = 'people/alice-example';+const BOB = 'people/bob-example';++function ctxOf(remote: boolean | undefined): OperationContext {+ return {+ engine, config: {} as never, dryRun: false, remote: remote as boolean, transport: 'stdio', sourceId: 'default',+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ } as OperationContext;+}+const run = (name: string, remote: boolean | undefined, p: Record<string, unknown>) =>+ operationsByName[name].handler(ctxOf(remote), p) as Promise<unknown>;+const values = (rows: unknown) => (rows as Array<{ dimension: string; value: string }>).map(r => `${r.dimension}=${r.value}`).sort();++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); }, 60_000);++beforeEach(async () => {+ await resetPgliteState(engine);+ await run('ontology_propose', false, { entity: ALICE, dimension: 'risk_tolerance', value: 'high privmarker', visibility: 'private' });+ await run('ontology_propose', false, { entity: ALICE, dimension: 'decision_style', value: 'deliberate', visibility: 'world' });+ // Backdated second write: both rows stay open, the private one is newer.+ await run('ontology_propose', false, { entity: BOB, dimension: 'role', value: 'founder privmarker', source: 'notes/b', valid_from: '2026-01-01', visibility: 'private' });+ await run('ontology_propose', false, { entity: BOB, dimension: 'role', value: 'advisor', source: 'notes/a', valid_from: '2025-01-01', visibility: 'world' });+}, 60_000);++describe('ontology reads hide private observations from untrusted callers', () => {+ test('ontology_get: remote gets world rows only; local keeps every tier', async () => {+ for (const remote of [true, undefined]) {+ expect(values(await run('ontology_get', remote, { entity: ALICE }))).toEqual(['decision_style=deliberate']);+ }+ expect(values(await run('ontology_get', false, { entity: ALICE }))).toEqual(['decision_style=deliberate', 'risk_tolerance=high privmarker']);+ });++ test('ontology_get: remote resolves the newest world value, not the newer private one', async () => {+ expect(values(await run('ontology_get', true, { entity: BOB }))).toEqual(['role=advisor']);+ expect(values(await run('ontology_get', false, { entity: BOB }))).toEqual(['role=founder privmarker']);+ });++ test('ontology_conflicts: a disagreement that needs a private row is not reported remotely', async () => {+ await run('ontology_propose', false, { entity: BOB, dimension: 'location', value: 'Lisbon', source: 'notes/c', valid_from: '2026-02-01', visibility: 'world' });+ await run('ontology_propose', false, { entity: BOB, dimension: 'location', value: 'Porto privmarker', source: 'notes/d', valid_from: '2025-02-01', visibility: 'private' });+ const remote = await run('ontology_conflicts', true, {});+ expect(JSON.stringify(remote)).not.toContain('privmarker');+ const local = await run('ontology_conflicts', false, {}) as Array<{ entity_slug: string; dimension: string }>;+ expect(local.map(c => `${c.entity_slug}:${c.dimension}`)).toContain(`${BOB}:location`);+ });++ test('volunteer_chronicle: remote ontologies carry no private observation', async () => {+ const remote = await run('volunteer_chronicle', true, { entities: `${ALICE},${BOB}` }) as { ontologies: Record<string, unknown> };+ expect(JSON.stringify(remote.ontologies)).not.toContain('privmarker');+ expect(values(remote.ontologies[ALICE])).toEqual(['decision_style=deliberate']);+ expect(values(remote.ontologies[BOB])).toEqual(['role=advisor']);+ const local = await run('volunteer_chronicle', false, { entities: ALICE }) as { ontologies: Record<string, unknown> };+ expect(JSON.stringify(local.ontologies)).toContain('privmarker');+ });+});diff --git a/test/ontology-revert.test.ts b/test/ontology-revert.test.tsnew file mode 100644index 0000000000..7ffb7c157f--- /dev/null+++ b/test/ontology-revert.test.ts@@ -0,0 +1,67 @@+/**+ * Ontology revert with the same provenance (eval wave N1-2).+ *+ * Lisbon (2020) → Porto (2022) → Lisbon (2024), all from one provenance, must+ * make Lisbon current again and keep Porto for its own window. The dedup key+ * carries the stint's valid_from, so the return is a new interval instead of+ * colliding with the first one, while retries stay idempotent.+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+const E = 'people/alice-example';++const ctx = () => ({+ engine, config: {} as never, dryRun: false, remote: false, sourceId: 'default',+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+}) as OperationContext;+const propose = (value: string, valid_from?: string) =>+ operationsByName.ontology_propose.handler(ctx(), { entity: E, dimension: 'location', value, visibility: 'world', ...(valid_from ? { valid_from } : {}) }) as Promise<{ action: string }>;+const locationAt = async (asof?: string) =>+ ((await operationsByName.ontology_get.handler(ctx(), { entity: E, ...(asof ? { asof } : {}) })) as Array<{ dimension: string; value: string }>)+ .find(r => r.dimension === 'location')?.value ?? null;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); }, 60_000);+beforeEach(async () => { await resetPgliteState(engine); });++describe('ontology revert to an earlier value with the same provenance', () => {+ test('A → B → A records a new interval and makes A current again', async () => {+ expect((await propose('Lisbon', '2020-01-01')).action).toBe('inserted');+ expect((await propose('Porto', '2022-01-01')).action).toBe('superseded_prior');+ expect((await propose('Lisbon', '2024-01-01')).action).toBe('superseded_prior');+ expect(await locationAt()).toBe('Lisbon');+ expect(await locationAt('2021-06-01')).toBe('Lisbon');+ expect(await locationAt('2023-06-01')).toBe('Porto');+ expect(await locationAt('2024-06-01')).toBe('Lisbon');+ });++ test('replaying any step of the chain is a noop', async () => {+ for (const [v, d] of [['Lisbon', '2020-01-01'], ['Porto', '2022-01-01'], ['Lisbon', '2024-01-01']]) await propose(v, d);+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts');+ for (const [v, d] of [['Lisbon', '2020-01-01'], ['Porto', '2022-01-01'], ['Lisbon', '2024-01-01'], ['Lisbon', '2024-03-01']]) {+ expect((await propose(v, d)).action).toBe('noop');+ }+ expect((await propose('Lisbon')).action).toBe('noop');+ const [{ n: after }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts');+ expect(after).toBe(n);+ expect(await locationAt()).toBe('Lisbon');+ });++ test('an undated return to an earlier value supersedes the current one', async () => {+ await propose('Lisbon', '2020-01-01');+ await propose('Porto', '2022-01-01');+ expect((await propose('Lisbon')).action).toBe('superseded_prior');+ expect(await locationAt()).toBe('Lisbon');+ expect(await locationAt('2023-06-01')).toBe('Porto');+ });+});