Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(google): unmanaged connector re-renders carry brain-added fences; a file lacking only gbrain's facts fence is replaceable (#7292)

garrytand0a73fcec440
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index dcfd09fba3..c78330660d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1092,6 +1092,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-133 (file-drift provenance, database and signal stops). `since` is stamped at the merge slot.
{ since: '0.60.359.0', text: 'A `gbrain repair file-drift --held --side deleted --state file_gone` preview names each gone file\'s provenance (`details.pages[].provenance`, counted in `details.provenance`): the newest commit of HEAD\'s full history that deleted it (sha, author, date, subject), `never_committed` when no commit held it, or `deletion_uncommitted` when HEAD still holds it. New `--provenance never_committed|deleted_by_commit|deletion_uncommitted` keeps only the holds of one provenance. `--provenance never_committed --prefer database` keeps each page database-only: no file is written, the page forgets its recorded path (`database_only_reason=detached`) and the hold is cleared, so the next sync holds nothing again; `--prefer file` with it is refused, since each page holds the only copy.' },
{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },
+ // #7292 (GBRA-133: brain-added fences on unmanaged connector pages). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'On a brain without managed persistence, a Google connector re-render now carries the page\'s `## Facts` and `## Takes` fences (added by loop extraction or `remember`) into the file and the database, as the managed connector already did; before, the re-render dropped them and the next `extract_facts` expired those facts. A contact or email page whose database copy holds a facts fence its checkout file lacks is no longer held `file_database_drift`: the file holds no edit the database lacks, so the re-render replaces it and writes the fence back. A page already held that way imports on its next attempt (a new upstream change, or `gbrain sources retry-held <id>`). A file with a real edit is still held, and a stored fence the render cannot carry verbatim refuses `connector_fence_below_timeline` (preview the fix with `gbrain repair connector-fences --source <id>`).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.ts
index 2b123bbd11..bf7bc6e056 100644
--- a/src/core/facts/file-body-guard.ts
+++ b/src/core/facts/file-body-guard.ts
@@ -132,9 +132,13 @@ function fileHeldBy(fileBytes: string, slug: string, state: StoredState): boolea
*
* `expectedFileBytes` is what the caller passes to `writePageThrough` (null: the file must still be absent), so a file
* that changes between this check and the write is refused there too.
+ *
+ * `alsoHeldAs` (GBRA-133, #7292): other bytes the file stands for, or null. A connector passes the file with the live
+ * page's `## Facts` fence put back: that fence is gbrain's own content, which the provider's render never had, so a
+ * file that lacks only it holds no edit the database lacks.
*/
-export async function replaceableFile(engine: BrainEngine, sourceId: string, slug: string, filePath: string):
- Promise<{ ok: true; expectedFileBytes: string | null } | { ok: false }> {
+export async function replaceableFile(engine: BrainEngine, sourceId: string, slug: string, filePath: string,
+ alsoHeldAs?: (fileBytes: string) => string | null): Promise<{ ok: true; expectedFileBytes: string | null } | { ok: false }> {
if (!existsSync(filePath)) return { ok: true, expectedFileBytes: null };
const bytes = readFileSync(filePath, 'utf-8');
const states = await engine.executeRaw<StoredState>(
@@ -145,5 +149,7 @@ export async function replaceableFile(engine: BrainEngine, sourceId: string, slu
(SELECT v.compiled_truth, v.timeline, v.frontmatter, v.title, v.type, v.tags FROM page_versions v JOIN pages p ON p.id = v.page_id
WHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth IS NOT NULL ORDER BY v.id DESC LIMIT ${HISTORY_ROWS})`,
[sourceId, slug]);
- return states.some(state => fileHeldBy(bytes, slug, state)) ? { ok: true, expectedFileBytes: bytes } : { ok: false };
+ const candidate = alsoHeldAs?.(bytes) ?? null;
+ return states.some(state => fileHeldBy(bytes, slug, state) || candidate !== null && fileHeldBy(candidate, slug, state))
+ ? { ok: true, expectedFileBytes: bytes } : { ok: false };
}
diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.ts
index df0e58bd6c..409289a9a7 100644
--- a/src/core/google/sweep-shared.ts
+++ b/src/core/google/sweep-shared.ts
@@ -14,6 +14,11 @@ import { connectorRender } from '../connectors/connector-text.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { mkdirPrivate } from '../atomic-write.ts';
import { replaceableFile } from '../facts/file-body-guard.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, replaceOrInsertFactsFence } from '../facts-fence.ts';
+import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';
+import { conceptPreservationHold, preserveCanonicalFences } from '../cycle/concept-publication.ts';
+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
+import type { Page } from '../types.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import { OperationError } from '../ops/contract.ts';
import { slugifyPath } from '../sync.ts';
@@ -119,6 +124,35 @@ function writePrivateTemp(tmpPath: string, markdown: string): void {
}
}
+const hasFence = (text: string | null | undefined) => [FACTS_FENCE_BEGIN, TAKES_FENCE_BEGIN].some(begin => (text ?? '').includes(begin));
+
+/**
+ * GBRA-133 (#7292): facts and takes fences added on the brain (loop extraction, `remember`) are not part of the
+ * provider's render. The managed connector carries them into each re-render (connector-sync.ts); the unmanaged one
+ * replaced the page with the bare render, so a re-render dropped the fence from the file and the database and the next
+ * `extract_facts` expired its facts. Carry them the same way: a render that brings its own fence owns it, and a stored
+ * fence the render cannot carry verbatim (below the timeline sentinel, duplicated, unbalanced, unparseable) refuses
+ * `connector_fence_below_timeline` instead of expiring its rows.
+ */
+async function carryStoredFences(sourceId: string, slug: string, relPath: string, existing: Page | null, markdown: string): Promise<string> {
+ if (!existing || !(hasFence(existing.compiled_truth) || hasFence(existing.timeline))) return markdown;
+ const parsed = parseMarkdown(markdown, relPath);
+ if (hasFence(parsed.compiled_truth)) return markdown;
+ const hold = conceptPreservationHold(existing);
+ if (hold) throw (await import('../persistence/connector-sync.ts')).connectorFenceRefusal(sourceId, slug, hold);
+ return serializePageToMarkdown({ ...existing, ...parsed, compiled_truth: preserveCanonicalFences(existing, parsed.compiled_truth),
+ type: parsed.typeExplicit ? parsed.type : existing.type }, parsed.tags);
+}
+
+/** GBRA-133 (#7292): the checkout file with the live page's `## Facts` fence put back, for `replaceableFile`; null when it has a fence of its own. */
+function withStoredFactsFence(existing: Page): (fileBytes: string) => string | null {
+ const body = existing.compiled_truth ?? '';
+ const start = body.indexOf(FACTS_FENCE_BEGIN);
+ const stop = start === -1 ? -1 : body.indexOf(FACTS_FENCE_END, start + FACTS_FENCE_BEGIN.length);
+ const block = stop === -1 ? null : body.slice(start, stop + FACTS_FENCE_END.length);
+ return fileBytes => block === null || hasFence(fileBytes) ? null : replaceOrInsertFactsFence(fileBytes, block);
+}
+
export async function importRendered(
deps: GoogleSyncDeps,
relPath: string,
@@ -149,8 +183,9 @@ export async function importRendered(
assertContained(deps.cfg.dir, filePath);
const existing = await deps.engine.getPage(slug, { sourceId: deps.sourceId });
if (existing) assertInlineBody(existing, 'Google connector materialization');
+ markdown = await carryStoredFences(deps.sourceId, slug, relPath, existing, markdown);
const databaseOnly = await isWriteThroughDisabled(deps.engine) || isSourceDbOnlySlug(deps.cfg.dir, slug, 'refuse');
- const guard = databaseOnly ? null : await replaceableFile(deps.engine, deps.sourceId, slug, filePath);
+ const guard = databaseOnly ? null : await replaceableFile(deps.engine, deps.sourceId, slug, filePath, existing ? withStoredFactsFence(existing) : undefined);
const drift = () => new OperationError('file_database_drift',
`${slug}: the checkout file has an edit not retained in the database, or changed during import. The file was not replaced. If the file is newer, run gbrain sync --source ${deps.sourceId}; if the database is newer, re-save its page with write-through on; if both changed, ask the user which version to keep before retrying.`,
'Import the newer file with gbrain sync, or ask the user which version to keep; the item is held until then.');
diff --git a/test/google-connector-facts-fence-7292.test.ts b/test/google-connector-facts-fence-7292.test.ts
new file mode 100644
index 0000000000..97b86ebc73
--- /dev/null
+++ b/test/google-connector-facts-fence-7292.test.ts
@@ -0,0 +1,113 @@
+/**
+ * #7292 (GBRA-133): facts that loop extraction (or `remember`) writes into the `## Facts` fence of an unmanaged Google
+ * connector page. The managed connector carries brain-added fences into each re-render; the unmanaged one replaced the
+ * page with the bare provider render, so the fence left the file and the database and the next `extract_facts` expired
+ * the facts. And a page whose database body holds the fence while its checkout file does not was refused
+ * `file_database_drift` on every re-render and frozen held after three, with no command that could unfreeze it. Now the
+ * unmanaged re-render carries the stored fence, a file that lacks only gbrain's own fence is replaceable (the carried
+ * render writes the fence back), and a held page imports on its next attempt (`gbrain sources retry-held`). A real file
+ * edit is still held. Real PGLite and Postgres (when DATABASE_URL is set), the real Google importer, a fake People API.
+ * Contributed report: @h6y3.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { parseGoogleSourceConfig, readGoogleState, runGoogleSync } from '../src/core/google/google-source.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { FACTS_FENCE_BEGIN, stripFactsFence } from '../src/core/facts-fence.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { runRetryHeld } from '../src/commands/sources-retry-held.ts';
+import { contact, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SOURCE = 'google-example';
+const SLUG = 'people/alice-example';
+const CLAIM = 'Alice will send the signed deck by Friday';
+const CONFIG = { kind: 'google', g_account: '[email protected]', g_services: 'contacts', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+
+interface Brain { engine: BrainEngine; root: string; path: string; file(): string; body(): Promise<string>; bump(): void; sync(): ReturnType<typeof runGoogleSync>;
+ remember(): Promise<void>; activeFacts(): Promise<number> }
+
+async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-7292-'));
+ try {
+ await withEnv({ GBRAIN_HOME: root, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const dir = join(root, 'google');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [SOURCE, dir, JSON.stringify(CONFIG)]);
+ let generation = 0;
+ const fetch = withGoogleAccount(async (url: string) => {
+ if (new URL(url).pathname === '/v1/people/me/connections') return json({ connections: [
+ { ...contact('c1', 'Alice Example'), organizations: [{ name: `Upstream ${generation}` }] },
+ { ...contact('c2', 'Bob Example'), organizations: [{ name: `Upstream ${generation}` }] }], nextSyncToken: `token-${generation}` });
+ throw new Error(`Unexpected Google fixture route: ${url}`);
+ }, CONFIG.g_account);
+ const cfg = parseGoogleSourceConfig(CONFIG, dir);
+ const sync = () => runGoogleSync(engine, SOURCE, cfg, { ...options, sourceId: SOURCE }, fetch);
+ expect((await sync()).failedFiles ?? 0).toBe(0);
+ const path = join(dir, `${SLUG}.md`);
+ await run({ engine, root, path, file: () => readFileSync(path, 'utf8'), bump: () => { generation++; }, sync,
+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, SLUG]))[0]!.compiled_truth,
+ remember: async () => { await writeSingleFact(engine, SOURCE, { fact: CLAIM, kind: 'commitment', entity: 'Alice Example', visibility: 'private', provenance: 'email thread (synthetic)', remote: false }); },
+ activeFacts: async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [SOURCE, CLAIM]))[0]!.n) });
+ } finally { await close(); }
+ });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+}
+
+const holds = (root: string) => ((readGoogleState(join(root, 'google')).item_holds ?? { items: {} }) as { items: Record<string, { code: string; state: string }> }).items;
+
+for (const backend of testBackends()) describe(`[${backend}] #7292: brain-added facts on an unmanaged Google connector page`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test('a re-render carries the fence into the file and the database, and extract_facts keeps the fact', async () => withBrain(databaseUrl, async b => {
+ await b.remember();
+ expect(b.file()).toContain(CLAIM);
+ b.bump();
+ const result = await b.sync();
+ expect(result.failedFiles ?? 0).toBe(0);
+ expect(b.file()).toContain('Upstream 1');
+ expect(b.file()).toContain(CLAIM);
+ expect(await b.body()).toContain(CLAIM);
+ await runExtractFacts(b.engine, { sourceId: SOURCE });
+ expect(await b.activeFacts()).toBe(1);
+ }), 180_000);
+
+ test('a file that lacks only the database fence is re-rendered with it instead of being held file_database_drift', async () => withBrain(databaseUrl, async b => {
+ await b.remember();
+ writeFileSync(b.path, stripFactsFence(b.file()).replace(/\n## Facts\n+/, '\n'));
+ expect(b.file()).not.toContain(FACTS_FENCE_BEGIN);
+ expect(await b.body()).toContain(CLAIM);
+ b.bump();
+ for (let i = 0; i < 3; i++) expect((await b.sync()).failedFiles ?? 0).toBe(0);
+ expect(holds(b.root)['contact:people/c1']).toBeUndefined();
+ expect(b.file()).toContain('Upstream 1');
+ expect(b.file()).toContain(CLAIM);
+ expect(await b.body()).toContain(CLAIM);
+ expect(await b.activeFacts()).toBe(1);
+ }), 180_000);
+
+ test('a page already held for a real edit imports on retry-held once only the fence differs; a real edit is still held', async () => withBrain(databaseUrl, async b => {
+ await b.remember();
+ const bare = stripFactsFence(b.file()).replace(/\n## Facts\n+/, '\n');
+ writeFileSync(b.path, `${bare}\nFILE-ONLY-EDIT: kept by the user.\n`);
+ b.bump();
+ for (let i = 0; i < 3; i++) expect((await b.sync()).failedFiles).toBe(1);
+ expect(holds(b.root)['contact:people/c1']).toMatchObject({ code: 'file_database_drift', state: 'held' });
+ expect(b.file()).toContain('FILE-ONLY-EDIT');
+ writeFileSync(b.path, bare);
+ await runRetryHeld(b.engine, [SOURCE]);
+ expect((await b.sync()).failedFiles ?? 0).toBe(0);
+ expect(holds(b.root)['contact:people/c1']?.state).not.toBe('held');
+ expect(b.file()).toContain(CLAIM);
+ expect(b.file()).toContain('Upstream 1');
+ }), 180_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 745364def6..1a87b3122a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -72,6 +72,7 @@ test/fence-repair-receipts.test.ts
test/forecast-journal.test.ts
test/frontmatter-reserved-keys-6454.test.ts
test/get-chunks-paging.test.ts
+test/google-connector-facts-fence-7292.test.ts
test/graduation-copy.test.ts
test/graduation-digest.test.ts
test/graduation-drain.test.ts