Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1 lane C: ledger graduation carry rows, deletion inventory rows, legacy copier names the ledger; probe 9
garrytan7630c3b83f2f
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex a8c44a963c..b288d43f6c 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -36,6 +36,10 @@ export interface InventoryEntry {type Row = [table: string, cls: InventoryClass, reason: string, columns: string, probe?: string];const ROWS: readonly Row[] = [['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust'],+ ['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields', 'value'],+ ['belief_page_lifetimes', 'out_of_scope', 'no_memory_text', 'source_id slug'],+ ['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],+ ['belief_retier_manifest', 'out_of_scope', 'text_free_ledger', 'source_id subject_kind subject_key from_tier to_tier'],['budget_ledger', 'out_of_scope', 'no_memory_text', 'scope resolver_id'],['budget_reservations', 'out_of_scope', 'no_memory_text', 'reservation_id scope resolver_id status'],['calibration_profiles', 'out_of_scope', 'probed_reported', 'source_id holder wave_version domain_scorecards pattern_statements active_bias_tags model_id', 'pattern_statements domain_scorecards'],diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex 39145907d2..c0798be5d0 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -30,6 +30,11 @@ export const GRADUATION_INVENTORY: Inventory = {version: 1,entries: [carry('access_tokens', 'security', 'Legacy bearer tokens and their unified grant columns; token hashes keep authorizing on the target.'),+ carry('belief_commit_marks', 'user_data', 'Belief ledger post-commit observations; without them carried events would read as unproven (W2 visibility).'),+ carry('belief_events', 'user_data', 'The belief ledger: recorded history Markdown cannot rebuild; event keys carry no ids, and the id order and sequence carry verbatim.'),+ carry('belief_page_lifetimes', 'user_data', 'Belief ledger page identities; event keys name these lifetimes.'),+ carry('belief_redactions', 'user_data', 'Belief ledger purge suppressions; dropping them would let a later append write purged text back.'),+ carry('belief_retier_manifest', 'user_data', 'Per-subject manifests behind bulk trust.retiered events.'),carry('budget_ledger', 'operational', 'Daily resolver spend totals; admission keeps counting today\'s spend.'),carry('calibration_profiles', 'user_data', 'Published calibration profiles per holder.'),carry('chat_usage_log', 'operational', 'Chat model usage and cost log.'),diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.tsindex 879bdbe606..e73a81733b 100644--- a/src/core/persistence/maintenance.ts+++ b/src/core/persistence/maintenance.ts@@ -69,24 +69,27 @@ export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operatiouser_message: `gbrain stopped ${operation} because your brain switched to managed writes while it ran. Nothing was written; running the same command again uses the managed path.` } });}-/** The legacy engine copier cannot transfer permanent IDs, withdrawals or ownership. */+/** The legacy engine copier cannot transfer permanent IDs, withdrawals, ownership or the belief ledger. */export async function assertLegacyEngineMigration(engine: SqlEngine, migration: EngineMigrationSide = { side: 'source', from: 'pglite', to: 'postgres' }): Promise<void> {- const tables = ['persistence_requests', 'fact_withdrawals', 'persistence_worktrees'] as const;+ const tables = ['belief_events', 'persistence_requests', 'fact_withdrawals', 'persistence_worktrees'] as const;// Older migration sources can predate these tables. Do not interpret any// other database failure as an empty history.const present = await engine.executeRaw<{ name: string }>('SELECT name FROM unnest($1::text[]) AS t(name) WHERE to_regclass(name) IS NOT NULL', [tables]);+ const held: string[] = [];for (const table of tables) {if (!present.some(row => row.name === table)) continue;const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS(SELECT 1 FROM ${table}) AS present`);- if (!row?.present) continue;- const why = `The ${migration.side === 'source' ? 'brain' : 'target datastore'} has rows in ${table}, and the engine copier cannot carry request IDs, withdrawals or canonical ownership.`;- throw opError('writer_coordinator_required',- 'Engine migration cannot discard durable write history, withdrawal protection, or canonical ownership.',- migration.side === 'target' ? 'Choose an empty target database; the source brain is unchanged.'- : 'Keep this datastore; nothing changed. Ask the user how to proceed.',- { why, reason: 'persistence_history', docs: ENGINE_MIGRATION_DOCS, fix: engineMigrationFix(migration, why) });+ if (row?.present) held.push(table);}+ if (!held.length) return;+ const ledger = held.includes('belief_events') ? ' The belief ledger (belief_events) is recorded history no Markdown rebuild can recover.' : '';+ const why = `The ${migration.side === 'source' ? 'brain' : 'target datastore'} has rows in ${held.join(', ')}, and the engine copier cannot carry request IDs, withdrawals, canonical ownership or the belief ledger.${ledger}`;+ throw opError('writer_coordinator_required',+ 'Engine migration cannot discard durable write history, withdrawal protection, canonical ownership, or the belief ledger.',+ migration.side === 'target' ? 'Choose an empty target database; the source brain is unchanged.'+ : 'Keep this datastore; nothing changed. Ask the user how to proceed.',+ { why, reason: 'persistence_history', docs: ENGINE_MIGRATION_DOCS, fix: engineMigrationFix(migration, why) });}/** Legacy reinit may rename only after acquiring the stable sibling kernel lock. */diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.tsindex 7a34cd950b..424343665e 100644--- a/test/belief-ledger-coverage.test.ts+++ b/test/belief-ledger-coverage.test.ts@@ -17,6 +17,15 @@ import { enableBeliefLedger, disableBeliefLedger } from '../src/core/belief/coveimport {beliefEventVisibility, coverageAt, coverageIntervals, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, scanBeliefDrift, unmarkedPublications,} from '../src/core/belief/coverage-report.ts';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationError } from '../src/core/ops/contract.ts';+import type { InventoryEntry } from '../src/core/persistence/engine-graduation.types.ts';+import { GRADUATION_INVENTORY } from '../src/core/persistence/graduation-inventory.ts';+import { copySequences } from '../src/core/persistence/graduation-copy.ts';+import { assertLegacyEngineMigration } from '../src/core/persistence/maintenance.ts';+import { copiedEntries, copyAll, digestMismatches } from './helpers/graduation-copy-harness.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { testBackends } from './helpers/test-backends.ts';import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';@@ -319,5 +328,57 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect((await coverageIntervals(b.engine, b.sourceId)).at(-1)!.stopped_at).not.toBeNull();}, { managed: false });}, 120_000);++ test('probe 9: graduation PGLite -> ' + engineCase.name + ' carries an identical ledger: equal event_key sets, digests and replay', async () => {+ await beliefBrain(async b => {+ await seeded(b);+ await b.put('companies/acme-example', page({ facts: ['Acme raised a seed round', { claim: 'Acme has ten staff', confidence: '0.5' }] }));+ await b.engine.executeRaw(`UPDATE takes SET resolved_at = now(), resolved_outcome = true WHERE claim = 'Acme will hire fast'`);+ await reconcileBeliefDrift(b.engine, b.sourceId);+ const ledger = GRADUATION_INVENTORY.entries.filter(e => e.relation.startsWith('belief_'));+ expect(ledger.map(e => [e.relation, e.class]).sort()).toEqual(['belief_commit_marks', 'belief_events', 'belief_page_lifetimes', 'belief_redactions',+ 'belief_retier_manifest'].map(r => [r, 'carry']));+ const keys = async (engine: BrainEngine) => (await engine.executeRaw<{ k: string }>(`SELECT encode(event_key, 'hex') AS k FROM belief_events ORDER BY id`)).map(r => r.k);+ const replay = async (engine: BrainEngine) => ({ intervals: await coverageIntervals(engine, b.sourceId), drift: (await scanBeliefDrift(engine, b.sourceId, { deep: true })).drifted,+ events: (await engine.executeRaw<Record<string, unknown>>(`SELECT id::int AS id, subject_key, event_type, value_hash, state_hash, recorded_at FROM belief_events ORDER BY id`))+ .map(r => ({ ...r, recorded_at: new Date(r.recorded_at as string).toISOString() })) });+ const graduate = async (mutate: (entries: readonly InventoryEntry[]) => readonly InventoryEntry[]) => {+ const t = await isolatedSharedSkillsEngine(engineCase.databaseUrl);+ const e = { source: b.engine, target: t.engine };+ await copyAll(e, mutate(await copiedEntries(e)), { bypass: 'session_replication_role', runId: randomUUID() });+ await copySequences(e);+ return t;+ };+ const target = await graduate(entries => entries);+ try {+ expect(await keys(target.engine)).toEqual(await keys(b.engine));+ expect(await digestMismatches({ source: b.engine, target: target.engine }, ledger)).toEqual([]);+ expect(await replay(target.engine)).toEqual(await replay(b.engine));+ const [{ next }] = await target.engine.executeRaw<{ next: number }>(`SELECT nextval('belief_events_id_seq')::int AS next`);+ expect(next).toBe(await b.lastId() + 1);+ } finally { await target.close(); }+ // Forced probe: a copier that drops one ledger row is caught by the key-set comparison.+ const broken = await graduate(entries => entries.map(entry => entry.relation === 'belief_events' ? { ...entry, rowFilter: 'id <> 1' } : entry));+ try { expect(await keys(broken.engine)).not.toEqual(await keys(b.engine)); } finally { await broken.close(); }+ }, { managed: false });+ }, 300_000);++ test('probe 9: the legacy engine copier refuses a brain with a ledger, naming it', async () => {+ const t = await isolatedSharedSkillsEngine(engineCase.databaseUrl);+ try {+ const [{ incarnation }] = await t.engine.executeRaw<{ incarnation: string }>(`SELECT incarnation::text AS incarnation FROM sources WHERE id = 'default'`);+ await t.engine.executeRaw(`INSERT INTO belief_events (event_key, source_id, source_incarnation, slug, subject_kind, subject_key, event_type, trust_tier, visibility,+ publication_id, ord, state_hash, cause) VALUES (decode(md5('k'), 'hex'), 'default', $1::uuid, '', 'coverage', '["coverage"]', 'coverage.started', 'unknown', 'world',+ gen_random_uuid(), 0, '', '{}'::jsonb)`, [incarnation]);+ expect(await t.engine.executeRaw('SELECT 1 FROM persistence_requests UNION ALL SELECT 1 FROM fact_withdrawals UNION ALL SELECT 1 FROM persistence_worktrees')).toEqual([]);+ const refusal = await assertLegacyEngineMigration(t.engine).then(() => null, (error: OperationError) => error);+ expect(refusal?.code).toBe('writer_coordinator_required');+ expect(refusal?.message).toContain('belief ledger');+ expect(String((refusal?.toJSON() as { why?: string }).why)).toContain('rows in belief_events');+ // Forced probe: the same brain without its ledger row is not refused, so the refusal is the ledger's.+ await t.engine.executeRaw('DELETE FROM belief_events');+ await expect(assertLegacyEngineMigration(t.engine)).resolves.toBeUndefined();+ } finally { await t.close(); }+ }, 120_000);});}diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 9c65c39233..0977c6000d 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 128, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });+ expect(counts).toEqual({ carry: 133, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });