Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(GBRA-47 D9): behavioral withdrawal-race owners replace the blind prepare-wiring pin
garrytan027a8a2b1430
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 91af9af8a5..6670d08285 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -156,7 +156,6 @@ test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on ptest/extract-atoms-drain.test.ts protected-names register comment names the real trust mechanism 1 readFileSynctest/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSynctest/extract-include-frontmatter-config.serial.test.ts no extraction path hardcodes includeFrontmatter 1 readFileSync-test/fact-withdrawal-prepare-wiring.test.ts (file-level) 2 readFileSynctest/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSynctest/facts-relink.test.ts relink reasons 1 readFileSynctest/features.test.ts CLI routing 2 source-surface-helperdiff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex c372d0758f..fc64475a7a 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -797,7 +797,6 @@"test/extraction-review.test.ts": 5143,"test/fact-backfill-resident.test.ts": 3635,"test/fact-withdrawal-normalized.test.ts": 299,- "test/fact-withdrawal-prepare-wiring.test.ts": 14,"test/facts-absorb-log.test.ts": 212,"test/facts-anti-loop.test.ts": 380,"test/facts-backstop-gating.test.ts": 839,diff --git a/test/fact-withdrawal-prepare-wiring.test.ts b/test/fact-withdrawal-prepare-wiring.test.tsdeleted file mode 100644index ab8586c2ad..0000000000--- a/test/fact-withdrawal-prepare-wiring.test.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * Ported from garrytan/gbrain#5469 by @tarush1989.- * Structural pin: every coordinated prepare path that applies a prepared content- * import must also run that import's pre-publication `validate` (the fact-withdrawal- * race check), and the coordinator must run `validate` before any file publication.- * The managed-import and put_page paths are proven behaviorally in- * persistence-file-import.test.ts and withdrawal-publication-file.test.ts; sync,- * connector and reconcile fixtures are heavy, so their wiring is pinned here.- */-import { expect, test } from 'bun:test';-import { readFileSync } from 'fs';-import { join } from 'path';--// test-reads-source-ok[structural]: pin on coordinated prepare wiring; sync, connector and reconcile fixtures are too heavy to drive each path behaviorally.-const source = (path: string) => readFileSync(join(import.meta.dir, '../src/core/persistence', path), 'utf8').replace(/\s+/g, ' ');-const count = (text: string, needle: string) => text.split(needle).length - 1;--test.each([- ['import-prepare.ts', 1],- ['connector-sync.ts', 1],- ['sync-prepare.ts', 2],- ['reconcile-prepare.ts', 1],- ['page-prepare.ts', 1],-] as const)('%s validates every prepared content import it applies', (file, applied) => {- const text = source(file);- expect(count(text, 'await ready.apply(tx)') + count(text, 'await applied.apply(tx)')).toBe(applied);- expect(count(text, 'await ready.validate(tx)') + count(text, 'validate: ready.validate')).toBe(applied);-});--test('a managed rename validates the import it re-prepares at the new slug before applying it', () => {- const text = source('sync-prepare.ts');- const validated = text.indexOf('await movedImport.validate(tx); applied = movedImport;');- expect(validated).toBeGreaterThan(0);- expect(validated).toBeLessThan(text.indexOf('await applied.apply(tx)'));-});--test('the coordinator validates prepared mutations before publication boundaries and file writes', () => {- const text = source('coordinator.ts');- const validate = text.indexOf('await prepared.validate?.(tx)');- expect(validate).toBeGreaterThan(0);- expect(validate).toBeLessThan(text.indexOf("hooks.boundary?.('before_publication', row)"));- expect(validate).toBeLessThan(text.indexOf("hooks.fileBoundary?.('before_file', row, index)"));-});diff --git a/test/persistence-connectors.test.ts b/test/persistence-connectors.test.tsindex 75823ef562..57180caed8 100644--- a/test/persistence-connectors.test.ts+++ b/test/persistence-connectors.test.ts@@ -15,6 +15,14 @@ import { importFromContent } from '../src/core/import-file.ts';import { parseMarkdown } from '../src/core/markdown.ts';import { withEnv } from './helpers/with-env.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { prepareConnectorMutation } from '../src/core/persistence/connector-sync.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { claimNextWrite } from '../src/core/persistence/journal.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint, connectorPendingSet } from './helpers/connector-fixture.ts';const { home, engines, env, source, boundSource, setup, teardown } = createConnectorFixture();@@ -498,3 +506,37 @@ test('aged live connector cursors survive actual checkpoint purge and normal inc: new URL(url).pathname.endsWith('/issues') && new URL(url).searchParams.has('since'))).toBe(true);}}), 120_000);++test('a fact withdrawn between bound connector preparation and publication leaves the canonical file and page unchanged', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, githubConfig);+ const claim = 'withdrawn between connector preparation and publication';+ let body = 'Original bound body';+ const fetcher = async (url: string) => new URL(url).pathname.endsWith('/issues/1') ? json({ ...issueFixture, body }) : githubFetch()(url);+ const run = () => runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), { ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, fetcher);+ await run();+ await disposePersistenceConsumer(engine);+ const slug = 'gh/acme-example/app/1', path = join(f.dir, `${slug}.md`);+ const original = readFileSync(path, 'utf8'), before = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ body = `Facts: ${renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: 'test evidence' }])}`;+ expect(await run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ expect(claimed.intent?.kind).toBe('connector_v2_import');+ const prepared = await prepareConnectorMutation(engine, claimed);+ expect(prepared.file?.content).toContain(claim);+ const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>+ tx.insertFact({ fact: claim, source: 'remember', visibility: 'world' }, { source_id: f.id }), TEST_WRITE_ATTRIBUTION));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id, true), TEST_WRITE_ATTRIBUTION));+ const boundaries: string[] = [];+ const outcome = await publishMutation(engine, claimed, prepared, localHostId(), {+ boundary: async name => { boundaries.push(name); }, fileBoundary: name => { boundaries.push(name); } });+ expect(outcome).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });+ expect(boundaries).not.toContain('before_publication');+ expect(boundaries).not.toContain('before_file');+ expect(readFileSync(path, 'utf8')).toBe(original);+ expect((await engine.readPageSnapshot(slug, { sourceId: f.id }))?.revision).toBe(before.revision);+ }+}), 120_000);diff --git a/test/persistence-file-import.test.ts b/test/persistence-file-import.test.tsindex 5a76fb6bc5..bf2f8b0fea 100644--- a/test/persistence-file-import.test.ts+++ b/test/persistence-file-import.test.ts@@ -20,6 +20,8 @@ import { sha256 } from '../src/core/persistence/digest.ts';import { runImport } from '../src/commands/import.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-file-import-'));const engines: BrainEngine[] = [];@@ -210,3 +212,38 @@ test('publication refuses admitted input-byte, canonical-target and page-identitawait expect(prepareManagedImportMutation(engine, { ...row, authority: { ...row.authority, remote: true } }, { engine: engine.kind })).rejects.toThrow('trusted local CLI');}}), 120_000);++test('publication refuses a fact withdrawn between managed-import preparation and publication', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ const f = await fixture(engine), file = join(f.input, 'withdrawn.md');+ const claim = 'withdrawn between managed import preparation and publication';+ const fence = renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world',+ notability: 'medium', active: true, context: 'test evidence' }]);+ const bytes = Buffer.from(`---\ntitle: Withdrawn import\ntype: note\n---\nFacts: ${fence}\n`); writeFileSync(file, bytes);+ const binding = (await getWorktreeBinding(engine, f.sourceId))!;+ const { slug, content } = managedImportContent('withdrawn.md', bytes);+ const ctx = { engine, remote: false, sourceId: f.sourceId } as OperationContext;+ const authority = await submissionAuthority(ctx, 'put_page', f.sourceId, binding.source_incarnation, slug);+ const intent: ManagedImportIntent = { kind: 'managed_file_import', slug, content, sourcePath: 'withdrawn.md', inputPath: file,+ inputHash: sha256(bytes), targetHash: null, ownerEpoch: String(binding.owner_epoch), noEmbed: true };+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId: f.sourceId, sourceIncarnation: binding.source_incarnation,+ slug, pageId: null, requestId: randomUUID(), callerIntent: intent, intent, authority, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const row = (await claimNextWrite(engine, localHostId()))!;+ const prepared = await prepareManagedImportMutation(engine, row, { engine: engine.kind });+ expect(prepared.file?.content).toContain(claim);++ const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () =>+ tx.insertFact({ fact: claim, source: 'remember', visibility: 'world' }, { source_id: f.sourceId }), TEST_WRITE_ATTRIBUTION));+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => recordFactWithdrawal(tx, fact.id, f.sourceId, true), TEST_WRITE_ATTRIBUTION));++ const boundaries: string[] = [];+ const outcome = await publishMutation(engine, row, prepared, localHostId(), {+ boundary: async name => { boundaries.push(name); }, fileBoundary: name => { boundaries.push(name); } });+ expect(outcome).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });+ expect(boundaries).not.toContain('before_publication');+ expect(boundaries).not.toContain('before_file');+ expect(await engine.getPage(slug, { sourceId: f.sourceId })).toBeNull();+ expect(existsSync(join(f.root, 'withdrawn.md'))).toBe(false);+ }+}), 120_000);diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex ffa7221167..25f5392fac 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -25,6 +25,8 @@ import { withEnv } from './helpers/with-env.ts';import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { loadSyncFailures, syncFailuresPath } from '../src/core/sync-failure-ledger.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-sync-'));const engines: BrainEngine[] = [];@@ -730,3 +732,35 @@ test('the waiver lookup for unfinished page requests is served by the request inexpect(text).not.toContain('Seq Scan');}}, 60_000);++test('a fact withdrawn between sync preparation and canonical file writeback conflicts without publishing', async () => withEnv({GBRAIN_HOME:home},async()=>{+ for(const engine of engines){+ const f=await fixture(engine,{'a.md':'An original observation before the withdrawal race.\n'});+ await performManagedSync(engine,{sourceId:f.id,noPull:true,noEmbed:true,noExtract:true});+ await disposePersistenceConsumer(engine);+ await engine.transaction(tx=>withCoordinatedWrite(tx,[f.id],()=>tx.addTag('a','database-only-tag',{sourceId:f.id}),TEST_WRITE_ATTRIBUTION));+ const base=(await engine.readPageSnapshot('a',{sourceId:f.id}))!;+ const claim='withdrawn between managed sync preparation and publication';+ const content=`Facts: ${renderFactsTable([{rowNum:1,claim,kind:'fact',confidence:1,visibility:'world',notability:'medium',active:true,context:'test evidence'}])}\n`;+ writeFileSync(join(f.root,'a.md'),content); const target=commit(f.root);+ const binding=(await getWorktreeBinding(engine,f.id))!;+ const authority=await managedSyncAuthority(engine,f.id,binding.source_incarnation,f.root);+ const intent:SyncIntent={kind:'managed_sync_import',processingOptions:{noEmbed:true,noExtract:true,noSchemaPack:false},expected_revision:base.revision,sourcePath:'a.md',path:'a.md',rawHash:sha256(content),content,+ ownerEpoch:String(binding.owner_epoch),syncAuthority:authority,cursorKey:'test-cursor',runId:randomUUID(),index:0,total:1,from:f.head,target,slugMode:'git-root'};+ await admitWrite(engine,{requestId:randomUUID(),operation:'submit_job',sourceId:f.id,sourceIncarnation:binding.source_incarnation,slug:'a',pageId:base.page.id,+ worktreeId:binding.worktree_id,topologyGeneration:binding.topology_generation,principal:authority.writer.principal,authority:authority.writer,callerIntent:intent,intent});+ const claimed=(await claimNextWrite(engine,localHostId()))!;+ const prepared=await prepareManagedSyncMutation(engine,claimed,{engine:engine.kind});+ expect(prepared.file?.content).toContain(claim);+ const fact=await engine.transaction(tx=>withCoordinatedWrite(tx,[f.id],()=>+ tx.insertFact({fact:claim,source:'remember',visibility:'world'},{source_id:f.id}),TEST_WRITE_ATTRIBUTION));+ await engine.transaction(tx=>withCoordinatedWrite(tx,[f.id],()=>recordFactWithdrawal(tx,fact.id,f.id,true),TEST_WRITE_ATTRIBUTION));+ const boundaries:string[]=[];+ const outcome=await publishMutation(engine,claimed,prepared,localHostId(),{boundary:async name=>{boundaries.push(name);},fileBoundary:name=>{boundaries.push(name);}});+ expect(outcome).toMatchObject({state:'conflict',error_code:'revision_conflict'});+ expect(boundaries).not.toContain('before_publication');+ expect(boundaries).not.toContain('before_file');+ expect(readFileSync(join(f.root,'a.md'),'utf8')).toBe(content);+ expect((await engine.readPageSnapshot('a',{sourceId:f.id}))?.revision).toBe(base.revision);+ }+}),120_000);diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.tsindex d063a80482..7340643617 100644--- a/test/persistence-reconcile.test.ts+++ b/test/persistence-reconcile.test.ts@@ -22,7 +22,7 @@ import { retainReconcileBackup } from '../src/core/persistence/reconcile-backup.import { prepareReconcileMutation } from '../src/core/persistence/reconcile-prepare.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';import { localHostId } from '../src/core/persistence/identity.ts';-import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';+import { parseFactsFence, renderFactsTable, upsertFactRow } from '../src/core/facts-fence.ts';import { sha256 } from '../src/core/persistence/digest.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { operationsByName } from '../src/core/operations.ts';@@ -671,3 +671,26 @@ test.each(['notes/example.md', 'notes/example.md.md'])('reconciliation preservesexpect(await engine.getPage('notes/other', { sourceId: f.id })).toBeNull();});}), 120_000);++test('a fact withdrawn between reconciliation preparation and publication leaves the canonical file and page unchanged', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const claim = 'withdrawn between reconciliation preparation and publication';+ const fence = renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: 'test evidence' }]);+ const f = await fixture(engine, enabled, `Facts: ${fence}`), originalBytes = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const repair = await preparedRepair(engine, f);+ expect(String(repair.prepared.file?.content)).toContain(claim);+ // The withdrawal row alone: a full forget would also rewrite this page and trip the revision check first.+ // Either the preview's withdrawals pin or the prepared import's validation must refuse it.+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash) VALUES($1,'world','*',gbrain_fact_fingerprint($2))", [f.id, claim]);+ const boundaries: string[] = [];+ const result = await publishMutation(engine, repair.row, repair.prepared, localHostId(), {+ boundary: async name => { boundaries.push(name); }, fileBoundary: name => { boundaries.push(name); } });+ expect(result.state).toBe('conflict');+ expect(boundaries).not.toContain('before_publication');+ expect(boundaries).not.toContain('before_file');+ expect(readFileSync(f.file)).toEqual(originalBytes);+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);+ });+ }+}), 120_000);