Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reconcile): audit reports database-only pages separately from drift (#5382)
time-attackb387bf713947
diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex d1fdd27821..2d2a8560e2 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -1,4 +1,4 @@-import { statSync } from 'node:fs';+import { existsSync, statSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError, opError, type OperationContext } from '../ops/contract.ts';@@ -15,12 +15,14 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import { readReconcileState } from './reconcile-state.ts';import { reconcileCanonical } from './reconcile-merge.ts';import { classifyDrift } from './reconcile-additive.ts';+import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';export interface ReconcileAuditReport extends Record<string, unknown> {source_id: string;inspected: number;drifted: number;errors: number;+ database_only: number;findings: Array<{ slug: string; reason: string; suggestion: string; classification?: string;drift_paths?: Array<{ path: string; class: string; reason: string }>; file_modified_after_database?: boolean }>;classified?: Record<string, number>;@@ -53,16 +55,26 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: string{ fix: readFix('Shows the canonical binding and owner host of this source.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });}const root = join(binding.local_path, binding.relative_path);- const rows = await engine.executeRaw<{ slug: string; bytes: number }>(`SELECT slug,+ const rows = await engine.executeRaw<{ slug: string; bytes: number; source_path: string | null; source_uri: string | null; database_only_reason: string | null }>(+ `SELECT slug, source_path, source_uri, database_only_reason,octet_length(compiled_truth)+octet_length(COALESCE(timeline,''))+octet_length(frontmatter::text) AS bytesFROM pages WHERE source_id=$1 AND deleted_at IS NULL AND page_kind='markdown' AND slug>$2ORDER BY slug LIMIT $3`, [sourceId, options.after ?? '', limit + 1]);- const report: ReconcileAuditReport = { source_id: sourceId, inspected: 0, drifted: 0, errors: 0, findings: [],+ const report: ReconcileAuditReport = { source_id: sourceId, inspected: 0, drifted: 0, errors: 0, database_only: 0, findings: [],next_after: rows.length > limit ? rows[limit - 1].slug : null, complete: rows.length <= limit, snapshot_only: true,...(options.classify ? { classified: { structurally_additive: 0, additive_with_suggestions: 0, review_required: 0, formatting_only: 0, error: 0 } } : {}) };const mode = await scannerSlugRootMode(engine, sourceId, root);for (const candidate of rows.slice(0, limit)) {report.inspected++;+ if (isDatabaseOnlyPage(candidate)) {+ const origin = slugDerivedOrigin(root, candidate.slug, mode);+ if (!origin || !existsSync(origin.path)) {+ report.database_only++;+ report.findings.push({ slug: candidate.slug, reason: 'database_only',+ suggestion: 'The page is database-only (written while the source had no canonical owner) and no file exists at its slug-derived path, so there is no file to reconcile; no action is needed.' });+ continue;+ }+ }try {if (Number(candidate.bytes) > 5_000_000) throw opError('invalid_params', 'The page exceeds the bounded audit size.',`Page ${candidate.slug} is over 5 MB in the database, so the audit skipped it; inspect it on the canonical host.`);diff --git a/test/reconcile-audit.test.ts b/test/reconcile-audit.test.tsindex c8dd8022e3..f8b44dfa7d 100644--- a/test/reconcile-audit.test.ts+++ b/test/reconcile-audit.test.ts@@ -62,6 +62,25 @@ test('bounded audit detects metadata drift and missing files without changing caexpect(await engine.executeRaw('SELECT request_id FROM persistence_requests')).toEqual([]);}), 60_000);+test('audit reports database-only pages separately; a legacy row without source_path is still drift', () => fixture(async (root, source) => {+ const insert = `INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter,content_hash,source_path,database_only_reason)+ VALUES($1,$2,'note','Example','A synthetic observation.','','{}'::jsonb,$3,NULL,$4)`;+ await engine.executeRaw(insert, [source, 'd-db-only', 'synthetic-dbonly-hash', 'unbound_source']);+ await engine.executeRaw(insert, [source, 'e-legacy', 'synthetic-legacy-hash', null]);+ const report = await runReconcileAudit(engine, { source_id: source });+ expect(report).toMatchObject({ inspected: 5, drifted: 3, errors: 0, database_only: 1 });+ expect(report.findings.map(row => [row.slug, row.reason])).toEqual([+ ['b', 'source_changed'], ['c', 'source_changed'], ['d-db-only', 'database_only'], ['e-legacy', 'source_changed']]);+ const dbOnly = report.findings.find(row => row.slug === 'd-db-only')!;+ expect(dbOnly.suggestion).not.toContain('sources reconcile');+ expect(report.findings.find(row => row.slug === 'e-legacy')!.suggestion).toContain('sources reconcile');++ writeFileSync(join(root, 'd-db-only.md'), '---\ntitle: Example\ntype: note\n---\nA file that appeared after binding.\n');+ const collided = await runReconcileAudit(engine, { source_id: source });+ expect(collided.database_only).toBe(0);+ expect(collided.findings.find(row => row.slug === 'd-db-only')?.reason).not.toBe('database_only');+}), 60_000);+test('audit cursor is bounded, explicit and not a source checkpoint', () => fixture(async (_root, source) => {const first = await runReconcileAudit(engine, { source_id: source, limit: 1 });expect(first).toMatchObject({ inspected: 1, drifted: 0, next_after: 'a', complete: false });