Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

keep_db policy: owner-host maintenance worker reconciles drifted pages with the database copy, rate-limited; doctor echoes it (#6696 C7)

garrytan203f78482831
diff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.ts
index c411f4bc14..e90c50e4bb 100644
--- a/src/commands/doctor/checks/maintenance-drift.ts
+++ b/src/commands/doctor/checks/maintenance-drift.ts
@@ -2,6 +2,9 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { agentFix, checkError } from '../check-fix.ts';
import { auditConflictsCommand, FILE_DRIFT_MESSAGE, fileDriftRepairCommand, liveFileDrift, readDriftSkips } from '../../../core/persistence/drift-conflicts.ts';
+import { existingLocalHostId } from '../../../core/persistence/identity.ts';
+import { isKeepDbSlug } from '../../../core/storage-config.ts';
+import { keepDbReceiptCost, readKeepDbPolicy } from '../../../core/repair/keep-db-policy.ts';
/** Newest request sequences scanned for drift conflicts (one range read of the unique sequence index). */
const WINDOW = 20_000;
@@ -16,6 +19,10 @@ const LIVE_LIMIT = 100;
* It measures the drift itself, not conflict-row growth: producers back off
* before admission, so a drifted page stops adding receipts. Names the
* read-only audit and the explicit-only `gbrain repair file-drift` preview.
+ * #6696 C7: on the owner host it also echoes each source's effective
+ * `storage.keep_db` policy (`keep_db_policy`, present only when one is
+ * declared): its prefixes, how many of the drifted pages checked here it
+ * matches, and their receipt cost (one request each).
*/
export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
const docs = 'docs/guides/troubleshooting.md#maintenance-write-drift';
@@ -24,7 +31,9 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?
const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');
const floor = String(Math.max(0, Number(bounds?.top ?? 0) - WINDOW));
const skips = await readDriftSkips(engine);
+ const hostId = existingLocalHostId();
const rows = [];
+ const policies = [];
for (const sourceId of sources) {
const candidates = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r
WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3
@@ -37,23 +46,34 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?
if (live.still_present === true) drifted.add(slug);
else if (live.still_present === null) unknown++;
}
+ const unchecked = Math.max(0, candidates.length - LIVE_LIMIT);
if (drifted.size || skipped.length || unknown) rows.push({ source_id: sourceId, drifted: drifted.size, sample: [...drifted].slice(0, 5),
- concept_skips: skipped.length, unknown, unchecked: Math.max(0, candidates.length - LIVE_LIMIT) });
+ concept_skips: skipped.length, unknown, unchecked });
+ try {
+ const policy = await readKeepDbPolicy(engine, sourceId, hostId);
+ const matched = policy ? [...drifted].filter(slug => isKeepDbSlug(slug, policy.keep_db)).length : 0;
+ if (policy) policies.push({ ...policy, matched, unchecked, receipt_cost: keepDbReceiptCost(matched) });
+ } catch (error) {
+ policies.push({ source_id: sourceId, error: error instanceof Error ? error.message : String(error) });
+ }
}
const count = rows.reduce((sum, row) => sum + row.drifted, 0);
const skipCount = rows.reduce((sum, row) => sum + row.concept_skips, 0);
- const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs };
+ const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, ...(policies.length ? { keep_db_policy: policies } : {}) };
+ const policyNote = policies.map(policy => 'error' in policy ? ` storage.keep_db of ${policy.source_id} could not be read: ${policy.error}`
+ : ` storage.keep_db of ${policy.source_id} (${policy.keep_db.join(', ')}) matches ${policy.matched} of them${policy.unchecked ? ` (${policy.unchecked} more not checked here)` : ''}; `
+ + `the owner host's maintenance worker reconciles them with the database copy, one rate-limited request each (${policy.receipt_cost.lifetime_ids} lifetime id(s), ${policy.receipt_cost.receipt_bytes} receipt bytes).`).join('');
if (!count && !skipCount) {
const unknown = rows.reduce((sum, row) => sum + row.unknown, 0);
return { name: 'maintenance_write_drift', status: 'ok', details,
message: unknown ? `No page checked on this host has a canonical file that differs from the database; ${unknown} could not be checked here (run doctor on the canonical owner host).`
- : 'No page whose writes refuse source_changed still has a canonical file that differs from the database.' };
+ : `No page whose writes refuse source_changed still has a canonical file that differs from the database.${policyNote}` };
}
const first = rows.find(row => row.drifted || row.concept_skips)!.source_id;
return { name: 'maintenance_write_drift', status: 'warn', details,
message: `${count} page(s) have a canonical file that differs from the database, so every coordinated write to them refuses source_changed `
+ `(${rows.filter(row => row.drifted || row.concept_skips).map(row => `${row.source_id}: ${row.drifted} drifted, ${row.concept_skips} concept skip(s)`).join('; ')}). `
- + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.`,
+ + `Maintenance now skips them before spending or admitting anything. List them: ${auditConflictsCommand(first)}; preview the resolution: ${fileDriftRepairCommand(first)} (or --prefer database), then apply with the --expect hash it prints.${policyNote}`,
fix: agentFix(['gbrain', 'sources', 'reconcile', first, '--brain', 'host', '--audit', '--conflicts', '--json'],
'Read-only: lists the conflict receipts grouped by slug, whether each file still differs, its drift class and producer.', 'maintenance_write_drift', { docs }) };
} catch (error) {
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index cc92d640ea..7542ff7968 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -50,6 +50,8 @@ export const DEFAULT_ZOMBIE_CAP = 1;
/** An effects drain running this long names itself on stderr (serve), then again at this cadence. */
const DRAIN_NOTICE_AFTER_MS = 5_000;
const DRAIN_NOTICE_EVERY_MS = 10_000;
+/** #6696 C7: at most one storage.keep_db policy pass (KEEP_DB_BATCH requests) per this interval. */
+const KEEP_DB_POLICY_INTERVAL_MS = 10 * 60_000;
/** #6650: how often a consumer looks for claims held by an owner it can prove dead. */
export const DEAD_OWNER_SCAN_MS = 5_000;
const yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));
@@ -198,6 +200,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
private settleCursor: NoopSettleCursor | undefined;
private topologyWorker: Promise<unknown> | undefined;
private maintenanceWorker: Promise<unknown> | undefined;
+ /** #6696 C7: the storage.keep_db policy pass (resident owners only, at most one per KEEP_DB_POLICY_INTERVAL_MS while idle). */
+ private keepDbWorker: Promise<unknown> | undefined;
+ private nextKeepDb = 0;
private nextMaintenance = 0;
private publishedSinceMaintenance = 0;
private maintenanceVolume = 50;
@@ -238,7 +243,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
/** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */
zombieCap?: number;
/** Write the long-drain progress line on stderr (serve; never a CLI command that may print --json). */
- drainNotice?: boolean } = {}) {
+ drainNotice?: boolean;
+ /** #6696 C7: run the storage.keep_db policy (repair/keep-db-policy.ts) for the sources this host owns while idle. */
+ keepDbPolicy?: boolean } = {}) {
this.hostId = opts.hostId ?? localHostId();
this.statements = consumerStatementEngine(engine);
}
@@ -493,6 +500,11 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))
.catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });
}
+ if (this.opts.keepDbPolicy && !this.opts.requestsOnly && !this.keepDbWorker && Date.now() >= this.nextKeepDb) {
+ this.nextKeepDb = Date.now() + KEEP_DB_POLICY_INTERVAL_MS;
+ this.keepDbWorker = import('../repair/keep-db-policy.ts').then(({ runKeepDbPolicy }) => runKeepDbPolicy(this.engine, { hostId: this.hostId }))
+ .catch(error => this.report(error)).finally(() => { this.keepDbWorker = undefined; });
+ }
return;
}
}
@@ -1074,6 +1086,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
await this.effectsWorker;
await this.topologyWorker;
await this.maintenanceWorker;
+ await this.keepDbWorker;
this.unobserveCheckout?.();
this.unobserveCheckout = undefined;
try { this.loopDelay?.disable(); } catch { /* fail-open */ }
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 89890125db..02039ad968 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -112,6 +112,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
* `autopilot`, `mcp`) get a `WaiterOnlyConsumer` that probes the host's consumer rows on its first tick and settles to
* full or waiter-only (consumer-election.ts). Either way the returned object has the consumer's whole surface.
*/
+/** #6696 C7: the resident owners whose full consumer runs the storage.keep_db policy (never a short-lived command). */
+const KEEP_DB_POLICY_OWNERS = ['serve', 'jobs', 'autopilot'];
export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumerLike {
const prior = services.get(engine);
if (prior) {
@@ -122,7 +124,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
return prior.consumer;
}
const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,
- { drainNotice: claimOwnerKind() === 'serve', onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
+ { drainNotice: claimOwnerKind() === 'serve', keepDbPolicy: KEEP_DB_POLICY_OWNERS.includes(claimOwnerKind()), onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });
const kind = claimOwnerKind();
const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'
? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 161ece39ca..bd16b10f58 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -177,7 +177,8 @@ export interface RepairResult {
details?: Record<string, unknown>;
}
-const RECEIPT_BYTES = 16_384;
+/** Receipt bytes one repair admission reserves (the journal's minimum per-request reservation). */
+export const RECEIPT_BYTES = 16_384;
const STOP_RATIO = 0.9;
const SAMPLE = 10;
@@ -212,8 +213,8 @@ async function writeCursor(engine: BrainEngine, kind: RepairKind, scope: RepairS
[fingerprint(kind, scope, approval), JSON.stringify([{ kind, scope, cursor, run_id: runId }])]);
}
-/** Cumulative journal counters this repair's admissions consume, with their 90% stop line. */
-async function capacity(ctx: OperationContext) {
+/** Cumulative journal counters this repair's admissions consume, with their 90% stop line (also the keep_db policy's headroom gate). */
+export async function capacity(ctx: OperationContext) {
// A dry run never registers a writer; an unregistered installation has consumed nothing yet.
const principal = await requestPrincipalForContext(ctx).then(principalKey, () => 'principal:unregistered');
const limits = await readJournalLimits(ctx.engine);
diff --git a/src/core/repair/keep-db-policy.ts b/src/core/repair/keep-db-policy.ts
new file mode 100644
index 0000000000..3695adaf45
--- /dev/null
+++ b/src/core/repair/keep-db-policy.ts
@@ -0,0 +1,145 @@
+/**
+ * #6696 C7: the opt-in `storage.keep_db` policy (gbrain.yml), consumed only by
+ * the trusted local maintenance worker on the canonical owner host.
+ *
+ * A source whose gbrain.yml declares `keep_db:` prefixes asks that a drifted
+ * page under them (its canonical file differs from the database copy, so every
+ * coordinated write refuses `source_changed` / `file_database_drift`) be
+ * reconciled with the database copy winning, the resolution
+ * `gbrain repair file-drift --prefer database` previews, inside the same
+ * reconcile protections. Nothing else reads the policy: remote and caller
+ * writes to those pages keep refusing until the worker (or an operator)
+ * reconciles them.
+ *
+ * `runKeepDbPolicy` runs only for a source whose active binding this host
+ * owns. Candidates are the slugs under the prefixes with a drift conflict
+ * receipt in the newest `CONFLICT_WINDOW_DEFAULT` request sequences, plus the
+ * recorded concept drift skips; each is checked live before anything is
+ * prepared. Each drifted page gets one reconcile request (`runReconcileApply`)
+ * whose id is derived from the page revision and file bytes, so the same drift
+ * is never submitted twice, whatever its outcome. A run submits at most `limit`
+ * requests (`KEEP_DB_BATCH`; the consumer runs it at most every 10 minutes) and
+ * stops before an admission the `admission` gate refuses.
+ */
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';
+import { getWorktreeBinding } from '../persistence/ownership.ts';
+import { CONFLICT_WINDOW_DEFAULT, FILE_DRIFT_MESSAGE, liveFileDrift, readDriftSkips } from '../persistence/drift-conflicts.ts';
+import { readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { runReconcileApply } from '../persistence/reconcile.ts';
+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
+import { digest } from '../persistence/digest.ts';
+import { capacity, RECEIPT_BYTES } from './core.ts';
+import { prepareDriftPage } from './file-drift.ts';
+
+/** Reconcile requests one policy run submits at most. */
+export const KEEP_DB_BATCH = 10;
+/** Candidate slugs one source contributes to a run. */
+const CANDIDATE_LIMIT = 1000;
+
+export interface KeepDbPolicy { source_id: string; keep_db: string[] }
+
+export interface KeepDbRun {
+ submitted: number;
+ skipped_by_reason: Record<string, number>;
+ /** `rate_limit`: candidates remain past `limit`; `capacity`: the admission gate refused the next request. */
+ stopped?: 'rate_limit' | 'capacity';
+ sources: Array<KeepDbPolicy & { submitted: number }>;
+}
+
+/**
+ * The admission seam for this background producer: a stop reason when it must not admit now. The default is the
+ * repair core's 90% stop line on lifetime ids and receipt bytes; near-cap backpressure for background producers
+ * plugs in here.
+ */
+export type KeepDbAdmission = (engine: BrainEngine) => Promise<'capacity' | null>;
+
+const headroom: KeepDbAdmission = async engine => (await capacity({ engine, remote: false } as OperationContext))
+ .some(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) ? 'capacity' : null;
+
+/** One request's receipt cost, as doctor `maintenance_write_drift` reports it for the matched pages. */
+export const keepDbReceiptCost = (pages: number) => ({ lifetime_ids: pages, receipt_bytes: pages * RECEIPT_BYTES });
+
+/**
+ * The effective policy of one source on this host: the `keep_db` prefixes of its canonical checkout's gbrain.yml,
+ * read only when `hostId` owns the source's active binding (null otherwise, or when none are declared).
+ * Throws `StorageConfigError` for a gbrain.yml whose tiers overlap.
+ */
+export async function readKeepDbPolicy(engine: BrainEngine, sourceId: string, hostId: string | null): Promise<KeepDbPolicy | null> {
+ const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;
+ if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return null;
+ const keepDb = loadStorageConfig(join(binding.local_path, binding.relative_path))?.keep_db ?? [];
+ return keepDb.length ? { source_id: sourceId, keep_db: keepDb } : null;
+}
+
+const likeEscape = (value: string) => value.replace(/[\\%_]/g, char => `\\${char}`);
+
+async function candidates(engine: BrainEngine, policy: KeepDbPolicy): Promise<string[]> {
+ const [bounds] = await engine.executeRaw<{ top: string | null }>('SELECT max(sequence)::text AS top FROM persistence_requests');
+ const floor = String(Math.max(0, Number(bounds?.top ?? 0) - CONFLICT_WINDOW_DEFAULT));
+ const prefixes = policy.keep_db.map(dir => `${likeEscape(dir.toLowerCase())}%`);
+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests r
+ WHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3
+ AND lower(r.slug) LIKE ANY($4::text[]) ORDER BY r.slug LIMIT ${CANDIDATE_LIMIT}`, [policy.source_id, floor, FILE_DRIFT_MESSAGE, prefixes]);
+ const skipped = Object.keys(await readDriftSkips(engine)).filter(key => key.startsWith(`${policy.source_id}:`)).map(key => key.slice(policy.source_id.length + 1));
+ return [...new Set([...rows.map(row => row.slug), ...skipped])].filter(slug => isKeepDbSlug(slug, policy.keep_db)).sort();
+}
+
+/**
+ * One drifted page: submitted, the capacity stop, or the reason it was skipped. It always runs as this
+ * installation's own CLI writer registration, never as whatever caller context the worker's timer inherited:
+ * the policy is the owner host's declaration, so no remote caller's grant applies to it or is widened by it.
+ */
+async function reconcileWithDatabase(engine: BrainEngine, sourceId: string, slug: string, admission: KeepDbAdmission): Promise<string> {
+ return withVerifiedLocalRegistration(engine, await readLocalWriter(engine, 'cli'), async writer => {
+ const live = await liveFileDrift(engine, sourceId, slug);
+ if (live.still_present !== true) return live.still_present === false ? 'no_drift' : live.reason;
+ let page;
+ try { page = await prepareDriftPage(engine, sourceId, slug, 'database', new Date().toISOString()); }
+ catch (error) { if (error instanceof OperationError) return error.code; throw error; }
+ const h = digest(['keep-db-policy-v1', sourceId, slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash]);
+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+ if (await getWriteRequest(engine, writer.principal, requestId)) return 'already_submitted';
+ if (await admission(engine)) return 'capacity';
+ try {
+ await runReconcileApply(engine, { source_id: sourceId, slug, preview: page.preview, request_id: requestId });
+ } catch (error) {
+ if (acceptedPendingReceipt(error)) return 'submitted';
+ if (!(error instanceof OperationError)) throw error;
+ return await getWriteRequest(engine, writer.principal, requestId) ? 'submitted' : error.code;
+ }
+ return 'submitted';
+ });
+}
+
+/**
+ * One rate-limited pass of the keep_db policy over `sourceIds` (default: every active source) for the owner host
+ * `hostId`. Sources this host does not own, or that declare no policy, are skipped without a read of their pages.
+ */
+export async function runKeepDbPolicy(engine: BrainEngine, opts: { hostId: string; sourceIds?: string[]; limit?: number; admission?: KeepDbAdmission }): Promise<KeepDbRun> {
+ const limit = opts.limit ?? KEEP_DB_BATCH;
+ const run: KeepDbRun = { submitted: 0, skipped_by_reason: {}, sources: [] };
+ const skip = (reason: string) => { run.skipped_by_reason[reason] = (run.skipped_by_reason[reason] ?? 0) + 1; };
+ const sourceIds = opts.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ for (const sourceId of sourceIds) {
+ let policy: KeepDbPolicy | null;
+ try { policy = await readKeepDbPolicy(engine, sourceId, opts.hostId); } catch { skip('storage_config_error'); continue; }
+ if (!policy) continue;
+ const entry = { ...policy, submitted: 0 };
+ run.sources.push(entry);
+ for (const slug of await candidates(engine, policy)) {
+ if (run.submitted >= limit) { run.stopped = 'rate_limit'; return run; }
+ let outcome: string;
+ try { outcome = await reconcileWithDatabase(engine, sourceId, slug, opts.admission ?? headroom); }
+ catch (error) { if (!(error instanceof OperationError)) throw error; outcome = error.code; }
+ if (outcome === 'capacity') { run.stopped = 'capacity'; return run; }
+ if (outcome !== 'submitted') { skip(outcome); continue; }
+ run.submitted++;
+ entry.submitted++;
+ }
+ }
+ return run;
+}
diff --git a/test/e2e/file-drift-bulk-reconcile-postgres.test.ts b/test/e2e/file-drift-bulk-reconcile-postgres.test.ts
new file mode 100644
index 0000000000..d3c8626d54
--- /dev/null
+++ b/test/e2e/file-drift-bulk-reconcile-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../file-drift-bulk-reconcile.test.ts'));
diff --git a/test/file-drift-bulk-reconcile.test.ts b/test/file-drift-bulk-reconcile.test.ts
new file mode 100644
index 0000000000..a6be209ed3
--- /dev/null
+++ b/test/file-drift-bulk-reconcile.test.ts
@@ -0,0 +1,271 @@
+/**
+ * #6696 PR C, C7: bulk file-drift reconcile.
+ *
+ * `gbrain repair file-drift` takes repeatable `--only` / `--skip` globs over
+ * the canonical file path, like the other kinds' `--only` (`*` within a
+ * segment, `**` across segments, an exact path matches itself), bound into the preview hash and
+ * carried through the printed apply command, so executing that exact command
+ * applies exactly the selected pages. `--keep` is refused on file-drift with a
+ * pointer at `--prefer database`. An opt-in `storage.keep_db` list in
+ * gbrain.yml lets the trusted local maintenance worker on the canonical owner
+ * host reconcile drifted pages under those prefixes with the database copy, one
+ * rate-limited request per page; doctor `maintenance_write_drift` echoes the
+ * policy, how many drifted pages it matches and their receipt cost.
+ *
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set
+ * (test/e2e/file-drift-bulk-reconcile-postgres.test.ts).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, 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 type { OperationContext } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { DRIFT_SKIPS_KEY, liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';
+import { existingLocalHostId } from '../src/core/persistence/identity.ts';
+import { argvFromCommand } from '../src/core/agent-output.ts';
+import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { maintenanceWriteDriftCheck } from '../src/commands/doctor/checks/maintenance-drift.ts';
+import { __resetMissingStorageWarning, loadStorageConfig } from '../src/core/storage-config.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const CONCEPTS = ['concepts/alpha-example', 'concepts/beta-example', 'concepts/gamma-example'];
+const PERSON = 'people/alice-example';
+
+describe('C7 file-drift argument rules', () => {
+ test('--only and --skip are repeatable file path globs on file-drift', () => {
+ const parsed = parseRepairArgs(['file-drift', '--source', 'default', '--all-drifted', '--only', 'concepts/**', '--only', 'ideas/*',
+ '--skip', 'concepts/archive/**', '--prefer', 'database']);
+ expect(parsed).toMatchObject({ kind: 'file-drift', allDrifted: true, prefer: 'database', only: ['concepts/**', 'ideas/*'], skip: ['concepts/archive/**'] });
+ });
+ test('--keep on file-drift is refused with a pointer at --prefer database, wherever it appears', () => {
+ for (const args of [['file-drift', '--source', 'default', '--all-drifted', '--keep', 'db'], ['--keep', 'prior', 'file-drift', '--slug', 'notes/a'],
+ ['file-drift', '--keep=disk', '--slug', 'notes/a', '--apply', '--expect', 'abc']]) {
+ let error: { code?: string; message?: string; suggestion?: string; fix?: { argv?: string[] } } | undefined;
+ try { parseRepairArgs(args); } catch (caught) { error = caught as never; }
+ expect(error?.code).toBe('invalid_params');
+ expect(error?.message).toContain('--keep');
+ expect(error?.suggestion).toContain('--prefer database');
+ expect(error?.fix?.argv).toContain('--prefer');
+ expect(error?.fix?.argv).not.toContain('--keep');
+ expect(error?.fix?.argv).not.toContain('--apply');
+ }
+ });
+ test('stuck-recovery keeps validating --keep values', () => {
+ expect(() => parseRepairArgs(['stuck-recovery', '--keep', 'db'])).toThrow('--keep must be prior or disk');
+ expect(parseRepairArgs(['stuck-recovery', '--keep', 'disk']).keep).toBe('disk');
+ });
+});
+
+describe('C7 doctor on a fresh keyless PGLite brain', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+ test('maintenance_write_drift stays ok and echoes no keep_db policy', async () => {
+ const check = await maintenanceWriteDriftCheck(engine);
+ expect(check.status).toBe('ok');
+ expect(check.details).not.toHaveProperty('keep_db_policy');
+ });
+});
+
+describe('C7 storage.keep_db in gbrain.yml', () => {
+ test('keep_db is a declared prefix list, normalized like the tiers, and an unknown storage key warns', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c7-yml-'));
+ const warnings: string[] = [];
+ const original = console.warn;
+ console.warn = (...args: unknown[]) => { warnings.push(args.join(' ')); };
+ try {
+ __resetMissingStorageWarning();
+ writeFileSync(join(dir, 'gbrain.yml'), 'storage:\n db_tracked:\n - people/\n keep_db:\n - concepts\n - ideas/\n kep_db:\n - extracts/\n');
+ expect(loadStorageConfig(dir)).toEqual({ db_tracked: ['people/'], db_only: [], keep_db: ['concepts/', 'ideas/'] });
+ expect(warnings.some(line => line.includes("'kep_db'") && line.includes('keep_db'))).toBe(true);
+ __resetMissingStorageWarning();
+ warnings.length = 0;
+ writeFileSync(join(dir, 'gbrain.yml'), 'storage:\n keep_db:\n - concepts/\n');
+ expect(loadStorageConfig(dir)).toEqual({ db_tracked: [], db_only: [], keep_db: ['concepts/'] });
+ expect(warnings.filter(line => line.includes('no storage configuration'))).toEqual([]);
+ } finally {
+ console.warn = original;
+ __resetMissingStorageWarning();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+for (const backend of testBackends()) describe(`C7 bulk file-drift reconcile (${backend})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-c7-db-'));
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (backend === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({ database_path: dataDir }); await pglite.initSchema(); engine = pglite;
+ } else {
+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engine = pg.engine; closePostgres = pg.close;
+ }
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ if (closePostgres) await closePostgres(); else await engine.disconnect();
+ resetGateway(); rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ async function fixture(run: (input: { root: string; sourceId: string; ctx: OperationContext }) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-c7-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = `c7-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ await run({ root, sourceId, ctx });
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.unsetConfig(DRIFT_SKIPS_KEY);
+ await engine.unsetConfig('persistence.limits.principal_lifetime_ids');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ const put = (ctx: OperationContext, slug: string, content: string) =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });
+ const drift = (root: string, slug: string, edit: (text: string) => string) => {
+ const file = join(root, `${slug}.md`);
+ writeFileSync(file, edit(readFileSync(file, 'utf8')));
+ };
+ /** A caller write refused source_changed: one conflict receipt for the slug. */
+ const refusedWrite = async (ctx: OperationContext, slug: string) => {
+ const expected_revision = (await engine.readPageSnapshot(slug, { sourceId: ctx.sourceId! }))!.revision;
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: '---\ntype: note\ntitle: Refused\n---\nRefused.\n', expected_revision, request_id: randomUUID() } })
+ .then(() => { throw new Error(`write to ${slug} committed`); }, (error: { code?: string }) => expect(error.code).toBe('source_changed'));
+ };
+ const requests = async (sourceId: string) => Number((await engine.executeRaw<{ n: number }>(
+ 'SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [sourceId]))[0].n);
+ const stillDrifted = async (sourceId: string, slugs: string[]) => {
+ const drifted: string[] = [];
+ for (const slug of slugs) if ((await liveFileDrift(engine, sourceId, slug)).still_present === true) drifted.push(slug);
+ return drifted;
+ };
+ /** Three concepts drifted by an appended line, one person rewritten (another drift class); each with a conflict receipt. */
+ async function driftedPages(root: string, ctx: OperationContext): Promise<void> {
+ for (const slug of CONCEPTS) await put(ctx, slug, `---\ntype: concept\ntitle: ${slug.slice(9)}\n---\nStored ${slug}.\n`);
+ await put(ctx, PERSON, '---\ntype: person\ntitle: Alice Example\n---\nOriginal sentence.\n');
+ for (const slug of CONCEPTS) drift(root, slug, text => `${text}\nA line added in the file only.\n`);
+ drift(root, PERSON, text => text.replace('Original sentence.', 'A different sentence.'));
+ for (const slug of [...CONCEPTS, PERSON]) await refusedWrite(ctx, slug);
+ expect(await stillDrifted(ctx.sourceId!, [...CONCEPTS, PERSON])).toEqual([...CONCEPTS, PERSON]);
+ }
+ async function json(args: string[]): Promise<{ results: Array<Record<string, unknown>> }> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...values: unknown[]) => { lines.push(values.join(' ')); };
+ try { await runRepairCommand(engine, [...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n'));
+ }
+
+ test('--all-drifted --only concepts/** previews 3 of 4 drifted pages, and executing the exact returned command applies exactly those 3', () => fixture(async ({ root, sourceId, ctx }) => {
+ await driftedPages(root, ctx);
+ const preview = (await json(['file-drift', '--source', sourceId, '--all-drifted', '--only', 'concepts/**', '--prefer', 'database'])).results[0]!;
+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 3 });
+ expect(preview.sample).toEqual(CONCEPTS.map(slug => `${sourceId}:${slug}`));
+ const command = String(preview.apply_command);
+ expect(command).toContain("--only 'concepts/**'");
+ expect(command).toContain(`--expect ${preview.preview_hash}`);
+ const argv = argvFromCommand(command)!;
+ expect(argv.slice(0, 2)).toEqual(['gbrain', 'repair']);
+ const before = await requests(sourceId);
+ const applied = (await json(argv.slice(2))).results[0]!;
+ expect(applied).toMatchObject({ mode: 'apply', applied: 3, complete: true, outcomes: { repaired: 3 } });
+ expect(await requests(sourceId)).toBe(before + 3);
+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([PERSON]);
+ expect((await engine.getPage(CONCEPTS[0]!, { sourceId }))!.compiled_truth).toBe(`Stored ${CONCEPTS[0]}.`);
+ }), 240_000);
+
+ test('the globs are bound into the preview hash: --skip narrows the set, and an apply under other globs refuses preview_changed', () => fixture(async ({ root, sourceId, ctx }) => {
+ await driftedPages(root, ctx);
+ const scope = await resolveRepairScope(engine, sourceId);
+ const runner = await repairRunner(engine, { apply: false, logger });
+ const mixed = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database' }).then(() => null, error => error);
+ expect(mixed).toMatchObject({ code: 'invalid_params' });
+ const all = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['concepts/*'] });
+ const skipped = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database',
+ only: ['concepts/*'], skip: ['concepts/beta-*'] });
+ expect(all.affected).toBe(3);
+ expect(skipped.affected).toBe(2);
+ expect(skipped.sample).toEqual([`${sourceId}:${CONCEPTS[0]}`, `${sourceId}:${CONCEPTS[2]}`]);
+ expect(skipped.preview_hash).not.toBe(all.preview_hash);
+ expect(skipped.apply_command).toContain("--skip 'concepts/beta-*'");
+ const other = await (await repairRunner(engine, { apply: true, logger })).run('file-drift', scope,
+ { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['concepts/*'], expect: skipped.preview_hash })
+ .then(() => null, error => error);
+ expect(other).toMatchObject({ code: 'preview_changed' });
+ const bySlug = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: [CONCEPTS[0]!] });
+ expect(bySlug).toMatchObject({ affected: 0, residuals: { not_selected: 4 } });
+ const exact = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, slugs: [CONCEPTS[0]!, PERSON], prefer: 'database',
+ only: [`${CONCEPTS[0]}.md`] });
+ expect(exact).toMatchObject({ affected: 1, sample: [`${sourceId}:${CONCEPTS[0]}`], residuals: { not_selected: 1 } });
+ const bad = await runner.run('file-drift', scope, { explicit: true, sourceFlag: sourceId, allDrifted: true, prefer: 'database', only: ['../concepts/*'] })
+ .then(() => null, error => error);
+ expect(bad).toMatchObject({ code: 'invalid_params' });
+ }), 240_000);
+
+ test('storage.keep_db: the owner host submits one rate-limited reconcile per drifted page under the prefixes; elsewhere and for callers nothing changes', () => fixture(async ({ root, sourceId, ctx }) => {
+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n keep_db:\n - concepts/\n');
+ await driftedPages(root, ctx);
+ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);
+ expect(doctor).toMatchObject({ status: 'warn', details: { count: 4, keep_db_policy: [{ source_id: sourceId, keep_db: ['concepts/'], matched: 3,
+ receipt_cost: { lifetime_ids: 3, receipt_bytes: 3 * 16_384 } }] } });
+ expect(doctor.message).toContain('storage.keep_db');
+
+ const { runKeepDbPolicy } = await import('../src/core/repair/keep-db-policy.ts');
+ const ownerHost = () => existingLocalHostId()!;
+ const before = await requests(sourceId);
+ const elsewhere = await runKeepDbPolicy(engine, { hostId: randomUUID(), sourceIds: [sourceId] });
+ expect(elsewhere.submitted).toBe(0);
+ expect(await requests(sourceId)).toBe(before);
+
+ const ids = (await engine.executeRaw<{ lifetime_ids: string }>("SELECT lifetime_ids::text FROM persistence_counters WHERE key LIKE 'principal:%' ORDER BY lifetime_ids DESC LIMIT 1"))[0]!;
+ await engine.setConfig('persistence.limits.principal_lifetime_ids', ids.lifetime_ids);
+ const full = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId] });
+ expect(full).toMatchObject({ submitted: 0, stopped: 'capacity' });
+ expect(await requests(sourceId)).toBe(before);
+ await engine.unsetConfig('persistence.limits.principal_lifetime_ids');
+
+ const first = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId], limit: 2 });
+ expect(first).toMatchObject({ submitted: 2, stopped: 'rate_limit' });
+ expect(await requests(sourceId)).toBe(before + 2);
+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([CONCEPTS[2]!, PERSON]);
+ const second = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId], limit: 2 });
+ expect(second.submitted).toBe(1);
+ expect(await stillDrifted(sourceId, [...CONCEPTS, PERSON])).toEqual([PERSON]);
+ expect(readFileSync(join(root, `${CONCEPTS[0]}.md`), 'utf8')).not.toContain('A line added in the file only.');
+ const third = await runKeepDbPolicy(engine, { hostId: ownerHost(), sourceIds: [sourceId] });
+ expect(third.submitted).toBe(0);
+ expect(await requests(sourceId)).toBe(before + 3);
+ const reconciles = await engine.executeRaw<{ slug: string; state: string }>(
+ "SELECT slug, state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='canonical_reconcile' ORDER BY slug", [sourceId]);
+ expect(reconciles).toEqual(CONCEPTS.map(slug => ({ slug, state: 'committed' })));
+ await refusedWrite(ctx, PERSON);
+ }), 240_000);
+});