Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sweep): the links/timeline pass publishes timeline rows through the coordinator on a managed brain

garrytan9d6b789f506f
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index f603f30ee1..3c05f831e1 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -255,6 +255,7 @@ jobs:
test/import-frontmatter-key-order-5158.test.ts
test/import-revision-concurrency.test.ts
test/managed-sweep-corpus-windows.test.ts
+ test/managed-sweep-timeline.test.ts
test/managed-sync-bulk.test.ts
test/managed-sync-chunker-version.test.ts
test/managed-sync-group-completion.test.ts
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.ts
index 50c3cccaa3..86e2a227e9 100644
--- a/src/commands/extract-timeline-db.ts
+++ b/src/commands/extract-timeline-db.ts
@@ -265,6 +265,19 @@ async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAu
}
}
+/**
+ * One page's timeline on a managed brain, through the coordinator (the serve
+ * sweep's path): rows added, 0 when nothing changes, or 'unsettled' when the
+ * page changed mid-run or its request is still pending (retry next time).
+ */
+export async function publishManagedPageTimeline(engine: BrainEngine, slug: string, sourceId: string): Promise<number | 'unsettled'> {
+ const authority = await maintenancePreflight(engine, sourceId);
+ if (!authority) throw opError('writer_coordinator_required', 'This brain is not managed; write the timeline batch directly.',
+ `Source ${sourceId} has no managed writer, so there is no coordinator to publish through.`);
+ const outcome = await publishPageTimeline(engine, authority, slug, sourceId, { dryRun: false, jsonMode: false });
+ return outcome === 'skipped' || outcome === 'pending' ? 'unsettled' : outcome ?? 0;
+}
+
/** Preparer for `managed_maintenance_timeline_extract`: a database-only publication on the page key. */
function timelinePageChanged(row: WriteRequest, message: string): OperationError {
return opError('page_identity_changed', message,
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 403a580c9e..3a1be055cc 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -52,6 +52,7 @@ import type { BrainEngine, LinkBatchInput, TimelineBatchInput } from './engine.t
import type { FactsBackstopCtx } from './facts/backstop.ts';
import type { CapabilityReport } from './capability.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
+import { managedPersistenceEnabled } from './persistence/ownership.ts';
/** Delay before the serve-startup sweep fires (post-connect settle). */
export const STARTUP_SWEEP_DELAY_MS = 3_000;
@@ -480,7 +481,22 @@ async function runLinksTimelinePass(
// Engine batch primitives self-retry; default auditSite labels apply
// (BATCH_AUDIT_SITES is a closed enum owned by retry.ts).
- if (tlBatch.length > 0) {
+ // A managed brain refuses raw timeline inserts (managed_writer_guard): each page publishes through the coordinator.
+ const timelineUnsettled = new Set<string>();
+ if (tlBatch.length > 0 && await managedPersistenceEnabled(engine)) {
+ const { publishManagedPageTimeline } = await import('../commands/extract-timeline-db.ts');
+ for (const slug of new Set(tlBatch.map(row => row.slug))) {
+ if (overBudget()) { skip('budget_exhausted:timeline'); timelineUnsettled.add(slug); continue; }
+ try {
+ const added = await publishManagedPageTimeline(engine, slug, sourceId);
+ if (added === 'unsettled') timelineUnsettled.add(slug);
+ else report.timelineExtracted += added;
+ } catch {
+ skip('timeline_publish_failed');
+ timelineUnsettled.add(slug);
+ }
+ }
+ } else if (tlBatch.length > 0) {
report.timelineExtracted += await maintenanceTransaction(engine, tx => tx.addTimelineEntriesBatch(tlBatch)); // gbrain-allow-direct-insert: same extract-path rationale as addLinksBatch above [CX-P0.3]
}
@@ -493,7 +509,7 @@ async function runLinksTimelinePass(
// contain frontmatter candidates and deleting them would clobber valid
// edges. 'manual' and 'mentions' are never touched. A page whose reconcile
// fails (or is cut by budget) is left unstamped so the next sweep retries.
- const stampable = new Set(processedRefs.map(r => r.slug));
+ const stampable = new Set(processedRefs.map(r => r.slug).filter(slug => !timelineUnsettled.has(slug)));
if (linksEnabled) {
const desiredBySlug = new Map<string, LinkBatchInput[]>(
processedRefs.map(r => [r.slug, []]),
diff --git a/test/managed-sweep-timeline.test.ts b/test/managed-sweep-timeline.test.ts
new file mode 100644
index 0000000000..aa680bee37
--- /dev/null
+++ b/test/managed-sweep-timeline.test.ts
@@ -0,0 +1,88 @@
+/**
+ * The serve sweep's links/timeline pass on a managed brain publishes each
+ * page's timeline through the persistence coordinator.
+ *
+ * 1. Protects: a page whose timeline rows are missing (written before the
+ * brain was managed, or by a remote writer) gets them from the sweep as a
+ * committed `managed_maintenance_timeline_extract` request, and the pass
+ * reports no `links_timeline_error`.
+ * 2. Fails when: the sweep writes `timeline_entries` with a raw batch insert,
+ * which the armed managed writer guard refuses
+ * (`writer_coordinator_required`) and which stopped the whole pass.
+ * 3. extract-timeline-db covers `gbrain extract timeline --source db`; this
+ * covers the sweep that remote writes rely on.
+ * 4. No production seam.
+ *
+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).
+ */
+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 { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runMaintenanceSweep } from '../src/core/sweep.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-sweep-timeline-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 });
+});
+
+test('managed: the sweep publishes missing timeline rows through the coordinator', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-sweep-timeline-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `timeline-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, 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 engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example.',
+ timeline: '- **2024-03-01** | note — Joined [Acme](companies/acme-example)\n- **2025-01-15** | note — Gave a talk', frontmatter: {} }, { sourceId });
+ expect(await engine.executeRaw('SELECT 1 FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1', [sourceId])).toEqual([]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await expect(engine.addTimelineEntriesBatch([{ slug: 'people/alice-example', date: '2024-03-01', source: 'note', summary: 'raw', detail: '', source_id: sourceId }])) // gbrain-allow-direct-insert: proves the guard is armed
+ .rejects.toThrow(/writer_coordinator_required/);
+
+ const report = await runMaintenanceSweep(engine, { sourceId, budgetMs: 120_000 });
+ expect(report.skipped.map(s => s.reason)).not.toContain('links_timeline_error');
+ expect(report.timelineExtracted).toBe(2);
+ const rows = await engine.executeRaw<{ date: string; summary: string }>(`SELECT to_char(t.date,'YYYY-MM-DD') AS date,t.summary FROM timeline_entries t
+ JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 ORDER BY t.date`, [sourceId]);
+ expect(rows.map(r => r.date)).toEqual(['2024-03-01', '2025-01-15']);
+ const [published] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests
+ WHERE source_id=$1 AND state='committed' AND intent->>'kind'='managed_maintenance_timeline_extract'`, [sourceId]);
+ expect(published.n).toBe(1);
+ // A second sweep finds nothing left to publish.
+ const again = await runMaintenanceSweep(engine, { sourceId, budgetMs: 120_000 });
+ expect(again.timelineExtracted).toBe(0);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1').catch(() => undefined);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}, 180_000);
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index b021ca7fee..88419751fc 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -681,12 +681,13 @@ describe('runMaintenanceSweep — bounded link resolution (no listAllPageRefs)',
}));
expect(r.timelineExtracted).toBe(1);
expect(log).not.toContain('listAllPageRefs');
- // Exactly three raw queries: the pass-1 fence scan, the pass-2 recency
- // scan and the maintenance principal's brain_id lookup the attributed
- // timeline batch makes (an installation with a CLI registration adds one
- // query that verifies it, once per engine). No candidates ⇒ no ref-lookup
- // query.
- expect(log.filter((m) => m === 'executeRaw').length).toBe(3);
+ // Exactly four raw queries: the pass-1 fence scan, the pass-2 recency
+ // scan, the managed-brain check that picks the timeline write path (a
+ // managed brain publishes per page through the coordinator) and the
+ // maintenance principal's brain_id lookup the attributed timeline batch
+ // makes (an installation with a CLI registration adds one query that
+ // verifies it, once per engine). No candidates ⇒ no ref-lookup query.
+ expect(log.filter((m) => m === 'executeRaw').length).toBe(4);
});
});