Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): owner-aware text_projection_readiness and resident projection_status IPC (#5401, E-T1)

garrytan1227af8e169e
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 497b425225..34ee3ad2ab 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -51,7 +51,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
-- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.
+- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`.
diff --git a/src/commands/doctor/checks/projection-readiness.ts b/src/commands/doctor/checks/projection-readiness.ts
index 4f24ea02ec..fe8c39a20a 100644
--- a/src/commands/doctor/checks/projection-readiness.ts
+++ b/src/commands/doctor/checks/projection-readiness.ts
@@ -1,9 +1,20 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { PageReadScope } from '../../../core/types.ts';
import { probeProjectionReadiness } from '../../../core/search/projection-readiness.ts';
+import type { PersistenceProjectionStatus } from '../../../core/persistence/ipc.ts';
import type { Check } from '../../doctor.ts';
+import type { DoctorContext, DoctorEntry } from '../context.ts';
-export async function checkProjectionReadiness(engine: BrainEngine, scope: PageReadScope = {}): Promise<Check> {
+const DOCS = 'docs/guides/repair.md#projection-drain';
+const UNCHANGED = 'No repair or embedding was started by this check.';
+const CODE_REPAIR = 'For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path.';
+
+/**
+ * #5401: `resident` is true when the caller runs inside a PGLite resident (the
+ * run_doctor operation on a serving process), where the drain command would
+ * refuse; the resident drains the backlog itself.
+ */
+export async function checkProjectionReadiness(engine: BrainEngine, scope: PageReadScope = {}, opts: { resident?: boolean } = {}): Promise<Check> {
const readiness = await probeProjectionReadiness(engine, scope);
return {
name: 'text_projection_readiness',
@@ -11,8 +22,70 @@ export async function checkProjectionReadiness(engine: BrainEngine, scope: PageR
message: readiness.status === 'ready'
? 'Visible text projections match their canonical revisions.'
: readiness.status === 'projection_pending'
- ? 'Visible pages have missing or stale text projections; search and code results may be incomplete. Restart the upgraded resident `gbrain serve` to drain queued Markdown and code rebuilds. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.'
+ ? `Visible pages have missing or stale text projections; search and code results may be incomplete. ${opts.resident
+ ? 'The resident gbrain process that holds this PGLite brain is rebuilding queued Markdown and code projections (up to 100 pages per pass, fewer while writes wait). On the brain host, `gbrain doctor` shows the pending count and how to drain faster.'
+ : 'Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres.'} ${CODE_REPAIR} ${UNCHANGED}`
: 'Text projection readiness is unknown because its read-only probe failed; index completeness could not be verified.',
details: { readiness: readiness.status, ready: readiness.ready },
};
}
+
+/** The doctor text when a PGLite resident holds the datastore, from its projection_status reply (null: it gave none). */
+export function residentProjectionReadiness(pid: number | undefined, status: PersistenceProjectionStatus | null, steps: string): Pick<Check, 'status' | 'message' | 'details'> {
+ const owner = `The resident gbrain process${pid ? ` (pid ${pid})` : ''} holds this PGLite brain`;
+ if (!status) {
+ return {
+ status: 'warn',
+ message: `${owner} and did not report its projection backlog, so it may predate the faster projection drain. Restart it on the upgraded gbrain so it drains up to 100 pages per pass. ${steps}`,
+ details: { readiness: 'unknown', ready: false, owner_pid: pid ?? null, docs: DOCS },
+ };
+ }
+ const details = { readiness: status.pending ? 'projection_pending' : 'ready', ready: status.pending === 0, owner_pid: pid ?? null, ...status, docs: DOCS };
+ if (status.pending === 0) return { status: 'ok', message: `${owner} and reports no queued text projections.`, details };
+ const age = status.oldest_age_seconds === null ? '' : `; the oldest was queued ${status.oldest_age_seconds}s ago`;
+ const failed = status.failed ? `; ${status.failed} last failed and are retried after 30 seconds` : '';
+ return {
+ status: 'warn',
+ message: `${owner} and is draining ${status.pending} queued text projections${age}${failed}. Search and code results may be incomplete until it finishes; it rebuilds up to 100 pages per pass, fewer while writes wait. Re-run \`gbrain doctor\` to watch the count. ${steps} ${UNCHANGED}`,
+ details,
+ };
+}
+
+async function runProjectionResident(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ if (ctx.engine || ctx.fastMode) return checks;
+ const { loadConfig } = await import('../../../core/config.ts');
+ const { getCliOptions } = await import('../../../core/cli-options.ts');
+ const { resolveBrainId } = await import('../../../core/brain-resolver.ts');
+ const { loadMounts } = await import('../../../core/brain-registry.ts');
+ const { persistenceConfigForBrain } = await import('../../../core/persistence/local-client.ts');
+ const { inspectLockHolder } = await import('../../../core/pglite-lock.ts');
+ const { persistenceSocketPathForConfig, requestPersistenceProjectionStatus } = await import('../../../core/persistence/ipc.ts');
+ const { residentDrainSteps } = await import('../../projections.ts');
+ let config: ReturnType<typeof persistenceConfigForBrain>;
+ try {
+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());
+ config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
+ } catch { return checks; }
+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url) return checks;
+ const holder = inspectLockHolder(config.database_path);
+ if (!holder.held) return checks;
+ const socketPath = persistenceSocketPathForConfig(config);
+ let status: PersistenceProjectionStatus | null = null;
+ if (socketPath) {
+ try { status = await requestPersistenceProjectionStatus(socketPath); } catch { /* an older resident, or none listening */ }
+ }
+ checks.push({ name: 'text_projection_readiness', ...residentProjectionReadiness(holder.pid, status, residentDrainSteps(holder.pid)) });
+ return checks;
+}
+
+/**
+ * Filesystem-lane entry (#5401, E-T1): when the engine did not open because a
+ * PGLite resident holds the datastore, ask that resident for its projection
+ * backlog over the read-only persistence IPC op.
+ */
+export const projectionResidentEntry: DoctorEntry = {
+ name: 'text_projection_readiness',
+ emits: ['text_projection_readiness'],
+ run: runProjectionResident,
+};
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 8367b16551..d682e2240e 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -452,7 +452,7 @@ export async function doctorReportRemote(
checks.push(await checkProjectionReadiness(engine, {
sourceIds: opts.sourceIds,
excludePrivate: await resolveExcludePrivatePages(engine, opts.remote),
- }));
+ }, { resident: engine.kind === 'pglite' && opts.remote === true }));
// issue #1777 — hidden_by_search_policy: chunked pages withheld from default
// search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index a874d27d24..6a018ec7d7 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -66,8 +66,17 @@ export interface PersistenceIpcAdminRequest {
registration: PersistenceIpcRegistration;
}
+/** #5401: the resident's queued text-projection backlog. Counts only, never identifiers. */
+export interface PersistenceProjectionStatus {
+ pending: number;
+ failed: number;
+ oldest_age_seconds: number | null;
+}
+
export interface PersistenceIpcProvider {
brainId: string;
+ /** Read-only and credential-free, like capabilities: serves doctor while this process holds the datastore. */
+ projectionStatus?(): Promise<PersistenceProjectionStatus>;
/** Authenticate registration against the DB, reconstruct context, then dispatch through the registry. */
dispatch(request: PersistenceIpcRequest): Promise<unknown>;
/** Verify the live CLI registration again; never accept stdio or a wire trust assertion. */
@@ -201,6 +210,11 @@ export async function startPersistenceIpcServer(
} satisfies PersistenceIpcCapabilities }));
return;
}
+ if (record(request) && exactKeys(request, ['version', 'kind']) && request.version === 1 && request.kind === 'projection_status') {
+ if (!provider.projectionStatus) throw new OperationError('unavailable', 'This owner does not report projection status.');
+ socket.end(responseFrame({ version: 1, ok: true, result: await provider.projectionStatus() }));
+ return;
+ }
if (!operationRequest(request) && !administrationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
if (request.brain_id !== provider.brainId) throw new OperationError('source_changed', 'The persistence listener now serves a different brain.');
if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw new OperationError('queue_capacity', 'The persistence listener is at capacity; retry this request ID.');
@@ -342,6 +356,17 @@ export async function requestPersistenceCapabilities(socketPath: string, timeout
return value as unknown as PersistenceIpcCapabilities;
}
+function count(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
+}
+
+export async function requestPersistenceProjectionStatus(socketPath: string, timeoutMs = 2_000): Promise<PersistenceProjectionStatus> {
+ const value = await exchange(socketPath, { version: 1, kind: 'projection_status' }, timeoutMs);
+ if (!record(value) || !count(value.pending) || !count(value.failed)
+ || !(value.oldest_age_seconds === null || count(value.oldest_age_seconds))) throw new PersistenceIpcTransportError(false);
+ return { pending: value.pending, failed: value.failed, oldest_age_seconds: value.oldest_age_seconds };
+}
+
export async function requestPersistenceOperation(socketPath: string, request: PersistenceIpcRequest, timeoutMs = 30_000): Promise<unknown> {
if (!operationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
return exchange(socketPath, request, timeoutMs,
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index c169b4e7de..e6ed9e9650 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -10,6 +10,7 @@ import { startPersistenceConsumer, assertPersistenceAccepting } from './service.
import { isWriteErrorCode, isWriteReceipt } from './types.ts';
import type { PersistenceIpcProvider } from './ipc.ts';
import { runPersistenceAdministration } from './administration.ts';
+import { projectionBacklog } from '../page-state/projections.ts';
/** Resident lifecycle owns the consumer; each connection proves its own durable registration. */
export async function createPersistenceIpcProvider(engine: BrainEngine, config: GBrainConfig): Promise<PersistenceIpcProvider> {
@@ -22,7 +23,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
}
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
startPersistenceConsumer(engine, config);
- return { brainId: brain.brain_id, dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {
+ return { brainId: brain.brain_id, projectionStatus: () => projectionBacklog(engine), dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {
assertPersistenceAccepting(engine);
if (request.brain_id !== brain.brain_id) throw new OperationError('permission_denied', 'This registration belongs to a different brain.');
const operation = operations.find(op => op.name === request.operation);
diff --git a/test/projection-resident-doctor.test.ts b/test/projection-resident-doctor.test.ts
new file mode 100644
index 0000000000..da3fb4858b
--- /dev/null
+++ b/test/projection-resident-doctor.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #5401 E-T1: while a PGLite resident holds the datastore, doctor cannot open
+ * the engine; the resident answers a read-only projection_status IPC op with
+ * counts only, and doctor's filesystem-lane entry reports the backlog from it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { projectionBacklog } from '../src/core/page-state/projections.ts';
+import {
+ persistenceSocketPathForConfig, requestPersistenceProjectionStatus, startPersistenceIpcServer, type PersistenceIpcProvider,
+} from '../src/core/persistence/ipc.ts';
+import { projectionResidentEntry } from '../src/commands/doctor/checks/projection-readiness.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-projection-resident-'));
+const config = { engine: 'pglite' as const, database_path: join(home, 'brain.pglite') };
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect(config); await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('resident-example','resident-example')");
+ for (const slug of ['notes/a', 'notes/b', 'notes/c']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example ${slug}.` }, { sourceId: 'resident-example' });
+ }
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='resident-example'");
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id='resident-example'
+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision`);
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+}, 120_000);
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const provider = (status?: PersistenceIpcProvider['projectionStatus']): PersistenceIpcProvider => ({
+ brainId: randomUUID(), dispatch: async () => { throw new Error('not used'); }, ...(status ? { projectionStatus: status } : {}),
+});
+const doctorContext = (overrides: Partial<DoctorContext> = {}) => ({ engine: null, fastMode: false, ...overrides }) as DoctorContext;
+const runEntry = (ctx: DoctorContext) => withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
+ async () => await projectionResidentEntry.run(ctx) as Check[]);
+
+test('the resident answers projection_status with counts only; an owner without it refuses', async () => {
+ const socket = persistenceSocketPathForConfig(config)!;
+ const server = (await startPersistenceIpcServer(socket, provider(() => projectionBacklog(engine))))!;
+ try {
+ const status = await requestPersistenceProjectionStatus(socket);
+ expect(status).toMatchObject({ pending: 3, failed: 0 });
+ expect(Object.keys(status).sort()).toEqual(['failed', 'oldest_age_seconds', 'pending']);
+ expect(status.oldest_age_seconds).toBeGreaterThanOrEqual(0);
+ } finally { server.close(); }
+ const old = (await startPersistenceIpcServer(socket, provider()))!;
+ try {
+ await expect(requestPersistenceProjectionStatus(socket)).rejects.toMatchObject({ code: 'unavailable' });
+ } finally { old.close(); }
+});
+
+test('doctor reports the resident backlog, its pid and the stop-drain-restart path while the resident holds the brain', async () => {
+ const socket = persistenceSocketPathForConfig(config)!;
+ const server = (await startPersistenceIpcServer(socket, provider(() => projectionBacklog(engine))))!;
+ let draining: Check[];
+ try { draining = await runEntry(doctorContext()); } finally { server.close(); }
+ expect(draining).toHaveLength(1);
+ expect(draining[0]).toMatchObject({ name: 'text_projection_readiness', status: 'warn',
+ details: { readiness: 'projection_pending', ready: false, pending: 3, failed: 0, owner_pid: process.pid } });
+ expect(draining[0].message).toContain(`(pid ${process.pid}) holds this PGLite brain and is draining 3 queued text projections`);
+ expect(draining[0].message).toContain('systemctl --user stop gbrain-serve.service && gbrain projections drain');
+ expect(draining[0].message).toContain(`kill ${process.pid}`);
+
+ const silent = await runEntry(doctorContext());
+ expect(silent[0]).toMatchObject({ name: 'text_projection_readiness', status: 'warn', details: { readiness: 'unknown' } });
+ expect(silent[0].message).toContain('may predate the faster projection drain');
+
+ expect(await runEntry(doctorContext({ engine: engine as never }))).toEqual([]);
+ expect(await runEntry(doctorContext({ fastMode: true }))).toEqual([]);
+}, 60_000);