Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): timeline_history keeps its scan cursor between runs so large brains reach ok (#5821)

garrytane9e70b8408c3
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 3841081674..27b7d4021f 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -28,7 +28,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 48 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig`; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).
+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig`; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).
- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0cdfbe16e5..0bc562de15 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -314,6 +314,17 @@ Do not delete binding rows by hand: the repair rechecks, in the same
statement, that the binding is still orphaned and that no pending write
request uses it.
+### Timeline history scan coverage
+
+Doctor's `timeline_history` check classifies at most 2,000 pages or 10
+seconds of work per run. On a larger brain each run continues where the last
+one stopped (the cursor is kept in the config row
+`doctor.timeline_history.scan:<sources>`), so a few consecutive `gbrain doctor`
+runs finish a full pass and report exact counts. While the next pass is in
+progress, a clean finished pass keeps the check `ok` until a newer timeline row
+is written. A run that has neither says `scan incomplete` and is a lower bound;
+`gbrain repair timeline` (preview) counts the whole brain in one go.
+
### Stale atoms
`gbrain repair stale-atoms` (explicit-only, #5770) retires atoms that drifted
diff --git a/src/commands/doctor/checks/timeline-history.ts b/src/commands/doctor/checks/timeline-history.ts
index bbad108925..ee00150afe 100644
--- a/src/commands/doctor/checks/timeline-history.ts
+++ b/src/commands/doctor/checks/timeline-history.ts
@@ -5,8 +5,12 @@
* kept by every writer and reported as informational.
*
* Bounded: pages carrying non-event timeline rows are classified in id order
- * up to PAGE_CAP pages or TIME_BUDGET_MS. A truncated scan reports its counts
- * as a lower bound and is never reported as clean.
+ * up to PAGE_CAP pages or TIME_BUDGET_MS per run. A run that stops early keeps
+ * its cursor in the config row `doctor.timeline_history.scan:<scope>` (#5821),
+ * so successive doctor runs cover the whole scope; a pass that ends reports
+ * the counts of every run in it. While a later pass is in progress, a clean
+ * finished pass is trusted until a newer timeline row is written. A truncated
+ * run with neither is a lower bound and is never reported as clean.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
@@ -14,29 +18,85 @@ import { scanTimelineHistory } from '../../../core/repair/timeline.ts';
const PAGE_CAP = 2_000;
const TIME_BUDGET_MS = 10_000;
+const STATE_KEY = 'doctor.timeline_history.scan';
+
+interface PassTotals { materializable: number; unrenderable: number; affected: number; inspected: number; runs: number }
+interface ScanState extends PassTotals {
+ cursor: number;
+ /** Highest timeline row id when the pass started; rows above it may be unscanned. */
+ started_max_entry: number;
+ last?: PassTotals & { max_entry: number; completed_at: string };
+}
+
+const emptyTotals = (): PassTotals => ({ materializable: 0, unrenderable: 0, affected: 0, inspected: 0, runs: 0 });
+
+async function loadState(engine: BrainEngine, key: string): Promise<ScanState | null> {
+ try {
+ const raw = await engine.getConfig(key);
+ const state = raw ? JSON.parse(raw) as ScanState : null;
+ return state && Number.isSafeInteger(state.cursor) ? state : null;
+ } catch { return null; }
+}
+
+async function saveState(engine: BrainEngine, key: string, state: ScanState): Promise<void> {
+ try { await engine.setConfig(key, JSON.stringify(state)); } catch { /* best effort: the next run rescans from the start */ }
+}
export async function timelineHistoryCheck(engine: BrainEngine, sourceId?: string, opts: { pageCap?: number } = {}): Promise<Check> {
const name = 'timeline_history';
try {
const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE')).map(r => r.id);
- const scan = await scanTimelineHistory(engine, sources, 0, { pages: opts.pageCap ?? PAGE_CAP, deadline: Date.now() + TIME_BUDGET_MS });
- const materializable = scan.pages.reduce((n, p) => n + p.materializable, 0);
- const unrenderable = scan.pages.reduce((n, p) => n + p.unrenderable, 0);
- const count = scan.truncated ? 'lower_bound' : 'exact';
- const details = { materializable_rows: materializable, kept_unrenderable_rows: unrenderable, pages_affected: scan.pages.filter(p => p.materializable).length,
- pages_inspected: scan.inspected, count, truncated: scan.truncated, repair: 'timeline' };
- const bound = scan.truncated ? `at least ` : '';
- const coverage = scan.truncated ? ` (scan stopped after ${scan.inspected} pages; counts are a lower bound)` : '';
- if (materializable > 0) {
- return { name, status: 'warn', details, message: `${bound}${materializable} timeline row(s) on ${details.pages_affected} page(s) exist only in the database${coverage}. `
- + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (unrenderable ? `. ${unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };
+ const key = `${STATE_KEY}:${[...sources].sort().join(',')}`;
+ const [{ max_entry }] = await engine.executeRaw<{ max_entry: number | string }>('SELECT COALESCE(max(id), 0) AS max_entry FROM timeline_entries');
+ const maxEntry = Number(max_entry);
+ const prior = await loadState(engine, key);
+ const state: ScanState = prior ?? { ...emptyTotals(), cursor: 0, started_max_entry: maxEntry };
+ const scan = await scanTimelineHistory(engine, sources, state.cursor, { pages: opts.pageCap ?? PAGE_CAP, deadline: Date.now() + TIME_BUDGET_MS });
+ const segment = {
+ materializable: scan.pages.reduce((n, p) => n + p.materializable, 0),
+ unrenderable: scan.pages.reduce((n, p) => n + p.unrenderable, 0),
+ affected: scan.pages.filter(p => p.materializable).length,
+ };
+ const pass: PassTotals = {
+ materializable: state.materializable + segment.materializable,
+ unrenderable: state.unrenderable + segment.unrenderable,
+ affected: state.affected + segment.affected,
+ inspected: state.inspected + scan.inspected,
+ runs: state.runs + 1,
+ };
+ const multiRun = pass.runs > 1;
+
+ if (!scan.truncated) {
+ if (prior) {
+ await saveState(engine, key, { ...emptyTotals(), cursor: 0, started_max_entry: maxEntry,
+ last: { ...pass, max_entry: state.started_max_entry, completed_at: new Date().toISOString() } });
+ }
+ const details = { materializable_rows: pass.materializable, kept_unrenderable_rows: pass.unrenderable, pages_affected: pass.affected,
+ pages_inspected: pass.inspected, count: 'exact', truncated: false, repair: 'timeline', ...(multiRun ? { pass_runs: pass.runs } : {}) };
+ const across = multiRun ? ` (full pass across ${pass.runs} doctor runs)` : '';
+ if (pass.materializable > 0) {
+ return { name, status: 'warn', details, message: `${pass.materializable} timeline row(s) on ${pass.affected} page(s) exist only in the database${across}. `
+ + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };
+ }
+ return { name, status: 'ok', details, message: pass.unrenderable
+ ? `No materializable database-only timeline rows${across}; ${pass.unrenderable} row(s) cannot round-trip through their page and are kept as-is (informational).`
+ : `Every timeline row has a bullet in its page (${pass.inspected} page(s) inspected${multiRun ? ` across ${pass.runs} doctor runs` : ''}).` };
+ }
+
+ await saveState(engine, key, { ...state, ...pass, cursor: scan.cursor });
+ const details = { materializable_rows: pass.materializable, kept_unrenderable_rows: pass.unrenderable, pages_affected: pass.affected,
+ pages_inspected: pass.inspected, count: 'lower_bound', truncated: true, repair: 'timeline', pass_runs: pass.runs, resumes_after_page_id: scan.cursor };
+ const coverage = ` (this pass has inspected ${pass.inspected} page(s) over ${pass.runs} run(s) and resumes on the next doctor run; counts are a lower bound)`;
+ if (pass.materializable > 0) {
+ return { name, status: 'warn', details, message: `at least ${pass.materializable} timeline row(s) on ${pass.affected} page(s) exist only in the database${coverage}. `
+ + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };
}
- if (scan.truncated) {
- return { name, status: 'warn', details, message: `Timeline history scan incomplete${coverage}; run \`gbrain repair timeline\` for the full count.` };
+ const last = state.last;
+ if (last && last.materializable === 0 && maxEntry <= last.max_entry) {
+ return { name, status: 'ok', details: { ...details, last_full_pass: { pages_inspected: last.inspected, runs: last.runs, completed_at: last.completed_at } },
+ message: `No materializable database-only timeline rows: the last full pass (${last.inspected} page(s), completed ${last.completed_at}) found none and no timeline row has been written since; the next pass is in progress.` };
}
- return { name, status: 'ok', details, message: unrenderable
- ? `No materializable database-only timeline rows; ${unrenderable} row(s) cannot round-trip through their page and are kept as-is (informational).`
- : `Every timeline row has a bullet in its page (${scan.inspected} page(s) inspected).` };
+ return { name, status: 'warn', details, message: `Timeline history scan incomplete${coverage}; run \`gbrain repair timeline\` for the full count now.` };
} catch (e) {
return { name, status: 'warn', message: `timeline history check skipped: ${e instanceof Error ? e.message : String(e)}`,
details: { count: 'lower_bound', truncated: true, health: 'unknown' } };
diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.ts
index 88b801937a..79c2e37f6b 100644
--- a/src/core/repair/timeline.ts
+++ b/src/core/repair/timeline.ts
@@ -41,14 +41,14 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: string
for (const page of batch) {
if ((budget.pages !== undefined && inspected >= budget.pages) || (budget.deadline !== undefined && Date.now() > budget.deadline)) {
truncated = true;
- return { pages, inspected, truncated };
+ return { pages, inspected, truncated, cursor };
}
inspected++;
cursor = page.id;
const counts = await pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' }, await removedRowIds(engine, page));
if (counts.materializable || counts.unrenderable) pages.push({ ...page, ...counts });
}
- if (batch.length < BATCH) return { pages, inspected, truncated };
+ if (batch.length < BATCH) return { pages, inspected, truncated, cursor };
}
}
diff --git a/test/doctor-timeline-history-cursor-5821.test.ts b/test/doctor-timeline-history-cursor-5821.test.ts
new file mode 100644
index 0000000000..c2b40a75c1
--- /dev/null
+++ b/test/doctor-timeline-history-cursor-5821.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #5821: timeline_history scans a bounded number of pages per doctor run. It
+ * used to restart from the first page id every run, so a scope with more
+ * timeline pages than the cap warned "scan incomplete" forever, even with
+ * nothing to repair. The cursor now persists between runs: successive runs
+ * finish a pass, a clean pass reports ok, and rows past the cap are found.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { timelineHistoryCheck } from '../src/commands/doctor/checks/timeline-history.ts';
+
+let engine: PGLiteEngine;
+const PAGES = 5;
+const CAP = 2;
+const run = () => timelineHistoryCheck(engine, 'default', { pageCap: CAP });
+
+async function seedPage(i: number): Promise<void> {
+ const slug = `notes/timeline-${i}`;
+ await importFromContent(engine, slug, `---\ntitle: Timeline ${i}\ntype: note\n---\nBody ${i}.\n\n## Timeline\n\n- **2026-07-0${i + 1}** | Event ${i} happened\n`, { noEmbed: true });
+ await engine.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)
+ SELECT id, $2::date, '', $3, '' FROM pages WHERE slug = $1 AND source_id = 'default'`, [slug, `2026-07-0${i + 1}`, `Event ${i} happened`]);
+}
+
+async function addDatabaseOnlyRow(i: number): Promise<void> {
+ await engine.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)
+ SELECT id, '2026-08-01', 'legacy', 'A database-only event', '' FROM pages WHERE slug = $1 AND source_id = 'default'`, [`notes/timeline-${i}`]);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM timeline_entries');
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'doctor.timeline_history.scan%'");
+ for (let i = 0; i < PAGES; i++) await seedPage(i);
+});
+
+test('a clean scope larger than the cap reaches ok and stays ok while the next pass runs', async () => {
+ const first = await run();
+ expect(first.status).toBe('warn');
+ expect(first.details).toMatchObject({ truncated: true, pages_inspected: CAP });
+ const second = await run();
+ const third = await run();
+ expect(third).toMatchObject({ status: 'ok', details: { count: 'exact', truncated: false, pages_inspected: PAGES, materializable_rows: 0 } });
+ expect(second.status).toBe('warn');
+ const fourth = await run();
+ expect(fourth.status).toBe('ok');
+ expect(fourth.details).toMatchObject({ truncated: true, last_full_pass: { pages_inspected: PAGES } });
+});
+
+test('a database-only row on a page past the cap is found by a later run', async () => {
+ await addDatabaseOnlyRow(PAGES - 1);
+ let last;
+ for (let i = 0; i < 3; i++) last = await run();
+ expect(last).toMatchObject({ status: 'warn', details: { count: 'exact', materializable_rows: 1, pages_affected: 1, pages_inspected: PAGES } });
+ expect(last!.message).toContain('gbrain repair timeline --apply');
+});
+
+test('a timeline row written after a clean pass withdraws the trust in that pass', async () => {
+ for (let i = 0; i < 3; i++) await run();
+ await addDatabaseOnlyRow(PAGES - 1);
+ const next = await run();
+ expect(next.status).toBe('warn');
+ expect(next.details).toMatchObject({ count: 'lower_bound', materializable_rows: 0 });
+ expect(next.message).toContain('scan incomplete');
+});