Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fences): persist the per-source fences_normalized trend from sync runs and page writes (E33) (#6188)
garrytan1b607dc73a7e
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.tsindex da98d7cd41..27f40443fb 100644--- a/src/commands/sync/holds.ts+++ b/src/commands/sync/holds.ts@@ -10,6 +10,7 @@*/import { createHash, randomUUID } from 'crypto';import { importFenceTally } from '../../core/fence-repair/report.ts';+import { flushSyncFenceTrend } from '../../core/fence-repair/census-store.ts';import { existsSync, lstatSync } from 'fs';import { join } from 'path';import type { SyncResult } from '../sync.ts';@@ -227,7 +228,11 @@ export async function legacyHoldFields(engine: BrainEngine, holds: LegacyHolds |policy: holds.policy, screened: holds.counts.screened });const recovered = holds.recoveredPaths.length || holds.counts.commentValues? recoveredReport(holds.sourceId, addRecovered(undefined, { paths: holds.recoveredPaths, commentValues: holds.counts.commentValues })) : undefined;- return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}), ...holds.fences.fields() };+ const fences = holds.fences.fields();+ const normalized = fences.fences_normalized;+ await flushSyncFenceTrend(engine, { sourceId: holds.sourceId, runId: holds.runId, tally: normalized && { count: normalized.count,+ by_class: normalized.by_class as Record<string, number>, writers: Object.fromEntries(normalized.writers.map(w => [w.writer, w.count])) } });+ return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}), ...fences };}/** Dry run: the files this run would hold, read-only (no hold row is written or changed). */diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex e0edbaa6d6..cf7bd9ac16 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -34,6 +34,7 @@ import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts'import { databaseRefusal, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';+import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';interface PreparedMutationBase {sourceExclusive?: boolean;@@ -339,6 +340,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = skill ? null : await publicationPostimage(tx, row, prepared);decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);+ await recordPublicationFenceTrend(tx, row, outcome);await queuePublicationEffects(tx, row, final, outcome, prepared);await hooks.boundary?.('before_commit', row);const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex c11338f559..ad8ca4f5f7 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -53,6 +53,7 @@ import { decoratePublicationOutcome, finishUnpublishedFailure, pageRecoveryRecorimport { pipelined } from '../page-state/transactions.ts';import { jsonBytes } from './digest.ts';import { writerStamp } from './writer-versions.ts';+import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';/** A `put_pages` group publishes at most this many pages per transaction, so one commit stays a few seconds long. */export const PAGE_BATCH_GROUP_MAX = 8;@@ -188,6 +189,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prif (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = await publicationPostimage(tx, row, member);decoratePublicationOutcome(row, member, outcome, final, file ? 1 : 0, false);+ await recordPublicationFenceTrend(tx, row, outcome);await queuePublicationEffects(tx, row, final, outcome, member, { deferBatchReconcile: true });outcomes.push(outcome);}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex c5ad59355b..2c44caf95a 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -41,6 +41,7 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { faultPoint } from './fault-points.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';+import { flushSyncFenceTrend } from '../fence-repair/census-store.ts';import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, fencesNormalizedReport, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold, type FencesTally } from './sync-holds.ts';export interface ManagedSyncWriteDiagnostic {@@ -716,6 +717,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slscreened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);+ const tally = cursor?.counts.fences;+ await flushSyncFenceTrend(engine, { sourceId: state.sourceId, runId: cursor?.runId, tally: tally && { count: tally.count, by_class: tally.by_class, writers: tally.dirs } });return { ...synced, ...report, ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),...(recovered ? { recovered_frontmatter: recovered } : {}), ...(fences ? { fences_normalized: fences } : {}) };} catch {diff --git a/test/fence-write-verbs.test.ts b/test/fence-write-verbs.test.tsindex 1af914c6fc..f4e5a7a376 100644--- a/test/fence-write-verbs.test.ts+++ b/test/fence-write-verbs.test.ts@@ -26,6 +26,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { assertExportProjectionRoundtrip } from '../src/core/shared-skills/migration-projection.ts';import { parseMarkdown } from '../src/core/markdown.ts';import { verifyAndRepairDreamPages } from '../src/core/cycle/synthesize-verify.ts';+import { FENCE_TREND_OP } from '../src/core/fence-repair/census-store.ts';import { withEnv } from './helpers/with-env.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';@@ -151,6 +152,25 @@ test('put_pages reports one batch-level fences_normalized and one notice for theexpect(parseFactsFence(await stored('people/batch-fixable')).facts.map(f => f.rowNum)).toEqual([1]);}));+describe('normalization trend (E33)', () => {+ test('each normalized write adds one trend row with its classes and writer; clean writes and refused writes add none', () => withEnv(env, async () => {+ const rows = () => engine.executeRaw<{ fingerprint: string; record: Record<string, unknown> }>(+ `SELECT fingerprint, completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'='default'`, [FENCE_TREND_OP]);+ const before = new Set((await rows()).map(r => r.fingerprint));+ await put('people/trend-fixable', page('Trend', factsFence(fact(1, 'Trend claim'), fact(1, 'Second trend claim'))));+ await put('people/trend-clean', page('Clean', factsFence(fact(1, 'Plain trend claim'))));+ await refusal(() => put('people/trend-residual', page('Residual', factsFence(fact(1, 'Bad trend claim', { vis: 'blorp' })))));+ const slug = 'people/trend-remember';+ await storeMalformed(slug, `${FB}\n${FH}\n${fact(1, 'Existing trend claim')}`);+ await op('remember').handler(ctx(), { fact: 'A remembered trend fact', provenance: 'chat', entity: slug });+ const added = (await rows()).filter(r => !before.has(r.fingerprint)).map(r => r.record);+ expect(added).toHaveLength(2);+ expect(added.map(r => ({ count: r.count, writers: r.writers }))).toEqual([{ count: 1, writers: { local_cli: 1 } }, { count: 1, writers: { local_cli: 1 } }]);+ expect(added.map(r => r.by_class).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))).toEqual([{ close_fence: 1 }, { renumber: 1 }]);+ expectNoSecrets(added);+ }));+});+describe('append verbs normalize their target fence in the same write (D20)', () => {test('remember on a page whose facts fence lost its end marker saves the fact and reports close_fence', () => withEnv(env, async () => {const slug = 'people/remember-target';diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex 8a83681bb8..70fb3b7065 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -33,6 +33,8 @@ import { waitFor } from './helpers/wait-for.ts';import { readFileSync } from 'node:fs';import { parseFactsFence } from '../src/core/facts-fence.ts';import { parseTakesFence } from '../src/core/takes-fence.ts';+import { listFenceCandidates, runFenceCensus } from '../src/core/fence-repair/census.ts';+import { FENCE_TREND_OP } from '../src/core/fence-repair/census-store.ts';const backends = testBackends();const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-holds-'));@@ -367,3 +369,22 @@ test('TE1: a stored take whose prior fence did not parse is updated by its normaexpect(await engine.executeRaw('SELECT row_num,kind FROM takes k JOIN pages p ON p.id=k.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY row_num', [s.id, 'people/probe'])).toEqual([{ row_num: 1, kind: 'take' }, { row_num: 2, kind: 'take' }]);}), 180_000);++test('E33: a sync that normalizes 50 files writes one trend row with the run total; the census lists the held file once', () => each(async engine => {+ const files: Record<string, string> = { 'people/malformed.md': MALFORMED };+ for (let i = 0; i < 50; i++) files[`notes/fix-${String(i).padStart(2, '0')}.md`] = fixable(`Fix ${i}`);+ const s = await source(engine, files);+ const result = await s.sync();+ expect(result).toMatchObject({ held_count: 1, fences_normalized: { count: 50 } });+ const trend = await engine.executeRaw<{ record: Record<string, unknown> }>(`SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'=$2`,+ [FENCE_TREND_OP, s.id]);+ expect(trend).toHaveLength(1);+ expect(trend[0]!.record).toMatchObject({ count: 50, by_class: { kind_map: 50, holder_alias: 50 }, writers: { 'notes/': 50 } });+ // A second sync with nothing new adds no trend row.+ await s.sync();+ expect(await engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'=$2`, [FENCE_TREND_OP, s.id])).toHaveLength(1);+ await runFenceCensus(engine, { sourceIds: [s.id], deadline: Date.now() + 60_000 });+ const candidates = await listFenceCandidates(engine, [s.id]);+ expect(candidates.map(c => [c.key, c.bucket, c.origins, c.tier, c.reasons])).toEqual([['people/malformed', 'hold', ['hold', 'file'], 'resolver', ['holder_unresolved']]]);+ expectNoSecrets(JSON.stringify(candidates));+}), 240_000);