Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(atoms): publish atom maintenance database-only on unbound connector sources (#5856)
garrytan4b735f695cf4
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex ae0719dda9..c4e16d7d21 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -10,6 +10,7 @@ import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './import { admitWriteInTransaction, getWriteRequest, receiptFor } from './journal.ts';import { digest, requireUuid, sha256 } from './digest.ts';import { acquireWorktree, getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';+import { isConnectorSourceKind } from './connector-identity.ts';import { preparePageMutation } from './page-prepare.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';import type { PreparedMutation } from './coordinator.ts';@@ -56,8 +57,8 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,if (caller && caller.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {throw new OperationError('permission_denied', 'Atom extraction cannot mutate a managed brain through an untrusted caller; a trusted local, source-wide writer is required.');}- const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null }>(- 'SELECT incarnation,archived,local_path FROM sources WHERE id=$1', [sourceId]);+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The atom source is unavailable.');if (!currentVerifiedLocalWriter()) await registerLocalWriter(engine, 'cli');const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext,@@ -70,7 +71,10 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,const binding = await getWorktreeBinding(engine, sourceId);const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');- if (writeThrough && root && !binding) throw new OperationError('owner_unavailable', 'Atom maintenance requires the configured canonical owner.');+ // An unbound connector source is database-only by design (connector_database), like its connector sync:+ // its local_path is the connector's state directory, not a canonical checkout.+ const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);+ if (writeThrough && root && !binding && !connectorDatabase) throw new OperationError('owner_unavailable', 'Atom maintenance requires the configured canonical owner.');if (writeThrough && binding && (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path)) {throw new OperationError('owner_unavailable', 'The canonical atom owner is unavailable; no extraction was started.');}@@ -80,6 +84,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,await lock.release();}if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';+ else if (connectorDatabase) authority.databaseOnlyReason = 'connector_database';else if (!binding) authority.databaseOnlyReason = 'no_repo_configured';const session: ManagedAtomSession = { sourceId, incarnation: source.incarnation, authority, binding: writeThrough ? binding : null, config: { engine: engine.kind } as GBrainConfig };if (retry) {@@ -186,7 +191,10 @@ function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {if (atomRetryInputKey(session, session.retry.origin) !== atomRetryInputKey(session, origin)) throw new OperationError('source_changed', 'The atom retry input no longer matches its accepted source snapshot.');return session.retry.runKey;}- return atomInputKey(session, origin);+ // A database-only connector run is its own run: once an owner claims the source, the owner's+ // run extracts again instead of replaying the batch the claim refused (claiming keeps the incarnation).+ const key = atomInputKey(session, origin);+ return session.authority.databaseOnlyReason === 'connector_database' ? digest([key, 'connector_database']) : key;}function atomRequestId(key: string, slug: string): string {@@ -330,6 +338,10 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Writethrow new OperationError('permission_denied', 'Unsupported atom maintenance intent.');}const validate = async (tx: BrainEngine) => {+ // A connector preflighted as unbound publishes database-only; one claimed since then must use its owner.+ if (row.authority.databaseOnlyReason === 'connector_database' && await getWorktreeBinding(tx, row.source_id)) {+ throw new OperationError('source_changed', 'The connector source gained a canonical owner after atom preflight; the next run extracts through its owner.');+ }if (p.origin.kind === 'transcript') {if (sha256(readFileSync(p.origin.locator)) !== p.origin.textHash) throw new OperationError('source_changed', 'The accepted atom transcript changed.');} else {diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex f204661c52..58c94471e4 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -1,5 +1,5 @@import { expect } from 'bun:test';-import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';@@ -8,6 +8,7 @@ import { runPhaseExtractAtoms, countExtractAtomsBacklog, discoverExtractablePageimport { disposePersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-root.ts';import { registerLocalWriter, withVerifiedLocalRegistration, type LocalGrant } from '../../src/core/persistence/identity.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts';@@ -22,7 +23,7 @@ import { registerBuiltinHandlers } from '../../src/commands/jobs.ts';import type { MinionJobContext } from '../../src/core/minions/types.ts';import { withEnv } from './with-env.ts';-export const atomContractCases = ['publication', 'zero_yield', 'revision', 'removal', 'deferred', 'unavailable', 'source_replaced', 'malformed', 'malformed_retry', 'malformed_retry_failure', 'malformed_retry_revision', 'publication_retry', 'pagination', 'transcript', 'transcript_changed'] as const;+export const atomContractCases = ['publication', 'zero_yield', 'revision', 'removal', 'deferred', 'unavailable', 'source_replaced', 'malformed', 'malformed_retry', 'malformed_retry_failure', 'malformed_retry_revision', 'publication_retry', 'pagination', 'transcript', 'transcript_changed', 'connector', 'connector_claimed'] as const;type Case = typeof atomContractCases[number];export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case): Promise<void> {@@ -51,6 +52,26 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):await registerLocalWriter(engine, 'cli');binding = await claimWorktree(engine, sourceId, root);}+ // #5856: a Google source's local_path is the connector's state directory, not a canonical checkout.+ const connectorDir = scenario.startsWith('connector') ? join(home, 'clones', `${sourceId}-google`) : undefined;+ // Its content files: the manifest skips the fence and owner markers a registered or claimed root carries.+ const connectorFiles = (): Record<string, string> => {+ const files: Record<string, string> = {};+ const visit = (dir: string, prefix: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === '.git' || entry.name === '.gbrain-managed' || isPhysicalRootMetadata(entry.name)) continue;+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;+ if (entry.isDirectory()) visit(join(dir, entry.name), rel);+ else files[rel] = readFileSync(join(dir, entry.name), 'utf8');+ }+ };+ visit(connectorDir!, '');+ return files;+ };+ if (connectorDir) {+ mkdirSync(connectorDir, { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path=$2, config=jsonb_build_object('kind','google') WHERE id=$1", [sourceId, connectorDir]);+ }await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');if (scenario === 'unavailable') await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding!.worktree_id]);let calls = 0;@@ -70,6 +91,12 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):});if (scenario === 'deferred') await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding!.worktree_id]);if (scenario === 'transcript_changed') writeFileSync(transcript!, 'Changed while extraction was running.');+ if (scenario === 'connector_claimed') {+ // The owner claims the connector source after the atom preflight, before admission.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await claimWorktree(engine, sourceId, connectorDir!);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }if (scenario === 'publication_retry') {const path = join(root!, 'atoms', new Date().toISOString().slice(0, 10));mkdirSync(path, { recursive: true });@@ -153,14 +180,24 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):expect(await discoverExtractablePages(engine, sourceId)).toEqual([]);return;}- if (scenario === 'revision' || scenario === 'removal' || scenario === 'source_replaced' || scenario === 'transcript_changed') {+ if (scenario === 'revision' || scenario === 'removal' || scenario === 'source_replaced' || scenario === 'transcript_changed' || scenario === 'connector_claimed') {expect(calls).toBe(1);expect(first.status).toBe('warn');expect(first.details?.atoms_extracted).toBe(0);+ if (connectorDir) expect(connectorFiles()).toEqual({});expect(await engine.executeRaw("SELECT id FROM pages WHERE source_id=$1 AND type='atom'", [sourceId])).toHaveLength(0);expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1", [sourceId])).toHaveLength(0);if (scenario === 'revision') expect((await engine.getPage(page.slug, { sourceId }))?.compiled_truth).toContain('A concurrent edit.');if (scenario === 'removal') expect(await engine.getPage(page.slug, { sourceId })).toBeNull();+ if (scenario === 'connector_claimed') {+ // The next run extracts through the new owner instead of replaying the refused database-only batch.+ await disposePersistenceConsumer(engine);+ expect((await runPhaseExtractAtoms(engine, opts)).status).toBe('ok');+ expect(calls).toBe(2);+ const [atom] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]);+ expect(Object.keys(connectorFiles())).toEqual([`${atom.slug}.md`]);+ expect(await countExtractAtomsBacklog(engine, sourceId)).toBe(0);+ }return;}if (scenario === 'pagination') {@@ -210,6 +247,12 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):if (!transcript) expect(await engine.executeRaw('SELECT l.id FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id WHERE f.source_id=$1 AND t.source_id=$1 AND f.slug=$2 AND t.slug=$3', [sourceId, page.slug, atoms[0].slug])).toHaveLength(1);if (root) expect(readFileSync(join(root, `${atoms[0].slug}.md`), 'utf8')).toContain('visibility: private');}+ if (connectorDir) {+ // Database-only, exactly as the connector's own sync publishes: no file lands in its state directory.+ expect(connectorFiles()).toEqual({});+ expect(await engine.executeRaw("SELECT DISTINCT authority->>'databaseOnlyReason' AS reason FROM persistence_requests WHERE source_id=$1", [sourceId]))+ .toEqual([{ reason: 'connector_database' }]);+ }if (scenario !== 'malformed' && !transcript) expect(await countExtractAtomsBacklog(engine, sourceId)).toBe(0);expect((await engine.getPage(page.slug, { sourceId }))?.frontmatter).not.toHaveProperty('atoms_scan_hash');if (scenario === 'zero_yield' || scenario === 'malformed') {