Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Stop a lost-fence-rows apply at a pending page write so its tiers are lowered
garrytanc703f17fa5fc
diff --git a/src/core/repair/lost-fence-rows.ts b/src/core/repair/lost-fence-rows.tsindex 61c0cbfd53..ad7c91a08a 100644--- a/src/core/repair/lost-fence-rows.ts+++ b/src/core/repair/lost-fence-rows.ts@@ -245,28 +245,30 @@ export const lostFenceRowsRepair: RepairHandler = {},async apply(ctx, entry): Promise<RepairItemOutcome> {const { page, hash, last } = entry as LostRowsItem;- let pending = false;const detail = { facts: page.rows.filter(r => r.kind === 'fact').length, takes: page.rows.filter(r => r.kind === 'take').length };+ // The approved set is retired only when the last page ends without an error, so a stopped run's rerun can still lower the tiers.+ const done = async (outcome: RepairItemOutcome): Promise<RepairItemOutcome> => {+ if (last) await clearApprovedSet(ctx.engine, { command: 'lost-fence-rows', hash });+ return outcome;+ };+ // A rerun after this repair's own page write was left pending finds the rows live at their numbers: it only lowers their tiers.+ if (await lowerRestoredTiers(ctx.engine, page, true)) return done({ applied: true, outcome: 'restored', detail });+ const changed = (reason: string) => done({ applied: false, outcome: 'changed_since_preview', reason: `${page.slug}: ${reason}; run ${COMMAND} again for a new preview.` });+ const [now] = (await scanLostFenceRows(ctx.engine, [page.source_id], page)).pages;+ if (!now || now.revision !== page.revision || stableJson(now.rows) !== stableJson(page.rows)) return changed('the page or its lost rows changed since the preview');+ const planned = await plannedPage(ctx.engine, page);+ if (typeof planned === 'string') return changed(planned);try {- // A rerun after this repair's own page write was left pending finds the rows live at their numbers: it only lowers their tiers.- if (await lowerRestoredTiers(ctx.engine, page, true)) return { applied: true, outcome: 'restored', detail };- const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason: `${page.slug}: ${reason}; run ${COMMAND} again for a new preview.` });- const [now] = (await scanLostFenceRows(ctx.engine, [page.source_id], page)).pages;- if (!now || now.revision !== page.revision || stableJson(now.rows) !== stableJson(page.rows)) return changed('the page or its lost rows changed since the preview');- const planned = await plannedPage(ctx.engine, page);- if (typeof planned === 'string') return changed(planned);- try {- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id, content: planned.content, expected_revision: page.revision,- request_id: await repairRequestId(ctx, 'lost-fence-rows', entry, page.revision) } });- } catch (error) {- pending = error instanceof OperationError && error.code === 'write_pending';- throw error;- }- await lowerRestoredTiers(ctx.engine, page, false);- return { applied: true, outcome: 'restored', detail };- } finally {- if (last && !pending) await clearApprovedSet(ctx.engine, { command: 'lost-fence-rows', hash });+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, source_id: page.source_id, content: planned.content, expected_revision: page.revision,+ request_id: await repairRequestId(ctx, 'lost-fence-rows', entry, page.revision) } });+ } catch (error) {+ // Without its receipt a pending write stops the run here, before the cursor passes this page: the runner would otherwise settle+ // the write on its own later and never come back to lower the restored tiers. The rerun replays the same request, then lowers them.+ if (error instanceof OperationError && error.code === 'write_pending') error.writeRequest = undefined;+ throw error;}+ await lowerRestoredTiers(ctx.engine, page, false);+ return done({ applied: true, outcome: 'restored', detail });},render(details) {return [` each page: republished with the rows page history last held, through a revision-bound put_page; guide: ${details.docs}`];diff --git a/test/repair-lost-fence-rows.test.ts b/test/repair-lost-fence-rows.test.tsindex 217f4e6fe3..4e9b47d1b8 100644--- a/test/repair-lost-fence-rows.test.ts+++ b/test/repair-lost-fence-rows.test.ts@@ -15,8 +15,8 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { operationsByName } from '../src/core/operations.ts';import { renderTakesFence } from '../src/core/takes-fence.ts';import { emptyFenceBlock } from '../src/core/generations/fence.ts';-import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';-import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope, runRepair, type RepairResult } from '../src/core/repair/core.ts';+import { repairRunner, repairSpec } from '../src/core/repair/registry.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { durableGitRepo } from './helpers/git-publication.ts';import { withEnv } from './helpers/with-env.ts';@@ -49,7 +49,7 @@ const tierOf = async (engine: BrainEngine, table: 'facts' | 'takes', claim: striasync function repair(engine: BrainEngine, expectHash?: string): Promise<RepairResult> {const scope = await resolveRepairScope(engine, 'default');return (await repairRunner(engine, { apply: expectHash !== undefined, noEmbed: true, logger: { info() {}, warn() {}, error() {} } })).run('lost-fence-rows', scope,- { explicit: true, sourceFlag: 'default', ...(expectHash ? { expect: expectHash } : {}) });+ { explicit: true, sourceFlag: 'default', ...(expectHash ? { expect: expectHash } : {}), });}/** The section with the rows, a rewrite without it (held), then a section holding only a new row: the rows are retired. */async function loseRows(ctx: OperationContext) {@@ -173,6 +173,19 @@ for (const backend of testBackends()) {expect(first.stopped?.reason).toBe('write_pending');}, opts), 180_000);+ test('an apply whose pending page write publishes while the run waits still lowers the restored tiers', () => managedBrain(async ({ engine, ctx }) => {+ await loseRows(ctx);+ const preview = await repair(engine);+ const scope = await resolveRepairScope(engine, 'default');+ const { handler } = repairSpec('lost-fence-rows');+ const result = await runRepair({ ...ctx, remote: false, dryRun: false, writeWaitMs: 5_000 } as OperationContext,+ { ...handler, apply: (itemCtx, item, opts) => handler.apply({ ...itemCtx, writeWaitMs: 0 }, item, opts) }, scope,+ { apply: true, explicit: true, sourceFlag: 'default', expect: preview.preview_hash, spec: repairSpec('lost-fence-rows'),+ publicationOwner: async () => { await settleManagedGitEffects(engine); return { alive: true, owner: 'test publisher' }; } });+ if (result.stopped?.reason === 'write_pending') await repair(engine, preview.preview_hash);+ expect(await tierOf(engine, 'takes', TA)).toBe('external_untrusted');+ }, opts), 180_000);+test('an apply after the page changed restores nothing and asks for a new preview', () => managedBrain(async ({ engine, ctx }) => {await loseRows(ctx);const preview = await repair(engine);