Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): lost_caller_writes counts only writes the replay can offer (#6527)
time-attackf02cdcf3f7e0
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex de0c7373a4..81564974b8 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1008,8 +1008,14 @@ write keeps a receipt with its full intent until receipt compaction(`persistence.receipt_retention_days`, 30 days by default). `gbrain repairfailed-writes` submits those writes again. It is explicit-only andpreview-bound, and needs v0.60.38.0 or later (`gbrain doctor --json` reports-schema version 197 or later). Doctor's `lost_caller_writes` counts the writes-it would replay, per source, and names this preview.+schema version 197 or later). Doctor's `lost_caller_writes` counts the+retained refused writes that may be replayable, per source, and names this+preview; the preview decides which ones it replays. Doctor leaves out (and+lists under `details.not_replayable`) the two classes it can decide from the+receipt alone: an unpinned `remember` (`unpinned_target`) and a `put_page`+whose page changed after the revision the caller read (`superseded`). The+preview changes no page content, but it records an approval checkpoint for its+replay set, which `--apply --expect <hash>` reads.**Say to your agent:** *"Preview which refused writes gbrain can replay, showme the list, then apply after I agree."* The agent runs `gbrain repairdiff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex 15d89dbed5..2e1f907109 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -215,11 +215,14 @@ export async function lostCallerWritesCheck(engine: BrainEngine, sourceIds?: strconst docs = 'docs/guides/repair.md#failed-writes';try {const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);- const { lost, compacted } = await lostCallerWrites(engine, sources);+ const { lost, compacted, not_replayable } = await lostCallerWrites(engine, sources);const count = lost.reduce((sum, row) => sum + row.count, 0);- const details = { count, writes: lost, compacted_unreplayable: compacted, repair: 'failed-writes', docs };+ const kept = not_replayable.unpinned_target + not_replayable.revision_superseded;+ const details = { count, writes: lost, ...(kept ? { not_replayable } : {}), compacted_unreplayable: compacted, repair: 'failed-writes', docs };const compactedNote = compacted ? ` ${compacted} older refused receipt(s) were compacted (persistence.receipt_retention_days) and cannot be replayed.` : '';- if (!count) return { name: 'lost_caller_writes', status: 'ok', details, message: `Every caller write with a retained receipt committed or was superseded.${compactedNote}` };+ const keptNote = kept ? ` ${kept} refused caller write(s) cannot be replayed (${not_replayable.unpinned_target} remember whose subject was inferred, `+ + `${not_replayable.revision_superseded} put_page whose page changed after the revision the caller read); the caller has to write them again.` : '';+ if (!count) return { name: 'lost_caller_writes', status: 'ok', details, message: `Every caller write with a retained receipt committed or was superseded.${keptNote}${compactedNote}` };const bySource = new Map<string, number>();for (const row of lost) bySource.set(row.source_id, (bySource.get(row.source_id) ?? 0) + row.count);const first = [...bySource.keys()][0]!;@@ -228,9 +231,10 @@ export async function lostCallerWritesCheck(engine: BrainEngine, sourceIds?: strreturn { name: 'lost_caller_writes', status: 'warn', details,message: `${count} caller write(s) never landed (${memory} remember; ${drift} refused source_changed because the page's canonical file did not match its database copy `+ `or was missing, ${count - drift} refused by the managed writer guard): ${[...bySource].map(([source, n]) => `${source}: ${n}`).join(', ')}. The callers saw an error and `- + `the fact or page edit was dropped. Preview the replay on the brain host: gbrain repair failed-writes --source ${first} — then run the apply command it prints after the user agrees.${compactedNote}`,+ + `the fact or page edit was dropped. Preview the replay on the brain host: gbrain repair failed-writes --source ${first} — it lists which writes can be replayed and records `+ + `an approval checkpoint for that set (no page content changes); then run the apply command it prints after the user agrees.${keptNote}${compactedNote}`,fix: agentFix(['gbrain', 'repair', 'failed-writes', '--source', first],- 'Read-only preview: lists each lost write with its disposition (replay, already_written, duplicate, superseded) and prints the apply command.', 'lost_caller_writes', { docs }) };+ 'Preview: lists each lost write with its disposition (replay, already_written, duplicate, superseded, unpinned_target, file_database_drift), records an approval checkpoint for the replay set (no page content changes) and prints the apply command.', 'lost_caller_writes', { docs }) };} catch (error) {return checkError('lost_caller_writes', 'inspect refused caller writes', error, { details: { count: 'unknown', docs } });}diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 41789d4cc9..2bd9a42486 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -111,7 +111,8 @@ async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: strin/*** #6429: the caller writes this command would still replay, counted per source, operation and refusal reason for- * doctor's `lost_caller_writes`, plus the refused receipts compaction already emptied (unreplayable). Distinct+ * doctor's `lost_caller_writes`, plus the refused receipts compaction already emptied (unreplayable) and (#6527) the+ * retained ones the preview keeps for a reason SQL can decide (`not_replayable`). Distinct* intents, so a caller's retry counts its write once; a refused replay attempt is the original write (its rows are* dropped and its attempts walked as `disposition` does); a write whose replay or retry committed or whose page was* later deleted (for put_page: written again) is not lost. Owner-produced writes are not counted: their producer@@ -119,14 +120,19 @@ async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: strin* doctor runs this on every call.*/export async function lostCallerWrites(engine: BrainEngine, sourceIds: string[]):-Promise<{ lost: { source_id: string; operation: string; reason: 'source_changed' | 'writer_guard'; count: number }[]; compacted: number }> {- type Lost = { id: string; request_id: string; source_id: string; slug: string; operation: string; digest: string; sequence: string; reason: 'source_changed' | 'writer_guard' };+Promise<{ lost: { source_id: string; operation: string; reason: 'source_changed' | 'writer_guard'; count: number }[]; compacted: number;+ not_replayable: { unpinned_target: number; revision_superseded: number } }> {+ type Lost = { id: string; request_id: string; source_id: string; slug: string; operation: string; digest: string; sequence: string; reason: 'source_changed' | 'writer_guard';+ unpinned: boolean; stale_revision: boolean };const caller = `r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind')`;const refused = `(${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})`;const [rows, [compacted]] = await Promise.all([engine.executeRaw<Lost>(`SELECT r.id::text, r.request_id::text, r.source_id, r.slug, r.operation, r.digest, r.sequence::text,- CASE WHEN r.state='conflict' THEN 'source_changed' ELSE 'writer_guard' END AS reason+ CASE WHEN r.state='conflict' THEN 'source_changed' ELSE 'writer_guard' END AS reason,+ (r.operation='remember' AND jsonb_typeof(r.intent->'entity_slug') IS DISTINCT FROM 'string') AS unpinned,+ (r.operation='put_page' AND jsonb_typeof(r.intent->'expected_revision')='string' AND r.intent->>'expected_revision' IS DISTINCT FROM+ (SELECT p.knowledge_revision::text FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug AND p.deleted_at IS NULL)) AS stale_revisionFROM persistence_requests rWHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND ${refused} AND ${caller}ORDER BY r.sequence`, [sourceIds, REPLAYABLE]),@@ -137,7 +143,7 @@ Promise<{ lost: { source_id: string; operation: string; reason: 'source_changed'WHERE r.source_id = ANY($1::text[]) AND r.compacted AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL}) AND r.operation = ANY($2::text[])`,[sourceIds, REPLAYABLE.filter(operation => operation !== 'put_page')]),]);- if (!rows.length) return { lost: [], compacted: Number(compacted?.count ?? 0) };+ if (!rows.length) return { lost: [], compacted: Number(compacted?.count ?? 0), not_replayable: { unpinned_target: 0, revision_superseded: 0 } };// Attempt rows this command submitted belong to their original (walked below), not to the listing.const requestIds = new Set(rows.map(row => row.request_id));const replays = new Set<string>();@@ -176,15 +182,26 @@ Promise<{ lost: { source_id: string; operation: string; reason: 'source_changed'}pending = next;}+ // #6527: the two classes the preview keeps out of its replay set that SQL decides (as `disposition` does): a remember+ // whose subject was inferred (entity_slug absent or not a string) and a put_page whose page moved past the revision+ // the caller read. The rest (duplicate, still-drifted file) need per-row or filesystem reads; the preview decides.+ const unpinned = new Set<string>(), stale = new Set<string>();+ const replayable = lost.filter(row => {+ if (row.stale_revision) stale.add(`${row.source_id}\0${row.digest}`);+ else if (row.unpinned) unpinned.add(`${row.source_id}\0${row.digest}`);+ else return true;+ return false;+ });const groups = new Map<string, { source_id: string; operation: string; reason: Lost['reason']; digests: Set<string> }>();- for (const row of lost) {+ for (const row of replayable) {const key = `${row.source_id}\0${row.operation}\0${row.reason}`;const group = groups.get(key) ?? { source_id: row.source_id, operation: row.operation, reason: row.reason, digests: new Set<string>() };group.digests.add(row.digest);groups.set(key, group);}const sorted = [...groups.values()].sort((a, b) => a.source_id.localeCompare(b.source_id) || a.operation.localeCompare(b.operation) || a.reason.localeCompare(b.reason));- return { lost: sorted.map(group => ({ source_id: group.source_id, operation: group.operation, reason: group.reason, count: group.digests.size })), compacted: Number(compacted?.count ?? 0) };+ return { lost: sorted.map(group => ({ source_id: group.source_id, operation: group.operation, reason: group.reason, count: group.digests.size })), compacted: Number(compacted?.count ?? 0),+ not_replayable: { unpinned_target: unpinned.size, revision_superseded: stale.size } };}async function pageRevision(engine: BrainEngine, sourceId: string, slug: string): Promise<string | null> {@@ -307,7 +324,8 @@ export const failedWritesRepair: RepairHandler = {replay: replay.map(write => ({ id: write.id, digest: write.digest, revision: write.revision })) });if (replay.length) await saveApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash }, replay);return { items: replay.map((write, index) => item(write, hash, index === replay.length - 1)), preview_hash: hash, residuals, listing,- warnings: [...producers].map(([what, run]) => `${what}: produced by gbrain itself, not replayed here; ${run}`) };+ warnings: [...[...producers].map(([what, run]) => `${what}: produced by gbrain itself, not replayed here; ${run}`),+ ...(replay.length ? [`This preview recorded an approval checkpoint for its replay set (preview ${hash.slice(0, 12)}), which --apply --expect reads; no page content changed.`] : [])] };}if (!opts.expect) {throw new OperationError('invalid_params', 'gbrain repair failed-writes --apply replays only the set a preview printed.',diff --git a/test/lost-caller-writes-6527.test.ts b/test/lost-caller-writes-6527.test.tsnew file mode 100644index 0000000000..b11269defb--- /dev/null+++ b/test/lost-caller-writes-6527.test.ts@@ -0,0 +1,91 @@+/**+ * #6527: doctor `lost_caller_writes` counted every retained refused caller+ * write, while `gbrain repair failed-writes` (the command it names) keeps an+ * unpinned `remember` and a `put_page` whose page moved past the revision the+ * caller read out of its replay set. The count now leaves those two+ * SQL-decidable classes out and reports them under `not_replayable`, so the+ * count equals what the preview offers to replay; and the doctor text says the+ * preview records an approval checkpoint instead of calling it read-only.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { lostCallerWrites, failedWritesRepair } from '../src/core/repair/failed-writes.ts';+import { lostCallerWritesCheck } from '../src/commands/doctor/checks/persistence-requests.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { maintenanceAttribution } from '../src/core/persistence/attribution.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { durableGitRepo } from './helpers/git-publication.ts';++const gitRoot = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };++async function replaySet(engine: Parameters<typeof lostCallerWrites>[0]) {+ const [{ brain_id }] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');+ return failedWritesRepair.plan(engine, { brain_id, source_ids: ['default'] }, null, { apply: false });+}++for (const entitySlug of ['absent', 'null'] as const) {+ test(`#6527 an unpinned remember (entity_slug ${entitySlug}) is not counted as lost; it is reported not_replayable`, () => managedBrain(async ({ engine, ctx, root }) => {+ const slug = 'people/owner-example';+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: '---\ntype: person\ntitle: Owner\n---\n\nBody.\n' } });+ const file = join(root, `${slug}.md`);+ writeFileSync(file, readFileSync(file, 'utf8').replace('Body.', 'Body.\n\nLocal edit.'));+ await submitRememberMutation(ctx, { fact: 'Owner prefers async updates', entity: slug, provenance: 'test', visibility: 'world' }).catch(() => null);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(entitySlug === 'absent' ? "UPDATE persistence_requests SET intent = intent - 'entity_slug' WHERE operation='remember'"+ : "UPDATE persistence_requests SET intent = jsonb_set(intent, '{entity_slug}', 'null'::jsonb) WHERE operation='remember'");+ });+ const result = await lostCallerWrites(engine, ['default']);+ const plan = await replaySet(engine);+ expect(plan.residuals).toEqual({ unpinned_target: 1 });+ expect(result.lost.reduce((n, row) => n + row.count, 0)).toBe(plan.items.length);+ expect(result.not_replayable).toEqual({ unpinned_target: 1, revision_superseded: 0 });+ const check = await lostCallerWritesCheck(engine, ['default']);+ expect(check.status).toBe('ok');+ expect(check.message).toContain('1 refused caller write(s) cannot be replayed');+ }, { setup: gitRoot }), 120_000);+}++test('#6527 a put_page bound to a revision the page has since moved past is not counted as lost', () => managedBrain(async ({ engine, ctx, root }) => {+ const slug = 'notes/revision-example';+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: '---\ntype: note\ntitle: Example\n---\n\nFirst.\n' } });+ const read = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ const file = join(root, `${slug}.md`);+ writeFileSync(file, readFileSync(file, 'utf8').replace('First.', 'First.\n\nLocal edit.'));+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: read.revision,+ content: '---\ntype: note\ntitle: Example\n---\n\nCaller edit.\n' } }).catch(() => null);+ const [refused] = await engine.executeRaw<{ state: string; error_code: string }>(+ "SELECT state, error_code FROM persistence_requests WHERE operation='put_page' ORDER BY sequence DESC LIMIT 1");+ expect(refused).toEqual({ state: 'conflict', error_code: 'source_changed' });+ expect((await lostCallerWrites(engine, ['default'])).lost.reduce((n, row) => n + row.count, 0)).toBe(1);+ // The page moves on outside the journal (a sync import of the edited file would do the same).+ await engine.transaction(async tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.executeRaw("UPDATE pages SET compiled_truth=compiled_truth||'\n\nMoved on.' WHERE source_id='default' AND slug=$1", [slug]);+ }, await maintenanceAttribution(tx)));+ const result = await lostCallerWrites(engine, ['default']);+ const plan = await replaySet(engine);+ expect(plan.items.length).toBe(0);+ expect(result.lost.reduce((n, row) => n + row.count, 0)).toBe(0);+ expect(result.not_replayable).toEqual({ unpinned_target: 0, revision_superseded: 1 });+}, { setup: gitRoot }), 120_000);++test('#6527 doctor says the preview records an approval checkpoint, not that it is read-only', () => managedBrain(async ({ engine, ctx, root }) => {+ const slug = 'people/owner-example';+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: '---\ntype: person\ntitle: Owner\n---\n\nBody.\n' } });+ const file = join(root, `${slug}.md`);+ writeFileSync(file, readFileSync(file, 'utf8').replace('Body.', 'Body.\n\nLocal edit.'));+ await submitRememberMutation(ctx, { fact: 'Owner prefers async updates', entity: slug, provenance: 'test', visibility: 'world' }).catch(() => null);+ const check = await lostCallerWritesCheck(engine, ['default']);+ expect(check.status).toBe('warn');+ expect(check.fix?.why).not.toContain('Read-only');+ expect(check.fix?.why).toContain('approval checkpoint');+ const plan = await replaySet(engine);+ expect(plan.items.length).toBe(1);+ expect(plan.warnings?.join(' ')).toContain('recorded an approval checkpoint');+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='repair-approval'"))[0]!.n).toBe(1);+}, { setup: gitRoot }), 120_000);