Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a database-only grandfather validate:false stamp is not an uncoordinated file edit (#6429)
garrytanaf64f83f6d18
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 385039505b..ed7e37871f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,22 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.153.0] - 2026-10-10++**A database-only `validate: false` stamp no longer refuses every write; lost memory writes are counted and replayable.**++The v0.13.1 grandfather stamped `validate: false` into the database. On an unmanaged brain that migration never wrote the file (by design), so once the brain was managed every page with the stamp looked hand-edited and every coordinated write on it, `remember` included, was refused `source_changed` (#6429: 209k of 304k pages on one brain, 68 facts dropped silently). The stamp is now read as what it is, a mechanical database-side annotation, and the next write publishes it to the file. Nothing needs doing after you upgrade; to recover facts that were refused, run `gbrain repair failed-writes --source <id>` on the brain host and apply the set it prints after you agree.++### Itemized changes++- `prepareFileTarget` (`fileMatchesSnapshot`) treats a stored `validate: false` the way #5943 treats a pack-inferred `subtype`: a canonical file without a `validate:` key keeps the stored stamp instead of counting as an uncoordinated local edit. A file that records its own `validate:` decision is still compared as written. `put_page`, `remember`, maintenance pages, lint and `sources reconcile --audit` all route through it.+- `gbrain repair failed-writes` also lists and replays caller writes (`remember`, `put_page`, `add_timeline_entry`) that ended `conflict` with `source_changed`, with the same dispositions. A replay refused `source_changed` is classified `file_database_drift` only while the file still differs from the database: a reconcile that rewrites only the file makes the write a candidate again (before, only a change to the page row did).+- Doctor `lost_caller_writes` (ops) counts, per source, the caller writes whose receipt still holds an intent that never landed and names the `repair failed-writes` preview; a write whose replay or retry committed, or whose page was later deleted, is not counted.++### For contributors++- `test/ingestion/put-page-write-through.test.ts` (#6429 case) proves the stamp carry on PGLite (fails before the fix with `source_changed`); `test/repair-failed-writes-conflict-6429.test.ts` covers the conflict replay and the doctor check on PGLite and Postgres; `test/doctor-lost-caller-writes.test.ts` pins the registry wiring. Doctor goldens were regenerated for the new check.+## [0.60.152.0] - 2026-10-10**Remote fact writes apply the same visibility filter as reads.**diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 9f2a76cf27..a13c5f0460 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -678,14 +678,20 @@ found.<a id="failed-writes"></a>### Failed writes+Two kinds of refusal leave a caller's write with a receipt but nothing landed.On a managed brain whose `tags`, `timeline_entries` or `takes` table has a`source_id` column gbrain does not create, the managed writer guard of a-gbrain older than v0.60.38.0 refuses writes it should allow. Each refused write-keeps a failed receipt with its full intent until receipt compaction+gbrain older than v0.60.38.0 refuses writes it should allow. And a write ends+`conflict` with `source_changed` when the page's canonical file and database+copy differed at publication, as every write did on a brain whose v0.13.1+grandfather `validate: false` stamp lived only in the database (#6429, fixed+in v0.60.153.0: that stamp is no longer read as a file edit). Each refused+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).+schema version 197 or later). Doctor's `lost_caller_writes` counts the writes+it would replay, per source, and names this preview.**Say to your agent:** *"Preview which refused writes gbrain can replay, showme the list, then apply after I agree."* The agent runs `gbrain repair@@ -698,9 +704,10 @@ gbrain repair failed-writes --source <id> --apply --expect <hash>gbrain repair failed-writes --source <id> # replayed writes now read already_written```-Candidates are failed receipts refused by the guard: `writer_coordinator_required`,+Candidates are failed receipts refused by the guard (`writer_coordinator_required`,or `storage_error` "Publication failed (P0001)" from releases that did not keep-the guard's message. Only writes a caller made directly are replayed:+the guard's message) and conflict receipts refused `source_changed` at+publication. Only writes a caller made directly are replayed:`put_page`, `add_timeline_entry` and `remember`. The preview gives everycandidate one class:@@ -711,7 +718,7 @@ candidate one class:| `duplicate` | A later request with the same intent exists; that one is the candidate. | Kept. || `superseded` | A later write or delete of the page committed or is pending; for `put_page`, also a later failed `put_page` (newer content) or a page changed since the caller read it. | Kept; re-issue by hand if still wanted. || `unpinned_target` | A `remember` saved unattributed; replaying would infer its subject again and could pick another page. | Kept. Re-issue it with an explicit `entity` if it is still wanted. |-| `file_database_drift` | Its last replay hit `source_changed` (file and database differ). | Kept until the page changes; reconcile it first. |+| `file_database_drift` | Its last replay hit `source_changed` and the file still differs from the database. | Kept until the file matches again (a reconcile that writes only the file counts) or the page changes; reconcile it first. || `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content (sync: `gbrain sync --source <id> --no-pull --retry-failed`). |The apply replays exactly the previewed set. Each write is classified againdiff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 1812789bc5..61bc242f7c 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -14,6 +14,7 @@|---|---|---|---|---|| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok || Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |+| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.153.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok || A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` || A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` || A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex e2fba4f133..3b1c5f8a31 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -286,6 +286,7 @@ export const timelineHistoryEntry: DoctorEntry = {'persistence_request_indexes','persistence_request_growth','persistence_write_stall',+ 'lost_caller_writes','persistence_session_timeouts','connector_held_items','git_held_files',diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex afd78d6583..61e6e8c1c6 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -7,6 +7,7 @@ import { preparationBudgetMs } from '../../../core/persistence/preparation-budgeimport { readPreparationPolicy } from '../../../core/persistence/switches.ts';import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';import { agentFix, checkError } from '../check-fix.ts';+import { lostCallerWrites } from '../../../core/repair/failed-writes.ts';const WINDOW_DAYS = 7;const SAMPLE = 10_000;@@ -193,3 +194,37 @@ export async function sessionTimeoutsCheck(engine: BrainEngine): Promise<Check>return checkError('persistence_session_timeouts', 'read the session statement_timeout', error, { details: { configured, health: 'unknown', docs } });}}++/**+ * #6429: caller writes (`remember`, `put_page`, `add_timeline_entry`) that+ * ended `conflict` with `source_changed` (the page's file and database+ * differed at publication) or that the managed writer guard refused, whose+ * receipt still holds the intent. The caller saw an error and nothing landed:+ * on the reported brain 68 `remember` writes were lost this way while a+ * database-only grandfather stamp made every file look edited, and only a+ * query on `persistence_requests` showed it. Names the explicit-only replay's+ * preview per source. Read-only.+ */+export async function lostCallerWritesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const 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 rows = await lostCallerWrites(engine, sources);+ const count = rows.reduce((sum, row) => sum + row.count, 0);+ const details = { count, writes: rows, repair: 'failed-writes', docs };+ if (!count) return { name: 'lost_caller_writes', status: 'ok', details, message: 'Every caller write with a retained receipt committed or was superseded.' };+ const bySource = new Map<string, number>();+ for (const row of rows) bySource.set(row.source_id, (bySource.get(row.source_id) ?? 0) + row.count);+ const first = [...bySource.keys()][0]!;+ const drift = rows.filter(row => row.reason === 'file_database_drift').reduce((sum, row) => sum + row.count, 0);+ const memory = rows.filter(row => row.operation === 'remember').reduce((sum, row) => sum + row.count, 0);+ return { name: 'lost_caller_writes', status: 'warn', details,+ message: `${count} caller write(s) never landed (${memory} remember; ${drift} refused source_changed because the page's file and database differed, `+ + `${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.`,+ 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 }) };+ } catch (error) {+ return checkError('lost_caller_writes', 'inspect refused caller writes', error, { details: { count: 'unknown', docs } });+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 260113cce2..df02457b27 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -119,6 +119,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'Inspect it with `gbrain sources writer status --source <id> --json`, then restart the `gbrain serve` that owns the root (docs/guides/troubleshooting.md#persistence-write-stall).',run: async engine => (await import('./checks/persistence-requests.ts')).writeStallCheck(engine),},+ {+ id: 'lost_caller_writes', resolution: 'repair', registration: 'wave',+ hostOnly: 'Replaying refused caller writes is a host-side, explicit-only repair.',+ count: d => Number(d.count ?? 0),+ impact: 'Some caller writes (remember, put_page, add_timeline_entry) were refused at publication and never landed; the caller saw an error and the fact or edit was dropped',+ run: async (engine, scope) => (await import('./checks/persistence-requests.ts')).lostCallerWritesCheck(engine, scope.sourceIds),+ },{id: 'persistence_session_timeouts', resolution: 'operator', registration: 'wave',count: d => d.reason === 'session_timeouts_not_applied' ? 1 : 0,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 548ebfc68a..37618bdfd2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -373,6 +373,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },+ { since: '0.60.153.0', text: 'A page whose database frontmatter carries the v0.13.1 grandfather `validate: false` while its canonical file does not is no longer refused `source_changed` on write; the next coordinated write publishes the stamp to the file. `remember` and other caller writes that were refused that way are counted by doctor (`lost_caller_writes`) and replayed by `gbrain repair failed-writes --source <id>` on the brain host, after the user agrees to the previewed set.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex e0bb1c687a..c15aae6b6d 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -252,6 +252,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['persistence_request_growth','persistence_request_indexes','persistence_write_stall',+ 'lost_caller_writes','managed_sync_not_moving','persistence_session_timeouts',// #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex b28df78fb2..b76894492a 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -135,6 +135,10 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, byt// without an explicit `subtype:` keeps the stored subtype (or none); the import still stamps it.delete parsed.inferredSubtype;resolveParsedSubtype(parsed, snapshot.page);+ // #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path+ // never wrote the file, so the file lacks a key the database carries. The mechanical stamp authors nothing+ // (grandfather.ts): a file without a `validate:` key keeps the stored stamp, and the next coordinated write publishes it.+ if (!Object.hasOwn(parsed.frontmatter, 'validate') && snapshot.page.frontmatter?.validate === false) parsed.frontmatter.validate = false;// #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import.const type = parsed.typeExplicit ? parsed.type : snapshot.page.type;// Withdrawal overlays intentionally precede physical mirroring. The ledgerdiff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex a97f9e45d1..0918deee36 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -2,9 +2,13 @@* `gbrain repair failed-writes` (#5983): resubmits caller writes that the* managed writer guard refused while it misread page children's source* (`writer_coordinator_required`, stored before #5982 as `storage_error`- * "Publication failed (P0001)"). The failed receipt keeps its full intent until- * receipt compaction (`persistence.receipt_retention_days`), so the write can- * be submitted again once the guard is fixed.+ * "Publication failed (P0001)"), and (#6429) caller writes that ended+ * `conflict` with `source_changed` because the page's file and database+ * differed, such as the writes refused while a database-only grandfather+ * stamp made every file look edited. The+ * terminal receipt keeps its full intent until receipt compaction+ * (`persistence.receipt_retention_days`), so the write can be submitted again+ * once the guard or the drift check is fixed.** Only writes a caller made directly are replayed: `put_page` without an* owner-internal `kind`, `add_timeline_entry` and `remember`. Writes an owner@@ -47,6 +51,8 @@ import { isTerminal, principalKey, type WriteAuthority, type WriteRequest } fromimport { authorizeStoredRequest } from '../persistence/authority.ts';import { initializeLocalPersistence, requestPrincipalForContext, submitPageMutation } from '../persistence/page-mutations.ts';import { submitRememberMutation } from '../persistence/memory-mutations.ts';+import { getWorktreeBinding } from '../persistence/ownership.ts';+import { prepareFileTarget } from '../persistence/page-prepare.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';@@ -55,11 +61,13 @@ const REPLAYABLE = ['put_page', 'add_timeline_entry', 'remember'];const REMEMBER_PREPARED_KEYS = ['entity_slug', 'fence', 'valid_from', 'valid_until', 'entity_inferred', 'entity_warning'];const REMOTE_PREPARED_KEYS = ['source_kind', 'source_uri', 'ingested_via'];const PAGE_REMOVALS = ['delete_page', 'purge_page'];-const GUARD_REFUSAL = `(r.error_code='writer_coordinator_required'- OR (r.error_code='storage_error' AND r.error_message LIKE 'Publication failed (P0001)%'))`;+const GUARD_REFUSAL = `(r.state='failed' AND (r.error_code='writer_coordinator_required'+ OR (r.error_code='storage_error' AND r.error_message LIKE 'Publication failed (P0001)%')))`;+/** #6429: a refusal from prepareFileTarget (page-prepare.ts); the receipt keeps the code, not the refusal's detail. */+const DRIFT_REFUSAL = `(r.state='conflict' AND r.error_code='source_changed')`;interface FailedWrite {- id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string;+ id: string; request_id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string; state: string;intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null;}type Disposition = 'replay' | 'already_written' | 'duplicate' | 'superseded' | 'unpinned_target' | 'file_database_drift';@@ -83,14 +91,67 @@ function producerCommand(producer: string, sourceId: string): string {}async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: string): Promise<FailedWrite[]> {- return engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.intent, r.authority,+ const rows = await engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.request_id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.state, r.intent, r.authority,to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at,CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULLELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producerFROM persistence_requests r- WHERE r.source_id = ANY($1::text[]) AND r.state='failed' AND NOT r.compacted AND r.intent IS NOT NULL AND ${GUARD_REFUSAL}+ WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})${id ? 'AND r.id=$3::uuid' : ''}ORDER BY r.sequence`, id ? [sourceIds, REPLAYABLE, id] : [sourceIds, REPLAYABLE]);+ if (id) return rows;+ // #6429: a replay this command submitted that was refused source_changed is itself a conflict row; the original+ // write stays the candidate (its attempts are read through replayAttempt), so the attempt rows are not listed twice.+ const replays = new Set<string>();+ const requestIds = new Set(rows.map(row => row.request_id));+ for (const row of rows) for (let attempt = 0; requestIds.has(replayId(row.id, attempt)); attempt++) replays.add(replayId(row.id, attempt));+ return rows.filter(row => !replays.has(row.request_id));+}++/**+ * #6429: the caller writes this command would still replay, counted per source, operation and refusal reason for+ * doctor's `lost_caller_writes`. 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 runs them again. Reads no intents.+ */+export async function lostCallerWrites(engine: BrainEngine, sourceIds: string[]):+Promise<{ source_id: string; operation: string; reason: 'file_database_drift' | 'writer_guard'; count: number }[]> {+ type Lost = { id: string; request_id: string; source_id: string; slug: string; operation: string; digest: string; reason: 'file_database_drift' | 'writer_guard' };+ const rows = await engine.executeRaw<Lost>(+ `SELECT r.id::text, r.request_id::text, r.source_id, r.slug, r.operation, r.digest, CASE WHEN r.state='conflict' THEN 'file_database_drift' ELSE 'writer_guard' END AS reason+ FROM persistence_requests r+ WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})+ AND r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind')+ AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE c.source_id=r.source_id AND c.slug=r.slug AND c.state='committed' AND c.sequence > r.sequence+ AND (c.digest=r.digest OR c.operation = ANY($3::text[]) OR r.operation='put_page'))+ ORDER BY r.sequence`, [sourceIds, REPLAYABLE, PAGE_REMOVALS]);+ const requestIds = new Set(rows.map(row => row.request_id));+ const replays = new Set<string>();+ for (const row of rows) for (let attempt = 0; requestIds.has(replayId(row.id, attempt)); attempt++) replays.add(replayId(row.id, attempt));+ let pending = rows.filter(row => !replays.has(row.request_id));+ const lost: Lost[] = [];+ for (let attempt = 0; pending.length; attempt++) {+ const states = new Map((await engine.executeRaw<{ request_id: string; state: string }>(+ 'SELECT request_id::text, state FROM persistence_requests WHERE request_id = ANY($1::uuid[])', [pending.map(row => replayId(row.id, attempt))])).map(row => [row.request_id, row.state]));+ const next: Lost[] = [];+ for (const row of pending) {+ const state = states.get(replayId(row.id, attempt));+ if (state === 'committed') continue;+ if (state && isTerminal({ state: state as WriteRequest['state'] })) next.push(row);+ else lost.push(row);+ }+ pending = next;+ }+ const groups = new Map<string, { source_id: string; operation: string; reason: Lost['reason']; digests: Set<string> }>();+ for (const row of lost) {+ 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);+ }+ return [...groups.values()].sort((a, b) => a.source_id.localeCompare(b.source_id) || a.operation.localeCompare(b.operation) || a.reason.localeCompare(b.reason))+ .map(group => ({ source_id: group.source_id, operation: group.operation, reason: group.reason, count: group.digests.size }));}async function pageRevision(engine: BrainEngine, sourceId: string, slug: string): Promise<string | null> {@@ -132,6 +193,24 @@ function driftDetail(sourceId: string, slug: string): string {return `the page's file and database differ, so the replay was refused (source_changed); reconcile first: gbrain sources reconcile ${sourceId} ${slug} --preview, then run gbrain repair failed-writes again`;}+/**+ * #6429: whether the page's canonical file still differs from its database copy, the same check the replay's+ * preparation applies. A reconcile that rewrites only the file leaves the page row untouched, so the row's+ * `updated_at` alone cannot tell that the drift is gone. Without the page or its owner binding on this host the+ * drift is assumed to remain.+ */+async function stillDrifted(engine: BrainEngine, write: FailedWrite): Promise<boolean> {+ const snapshot = await engine.readPageSnapshot(write.slug, { sourceId: write.source_id });+ const binding = await getWorktreeBinding(engine, write.source_id);+ if (!snapshot || !binding) return true;+ try {+ await prepareFileTarget(engine, { source_id: write.source_id, worktree_id: binding.worktree_id, slug: write.slug }, snapshot, null);+ return false;+ } catch (error) {+ return !(error instanceof OperationError) || error.code === 'source_changed';+ }+}+/** Why a caller write must not be replayed now, or `replay`. */async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ class: Disposition; detail?: string }> {if ((await replayAttempt(engine, write.id)).prior?.state === 'committed') return { class: 'already_written', detail: 'replayed by gbrain repair failed-writes' };@@ -139,7 +218,7 @@ async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ cif (drifted?.error_code === 'source_changed') {const [written] = await engine.executeRaw<{ later: boolean }>('SELECT updated_at > $3::timestamptz AS later FROM pages WHERE source_id=$1 AND slug=$2', [write.source_id, write.slug, drifted.updated_at]);- if (!written?.later) return { class: 'file_database_drift', detail: driftDetail(write.source_id, write.slug) };+ if (!written?.later && await stillDrifted(engine, write)) return { class: 'file_database_drift', detail: driftDetail(write.source_id, write.slug) };}const replace = write.operation === 'put_page';const [later] = await engine.executeRaw<{ state: string; operation: string; same_intent: boolean }>(@@ -180,7 +259,7 @@ export const failedWritesRepair: RepairHandler = {const producers = new Map<string, string>();const replay: ApprovedWrite[] = [];for (const write of rows) {- const label = `${write.source_id}:${write.slug} ${write.operation} (failed ${write.created_at}, request ${write.id})`;+ const label = `${write.source_id}:${write.slug} ${write.operation} (${write.state} ${write.created_at}, request ${write.id})`;if (write.producer) {residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;producers.set(`${write.producer} in ${write.source_id}`, producerCommand(write.producer, write.source_id));diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex a1fe0b1704..39392a41f8 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -206,9 +206,9 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '(SQLSTATE XX000) as torn_pages without changing them. Bookkeeping only; no journal admission. Brain-wide; runs only when named.',},'failed-writes': {- handler: failedWritesRepair, embeds: 'effect', checks: [], explicit_only: true,- summary: 'Resubmit caller writes (put_page, add_timeline_entry, remember) that the managed writer guard refused before v0.60.38.0 (#5983), from the '- + 'intent their failed receipt retains until receipt compaction. A write is kept when a later request with the same intent committed (already_written) '+ handler: failedWritesRepair, embeds: 'effect', checks: ['lost_caller_writes'], explicit_only: true,+ summary: 'Resubmit caller writes (put_page, add_timeline_entry, remember) that the managed writer guard refused before v0.60.38.0 (#5983) or that ended '+ + 'conflict with source_changed because the page\'s file and database differed (#6429), from the intent their terminal receipt retains until receipt compaction. A write is kept when a later request with the same intent committed (already_written) '+ 'or is pending (duplicate), or a later write or delete of the page committed (superseded). Writes gbrain itself produced (sync and file imports, '+ 'reconcile, relink, maintenance) are counted with the command that produces them again. Preview-bound: --apply --expect <hash> replays exactly '+ 'the previewed set under new request ids, after re-checking each write\'s original authority; the failed receipts stay as history.',diff --git a/test/doctor-lost-caller-writes.test.ts b/test/doctor-lost-caller-writes.test.tsnew file mode 100644index 0000000000..0a9f0d2770--- /dev/null+++ b/test/doctor-lost-caller-writes.test.ts@@ -0,0 +1,28 @@+/**+ * lost_caller_writes doctor check (#6429): caller writes refused at+ * publication whose receipt still holds the intent are counted per source+ * with the explicit-only replay's preview. The warn path, the replay and the+ * clearing are exercised end to end in test/repair-failed-writes-conflict-6429.test.ts.+ *+ * PGLite in-memory ($0).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { lostCallerWritesCheck } from '../src/commands/doctor/checks/persistence-requests.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';+import { REPAIR_REGISTRY } from '../src/core/repair/registry.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => { await engine.disconnect(); });++test('a brain with no refused caller writes is ok, and the check is wired to the explicit-only replay', async () => {+ const check = await lostCallerWritesCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ count: 0, writes: [], repair: 'failed-writes' });+ expect(categorizeCheck('lost_caller_writes')).toBe('ops');+ const spec = WAVE_CHECKS.find(spec => spec.id === 'lost_caller_writes');+ expect(spec).toMatchObject({ resolution: 'repair', registration: 'wave' });+ expect(REPAIR_REGISTRY.find(spec => spec.kind === 'failed-writes')?.checks).toContain('lost_caller_writes');+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 82af928fec..374fc9763d 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -760,6 +760,18 @@"name": "persistence_write_stall","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#failed-writes",+ "repair": "failed-writes",+ "writes": []+ },+ "message": "Every caller write with a retained receipt committed or was superseded.",+ "name": "lost_caller_writes",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex ea15f2363b..1496441c98 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -843,6 +843,18 @@"name": "persistence_write_stall","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#failed-writes",+ "repair": "failed-writes",+ "writes": []+ },+ "message": "Every caller write with a retained receipt committed or was superseded.",+ "name": "lost_caller_writes",+ "status": "ok"+ },{"category": "ops","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 3adaf68f23..ee2affe2a7 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -393,6 +393,10 @@"category": "ops","name": "persistence_write_stall"},+ {+ "category": "ops",+ "name": "lost_caller_writes"+ },{"category": "ops","name": "persistence_session_timeouts"diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 6508527096..db9559ec5b 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -296,6 +296,40 @@ ${subtypes}`);expect(fs.readFileSync(file, 'utf8')).toContain('subtype: therapy');});+ test('a grandfather validate:false stamp held only by the database is not an uncoordinated file edit (#6429)', async () => {+ const ctx = makeCtx({ remote: true });+ const slug = 'companies/acme-example';+ const file = path.join(brainDir, `${slug}.md`);+ const content = '---\ntitle: Acme Example\ntype: company\n---\n\nFirst note.';+ const first = await putPage.handler(ctx, { slug, content }) as { revision: string };+ expect(fs.readFileSync(file, 'utf8')).not.toContain('validate:');+ // The unmanaged v0.13.1 grandfather path stamps the database row and never writes the file (v0_13_1.ts, raw UPDATE).+ await engine.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb) WHERE slug=$1 AND source_id='default'`, [slug]);+ const stamped = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ expect(stamped?.page.frontmatter.validate).toBe(false);+ expect(stamped?.revision).not.toBe(first.revision);++ const edited = await putPage.handler(ctx, { slug, content: content.replace('First', 'Second'), expected_revision: stamped!.revision });+ expect(edited).toMatchObject({ state: 'committed' });+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))?.page.compiled_truth).toBe('Second note.');++ // A memory write renders the stored page, so it publishes the stamp to the file instead of refusing.+ await engine.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb) WHERE slug=$1 AND source_id='default'`, [slug]);+ const remember = operations.find((o) => o.name === 'remember')!;+ const saved = await withEnv({ GBRAIN_HOME: path.join(tmpRoot, 'home') }, () => remember.handler(ctx,+ { fact: 'Acme Example moved to Austin', provenance: 'user told me, 2026-10-10', entity: slug, visibility: 'world', request_id: randomUUID() })) as { state?: string; status?: string };+ expect(saved.state ?? saved.status).toMatch(/committed|inserted/);+ const onDisk = fs.readFileSync(file, 'utf8');+ expect(onDisk).toContain('validate: false');+ expect(onDisk).toContain('Acme Example moved to Austin');++ // A file that records its own decision still wins: that is a real edit, not the stamp.+ fs.writeFileSync(file, onDisk.replace('validate: false', 'validate: true'));+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await expect(putPage.handler(ctx, { slug, content: content.replace('First', 'Third'), expected_revision: current!.revision }))+ .rejects.toMatchObject({ code: 'source_changed' });+ });+test('stamps provenance frontmatter (ingested_via=put_page for local CLI)', async () => {const ctx = makeCtx({ remote: false });const result = (await putPage.handler(ctx, {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d69bb896dc..e052e76b08 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -101,6 +101,7 @@ test/purge-fact.test.tstest/purge-global-marker.test.tstest/remediation-manual-only.test.tstest/repair-embedding-effects.test.ts+test/repair-failed-writes-conflict-6429.test.tstest/repair-failed-writes-drift-w411.test.tstest/repair-fences.test.tstest/repair-frontmatter.test.tsdiff --git a/test/repair-failed-writes-conflict-6429.test.ts b/test/repair-failed-writes-conflict-6429.test.tsnew file mode 100644index 0000000000..8a4022d1b5--- /dev/null+++ b/test/repair-failed-writes-conflict-6429.test.ts@@ -0,0 +1,122 @@+/**+ * #6429: a caller write that ended `conflict` with `source_changed` because+ * the page's file and database differed is a `gbrain repair failed-writes`+ * candidate. On the reported brain the+ * v0.13.1 grandfather stamped `validate: false` into the database only, so+ * every `remember` on those pages bounced and the fact was lost; once the+ * drift check carries the stamp (page-prepare.ts), the replay commits.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { lostCallerWritesCheck } from '../src/commands/doctor/checks/persistence-requests.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-replay-6429-db-'));+const logger = { info() {}, warn() {}, error() {} };+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++test('a remember refused as file/database drift is listed and replayed by repair failed-writes', async () => {+ for (const engine of engines) await conflictCase(engine);+}, 240_000);++async function conflictCase(engine: BrainEngine): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-6429-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `c6429-${randomUUID().slice(0, 8)}`;+ const slug = 'companies/acme-example';+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: '---\ntitle: Acme Example\ntype: company\n---\nAcme.', request_id: randomUUID() } });+ const file = join(root, 'companies', 'acme-example.md');+ expect(existsSync(file)).toBe(true);+ const published = readFileSync(file, 'utf8');+ // The file drifts from the database (a hand edit), so the remember is refused source_changed and ends in conflict.+ appendFileSync(file, '\nEdited in the file only.\n');+ await submitRememberMutation(ctx, { fact: 'Acme Example moved to Austin', entity: slug, provenance: 'test', visibility: 'world', request_id: randomUUID() }).catch(() => undefined);+ const [receipt] = await engine.executeRaw<{ state: string; error_code: string }>(+ `SELECT state, error_code FROM persistence_requests WHERE source_id=$1 AND operation='remember'`, [sourceId]);+ expect(receipt).toMatchObject({ state: 'conflict', error_code: 'source_changed' });++ // Doctor names the loss and the replay's preview; before this check only a query on persistence_requests showed it.+ const lost = await lostCallerWritesCheck(engine, [sourceId]);+ expect(lost.status).toBe('warn');+ expect(lost.message).toContain(`1 caller write(s) never landed (1 remember; 1 refused source_changed`);+ expect(lost.message).toContain(`gbrain repair failed-writes --source ${sourceId}`);+ expect(lost.details).toMatchObject({ count: 1, repair: 'failed-writes', writes: [{ source_id: sourceId, operation: 'remember', reason: 'file_database_drift', count: 1 }] });++ const scope = await resolveRepairScope(engine, sourceId);+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((preview.listing ?? []).map(entry => entry.class)).toEqual(['replay']);+ expect(preview.listing?.[0]?.item).toContain(`${slug} remember (conflict `);++ // Replaying while the file still differs refuses the same way and is classified, not retried blindly (W4.11).+ const stillDrifted = await (await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope,+ { explicit: true, sourceFlag: sourceId, expect: preview.apply_command.split('--expect ')[1] });+ expect(stillDrifted.outcomes).toEqual({ file_database_drift: 1 });+ const classified = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((classified.listing ?? []).map(entry => entry.class)).toEqual(['file_database_drift']);+ // The refused replay attempt is the same write, counted once.+ expect((await lostCallerWritesCheck(engine, [sourceId])).details).toMatchObject({ count: 1 });++ // A reconcile that publishes the file and leaves the page row untouched (file_written, database_changed=false)+ // makes the write a candidate again: the preview probes the file, not only the row's updated_at.+ writeFileSync(file, published);+ const again = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((again.listing ?? []).map(entry => entry.class)).toEqual(['replay']);+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope,+ { explicit: true, sourceFlag: sourceId, expect: again.apply_command.split('--expect ')[1] });+ expect(applied.outcomes).toEqual({ replayed: 1 });+ const [fact] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND fact LIKE 'Acme Example moved to Austin%'`, [sourceId]);+ expect(fact.n).toBe(1);+ expect(readFileSync(file, 'utf8')).toContain('Acme Example moved to Austin');++ const done = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect(done.affected).toBe(0);+ expect(done.residuals).toEqual({ already_written: 1 });+ // The replay committed the same intent, so doctor no longer counts the write as lost.+ expect((await lostCallerWritesCheck(engine, [sourceId])).status).toBe('ok');+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+}