Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): unbound_source counts only pages with no recorded origin (#6536)

time-attackf7800d608219
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 5f8907a79b..bb313f35d0 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -11,7 +11,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).
- `src/commands/doctor/checks/persistence-requests.ts` — wave checks (OPS, registered in `wave-checks.ts`); `persistence_terminal_failures` (#6650) is in [Managed sync bookkeeping](managed-sync-bookkeeping.md). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. `persistence_write_stall` (#6176, host-only) reads running requests and warns when one has held its claim longer than `persistence.max_claim_ms` (`claim-phase.ts`; an owner that predates phase recording falls back to the request's age on the database clock), naming the stuck phase, the root, the claim age, the queued writes behind it and whether the request resumes on its own, with `gbrain sources writer status --source <id> --json` as the fix. `persistence_session_timeouts` (#6278, host-only) reads `SHOW statement_timeout` through the configured URL and warns `session_timeouts_not_applied` when it is `0` while `resolveSessionTimeouts()` configured one (a transaction-mode pooler dropped the startup parameter), naming the role-level fix. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`, `test/persistence-write-stall.test.ts`, `test/persistence-session-timeouts-check.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
-- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
+- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` and no recorded origin (blank `source_path` and `source_uri`) per source, using `databaseOnlyPageSql` from `persistence/unbound-pages.ts`, the SQL form of the `isDatabaseOnlyPage` predicate persistence uses (#6536; parity pinned by `test/unbound-source-6536.test.ts`). A managed sync that records a page's origin, and a reconcile apply, clear the marker. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/unbound-source-6536.test.ts`.
- `src/commands/doctor/checks/revision-backfill.ts` — `revision_backfill` (#5216, META, registered before `search_mode`): reads `readRevisionBackfillStatus` (column state, pages still without `knowledge_revision`, failed rows still pending with their page). ok when the column is NOT NULL; warn with the pending count and `gbrain apply-migrations --force-schema` as `fix` while any row is resumable (or only the NOT NULL step remains); failed rows are listed by page id, `source:slug`, attempt and error, and when only rows with spent attempts remain the `fix` is the read-only `gbrain repair orphan-children` preview. Tests: `test/doctor-revision-backfill.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/conversation-outcomes.ts` — `conversation_label_facts` (wave check, host-only, resolution `repair`): bounded count (capped at 1000, reported as at least N) of the default set `gbrain repair conversation-labels` would retire; names the preview, never the apply. `conversation_outcomes_stale` (wave check, host-only, resolution `operator`): counts active conversation extraction outcomes stamped with an older `extractor_version` than `CONVERSATION_EXTRACTOR_VERSION` (outcomes are never reopened automatically) and names the `--force --dry-run` re-extract preview; outcomes older than the stamp are counted as `unstamped` and never warn. Bounded scan of the extractor rows, capped at 5000 (reported as at least N). Read-only.
diff --git a/src/commands/doctor/checks/unbound-source.ts b/src/commands/doctor/checks/unbound-source.ts
index 6823f45191..b7ed5e1fbb 100644
--- a/src/commands/doctor/checks/unbound-source.ts
+++ b/src/commands/doctor/checks/unbound-source.ts
@@ -1,10 +1,12 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { unboundBindCommand } from '../../../core/persistence/unbound-source.ts';
+import { databaseOnlyPageSql } from '../../../core/persistence/unbound-pages.ts';
/**
* #5254: pages written database-only while their filesystem source had no
- * canonical owner (`persistence.unbound_write=database_only`). While the source
+ * canonical owner (`persistence.unbound_write=database_only`): the marker with
+ * no recorded origin, the same predicate persistence uses (#6536). While the source
* stays unbound that is the chosen mode, so the count reports ok with the bind
* command; once the source is bound those pages sit outside its canonical
* files and are never materialized automatically, so it warns.
@@ -17,7 +19,7 @@ export async function checkUnboundSource(engine: BrainEngine): Promise<Check> {
WHERE b.source_id=p.source_id) AS bound,
COALESCE((SELECT s.local_path FROM sources s WHERE s.id=p.source_id),
CASE WHEN p.source_id='default' THEN (SELECT c.value FROM config c WHERE c.key='sync.repo_path') END) AS local_path
- FROM pages p WHERE p.database_only_reason='unbound_source' AND p.deleted_at IS NULL
+ FROM pages p WHERE ${databaseOnlyPageSql('p')} AND p.deleted_at IS NULL
GROUP BY p.source_id ORDER BY p.source_id`);
const sources = rows.map(row => ({ source_id: row.source_id, pages: row.pages, bound: row.bound }));
const total = rows.reduce((sum, row) => sum + row.pages, 0);
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index bc2fb97c0c..731d2c7183 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -158,10 +158,10 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
if (state.originSourcePath) {
await tx.executeRaw(`UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
AND source_path IS NULL`, [row.source_id, row.slug, state.originSourcePath]);
- // The page now has a canonical origin: drop the #5254 database-only classification.
- await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
- AND database_only_reason='unbound_source' AND source_path IS NOT NULL`, [row.source_id, row.slug]);
}
+ // The page has a canonical origin (adopted above, or already recorded, #6536): drop the #5254 database-only classification.
+ await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
+ AND database_only_reason='unbound_source' AND source_path IS NOT NULL`, [row.source_id, row.slug]);
if (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });
const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 24e00fb229..a18456faee 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -683,6 +683,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
const installed = await applied.apply(tx, renamed ? undefined : preimage);
// Hash no-ops still repair a missing physical origin under the same guard (a page write records it itself).
if (applied.noop) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ // #6536: the page now records this file as its origin, so it is no longer a #5254 database-only page.
+ await tx.executeRaw("UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'", [row.source_id, row.slug]);
// #5984: the one read of the page after its last page write (the projections
// below and the seal leave its revision unchanged): read-back check, projection
// target, seal input, receipt revision and effects.
diff --git a/src/core/persistence/unbound-pages.ts b/src/core/persistence/unbound-pages.ts
index b9a757f4cd..40f5cf85c3 100644
--- a/src/core/persistence/unbound-pages.ts
+++ b/src/core/persistence/unbound-pages.ts
@@ -19,6 +19,12 @@ export function isDatabaseOnlyPage(page: { source_path?: string | null; source_u
return page.database_only_reason === 'unbound_source' && !page.source_path?.trim() && !page.source_uri?.trim();
}
+/** `isDatabaseOnlyPage` as a SQL predicate over the `pages` row aliased `alias` (#6536: doctor counts with it). */
+export function databaseOnlyPageSql(alias: string): string {
+ const blank = (column: string) => `COALESCE(btrim(${alias}.${column}, E' \\t\\n\\r\\f\\v'), '')=''`;
+ return `${alias}.database_only_reason IS NOT DISTINCT FROM 'unbound_source' AND ${blank('source_path')} AND ${blank('source_uri')}`;
+}
+
/**
* The canonical file an import would give this slug (`<slug>.md` under the Git
* root or the source root, per the source's slug-root mode) and the
diff --git a/test/reconcile-unbound-collision.test.ts b/test/reconcile-unbound-collision.test.ts
index 559f9d730f..204f4dc585 100644
--- a/test/reconcile-unbound-collision.test.ts
+++ b/test/reconcile-unbound-collision.test.ts
@@ -199,3 +199,25 @@ test('--adopt-slug-path refuses a page that is database-only by design (a never-
}
});
}, 180_000);
+
+// #6536: a marked page whose origin was already recorded (sync recorded source_path) reconciles with origin 'recorded';
+// apply must still drop the #5254 marker, or doctor and reconcile-state keep reporting a page that has a canonical file.
+test('reconcile of a marked page with a recorded origin clears the unbound_source marker', async () => {
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ for (const engine of engines) {
+ const f = await collision(engine);
+ await engine.executeRaw("UPDATE pages SET source_path='notes/example.md' WHERE source_id=$1 AND slug=$2", [f.id, f.slug]);
+ await withVerifiedLocalRegistration(engine, f.registration, async () => {
+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });
+ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,
+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_file' })) });
+ expect(resolved.status).toBe('ready');
+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });
+ expect(receipt.state).toBe('committed');
+ const [page] = await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null }>(
+ 'SELECT source_path,database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);
+ expect(page).toEqual({ source_path: 'notes/example.md', database_only_reason: null });
+ });
+ }
+ });
+}, 180_000);
diff --git a/test/unbound-source-6536.test.ts b/test/unbound-source-6536.test.ts
new file mode 100644
index 0000000000..b9804db788
--- /dev/null
+++ b/test/unbound-source-6536.test.ts
@@ -0,0 +1,98 @@
+/**
+ * #6536: doctor `unbound_source` counted every page carrying the #5254
+ * marker, while persistence (`isDatabaseOnlyPage`) only treats a marked page
+ * with no recorded origin as database-only. A page whose canonical file sync
+ * had recorded kept warning forever. Doctor now uses the persistence
+ * predicate's SQL form, and a managed sync that records a page's origin
+ * clears the marker.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { performSync } from '../src/commands/sync.ts';
+import { checkUnboundSource } from '../src/commands/doctor/checks/unbound-source.ts';
+import { databaseOnlyPageSql, isDatabaseOnlyPage } from '../src/core/persistence/unbound-pages.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const dirs: string[] = [];
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); 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?.();
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
+});
+
+const ORIGINS: Array<{ source_path: string | null; source_uri: string | null }> = [
+ { source_path: null, source_uri: null }, { source_path: '', source_uri: '' }, { source_path: ' \t\n', source_uri: null },
+ { source_path: 'notes/a.md', source_uri: null }, { source_path: null, source_uri: 'file:///x/notes/a.md' }, { source_path: ' notes/a.md ', source_uri: ' ' },
+];
+
+for (const backend of backends) {
+ test(`${backend}: doctor counts exactly the pages isDatabaseOnlyPage matches (#6536)`, async () => {
+ const engine = engines[backends.indexOf(backend)];
+ const sourceId = `parity-${backend}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ for (const [i, origin] of ORIGINS.entries()) {
+ for (const marker of ['unbound_source', null]) {
+ const slug = `notes/p${i}-${marker ?? 'none'}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'x', timeline: '' }, { sourceId });
+ await engine.executeRaw('UPDATE pages SET database_only_reason=$3,source_path=$4,source_uri=$5 WHERE source_id=$1 AND slug=$2',
+ [sourceId, slug, marker, origin.source_path, origin.source_uri]);
+ }
+ }
+ const rows = await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null; database_only_reason: string | null; matched: boolean }>(
+ `SELECT slug,source_path,source_uri,database_only_reason,(${databaseOnlyPageSql('p')}) AS matched FROM pages p WHERE source_id=$1`, [sourceId]);
+ for (const row of rows) expect({ slug: row.slug, matched: row.matched }).toEqual({ slug: row.slug, matched: isDatabaseOnlyPage(row) });
+ const expected = rows.filter(row => isDatabaseOnlyPage(row)).length;
+ expect(expected).toBe(3);
+ const check = await checkUnboundSource(engine);
+ expect((check.details as { sources: Array<{ source_id: string; pages: number }> }).sources.find(s => s.source_id === sourceId)?.pages).toBe(expected);
+ }, 120_000);
+}
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', ...args],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+for (const backend of backends) {
+ test(`${backend}: a managed sync that records a marked page's origin clears the unbound_source marker (#6536)`, async () => {
+ const engine = engines[backends.indexOf(backend)];
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-unbound-6536-')); dirs.push(dir);
+ const root = join(dir, 'brain'); mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['init', '-q', '-b', 'main', root]);
+ const commit = (body: string) => { writeFileSync(join(root, 'notes/adopted.md'), `---\ntitle: Adopted\ntype: note\n---\n${body}\n`); git(root, 'add', '.'); git(root, 'commit', '-qm', body); };
+ commit('First.');
+ const sourceId = `synced-${backend}`;
+ 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 claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ await performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true });
+ await engine.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1 AND slug='notes/adopted'", [sourceId]);
+ commit('Second.');
+ await performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true });
+ const [page] = await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null; compiled_truth: string }>(
+ "SELECT source_path,database_only_reason,compiled_truth FROM pages WHERE source_id=$1 AND slug='notes/adopted'", [sourceId]);
+ expect(page.compiled_truth).toContain('Second.');
+ expect({ source_path: page.source_path, database_only_reason: page.database_only_reason }).toEqual({ source_path: 'notes/adopted.md', database_only_reason: null });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ });
+ }, 120_000);
+}