Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger lane A: typed purge_mirror_unwritable refusal (#22); committed mirror line from the coordinator after commit (#23)
garrytan53b747efb15d
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 34924c5f34..dd53b00479 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -95,6 +95,7 @@ of making a duplicate.| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. || <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. || <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |+| <a id="purge_mirror_unwritable"></a>`purge_mirror_unwritable` | `purge_mirror_unwritable` | A fact or page purge appends a text-free `intent` line to the purge mirror (`<brain home>/.gbrain/purge-events.jsonl`) and fsyncs it before it commits, so a later restore of an older backup can replay the purge. The mirror could not be written (a directory in its place, a read-only home, a full disk), so the purge was refused: nothing was removed, tombstoned or redacted. Do not assume the requested content was erased. | Make the mirror a writable regular file owned by the brain's user (mode 0600), then run the purge again with a new `request_id`. || <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). || <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. || <a id="fence_unrenderable"></a>`fence_unrenderable` | `fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. Before v0.60.218.0 the planner could reuse a leftover fence row (one with no database owner) whose visibility differed from the legacy fact's. On a managed brain the publisher refused that page here every cycle, so no private fact was published as world. An unmanaged brain had no such check: it fenced the fact into the leftover row, and the same cycle's reconcile copied that row's visibility into the fact, so a private fact could become world. The current planner never reuses a leftover row for a fact with a different visibility unless the fact is private, and re-renders a reused row from the fact. To count what an older build left in the writer table, run the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. |diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.tsindex 4fcf4d9fdc..35a2040148 100644--- a/src/core/belief/purge-mirror.ts+++ b/src/core/belief/purge-mirror.ts@@ -26,6 +26,7 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFimport { dirname, join } from 'node:path';import type { BrainEngine } from '../engine.ts';import { configDir } from '../config.ts';+import { opError } from '../ops/contract.ts';import { COVERAGE_KEY, factKey, pageKey, slugRef } from './keys.ts';import { appendBeliefEvents, type BeliefEventDraft } from './append.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers } from './purge.ts';@@ -47,8 +48,7 @@ export type PurgeMirrorLine = PurgeMirrorIntent | { kind: 'committed'; request:export const purgeMirrorPath = (home = configDir()) => join(home, PURGE_MIRROR_FILE);-/** Appends one line and fsyncs it (file 0600). Called before the purge commits (intent) and after (committed). */-export function appendPurgeMirror(line: Omit<PurgeMirrorIntent, 'recorded_at'> | { kind: 'committed'; request: string }, home = configDir()): void {+function writeMirrorLine(line: Record<string, unknown>, home: string): void {const path = purgeMirrorPath(home);mkdirSync(dirname(path), { recursive: true, mode: 0o700 });const fd = openSync(path, 'a', 0o600);@@ -59,6 +59,24 @@ export function appendPurgeMirror(line: Omit<PurgeMirrorIntent, 'recorded_at'> |chmodSync(path, 0o600);}+/**+ * Appends and fsyncs the `intent` line inside the purge transaction, before it commits. A mirror that cannot be+ * written refuses the purge with the typed `purge_mirror_unwritable` (review #22): committing without the line would+ * let a later restore bring the content back silently.+ */+export function appendPurgeIntent(line: Omit<PurgeMirrorIntent, 'recorded_at' | 'kind'>, home = configDir()): void {+ try { writeMirrorLine({ kind: 'intent', ...line }, home); }+ catch (error) {+ throw opError('purge_mirror_unwritable', 'This purge could not record itself in the purge mirror, so nothing was purged.',+ `${purgeMirrorPath(home)} could not be written (${(error as NodeJS.ErrnoException).code ?? (error as Error).message}). Make it a writable file owned by the brain's user (mode 0600), then run the purge again with a new request_id.`);+ }+}++/** Appends the `committed` line after the purge committed (the coordinator's after-commit step for a page purge). Best effort: a missing line reads as `unverified` at restore. */+export function appendPurgeCommitted(request: string, home = configDir()): boolean {+ try { writeMirrorLine({ kind: 'committed', request }, home); return true; } catch { return false; }+}+/*** Reads a mirror. Null when it cannot be read: the file is unreadable or* corrupt, or neither it nor the brain home it lives in exists. A brain homediff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c64a77d8d9..7545c054ce 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -424,6 +424,11 @@ export const CODES = {docs: 'docs/guides/write-refusals.md#purge_lookup_timeout',suggestion: 'Do not assume the requested content was erased. If the receipt names the slug index as missing or INVALID, run gbrain repair request-indexes --apply first; then submit the purge again with a new request_id (a retry with the same id returns this failure).',fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'host_admin', why: 'Previews the request-table indexes without changing anything; the purge receipt says whether the slug index is the cause.', requires_exclusive: false } },+ purge_mirror_unwritable: { class: 'caller', retryable: false, actor: 'host_admin',+ summary: "A purge could not append its intent line to the purge mirror (<brain home>/.gbrain/purge-events.jsonl), so it was refused; nothing was removed, tombstoned or redacted.",+ why: 'Restore replays the purges recorded in that text-free mirror; a purge that committed without its line would come back silently from an older backup.',+ docs: 'docs/guides/write-refusals.md#purge_mirror_unwritable',+ suggestion: 'Do not assume the requested content was erased. Make the mirror a writable regular file owned by the brain\'s user (mode 0600), then run the purge again with a new request_id.' },purged_content: { class: 'caller', summary: "The content matches a purged fact, take or page in this source, so it was not saved.", why: "A purge leaves a text-free tombstone (the claim fingerprint or the page content hash) so stale files, re-syncs, reverts and re-extraction cannot bring purged content back.", suggestion: 'Do not retry the same content. Write it in new words if it is still true, or ask the user to clear the tombstone on the brain host (gbrain pages purges list, then gbrain pages unpurge <slug> for a page).', docs: 'docs/guides/memory-boundaries.md#purge' },question_not_found: { class: 'caller', summary: "No pinned question has this id in the caller's scope; ids are source-qualified (default:questions/<slug>).", docs: 'docs/guides/pinned-questions.md#ids-and-scope' },question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 4bac47c9e3..fa773ca1c5 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -46,7 +46,7 @@ import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { carriesClaimSql, claimNeedles, purgeCompletion, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';import { noteBelief, withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';-import { appendPurgeMirror } from '../belief/purge-mirror.ts';+import { appendPurgeCommitted, appendPurgeIntent } from '../belief/purge-mirror.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, redactCarryingFields, redactPurgedKeys, registerLiveCarriers, sourceHasBeliefEvents,type LedgerPurgeReport } from '../belief/purge.ts';@@ -397,7 +397,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rectargets: derivedTargets, truncated: walk === 'truncated' }),derived_walk: walk }), current.id, p.sourceId) : null;counts.belief_events = ledger ? ledger.purged_events + ledger.redacted_fields.length : 0;- appendPurgeMirror({ kind: 'intent', request: admitted.id, request_id: p.requestId, source_id: p.sourceId, source_incarnation: source.incarnation, scope: 'fact',+ appendPurgeIntent({ request: admitted.id, request_id: p.requestId, source_id: p.sourceId, source_incarnation: source.incarnation, scope: 'fact',purge_epoch: epoch, facts: [{ fact_hash: current.fact_hash, visibility: current.visibility, subject: plan.subject }], takes: [], lifetimes: [] });return completeWrite(tx, admitted, 'committed', { purge: { fact_id: p.id, hash8: token, fact_hash: current.fact_hash, subject: plan.subject,visibility: current.visibility, removed: counts, derived: { ...derivedHidden, truncated: plan.derived.truncated }, pages: rewritten.length,@@ -411,7 +411,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recawait rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId: p.sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);}if (row.state !== 'committed') return { ...(row.outcome ?? {}), request_id: row.request_id, state: row.state, error: row.error_code };- appendPurgeMirror({ kind: 'committed', request: row.id });+ appendPurgeCommitted(row.id);if (beliefReport.appended || ledger?.derived_hidden) await markBeliefCommits(ctx.engine, [row.id]).catch(() => undefined);const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,vacuum: params.vacuum === true, ledger });diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 27a66e65b8..14f66fdabc 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -1,4 +1,5 @@import { isEmbedSkipped } from '../embed-skip.ts';+import { appendPurgeCommitted } from '../belief/purge-mirror.ts';import { sizeStateField } from '../page-embedding-budget.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { boundedReads } from './bounded-reads.ts';@@ -402,6 +403,8 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,// W1: a purge bumps sources.purge_epoch, so it holds the source row exclusively from the start (retention bumps nothing, #26);// the derived rows' and cascaded links' streams are locked with the page....(purge && !preparedPurge?.retention ? { sourceExclusive: true } : {}),+ // The purge mirror's `committed` line comes from the coordinator after the commit, whoever waits for the reply (#23).+ ...(preparedPurge && !preparedPurge.retention ? { afterCommit: async () => { appendPurgeCommitted(row.id); } } : {}),...(preparedPurge?.derivedSlugs.length ? { additionalPageKeys: preparedPurge.derivedSlugs.map(slug => ({ sourceId: row.source_id, slug })) } : {}),...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), ...(shared ? { databaseOnlyReason: 'shared_origin' as const } : {}),...(shared ? { validate: async (tx: BrainEngine) => { prepared.databaseOnlyWarning = await validateSharedOrigin(tx, row, shared); } } : {}),diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 475a20b575..c3886bd4b1 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -42,7 +42,7 @@ import { derivedRowsFrom, hideDerivedRows } from '../facts/derivation-inputs.ts'import { contentHash } from '../utils.ts';import { assertHeldPageKeys } from '../page-state/guards.ts';import { noteBelief } from '../belief/ledger.ts';-import { appendPurgeMirror } from '../belief/purge-mirror.ts';+import { appendPurgeIntent } from '../belief/purge-mirror.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers,sourceHasBeliefEvents, type LedgerPurgeReport } from '../belief/purge.ts';@@ -246,14 +246,14 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,derived_walk: walk })) : null;if (ledger) removed.belief_events = ledger.purged_events + ledger.redacted_fields.length;await tx.deletePage(slug, { sourceId });- if (!retention) appendPurgeMirror({ kind: 'intent', request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,+ if (!retention) appendPurgeIntent({ request: row.id, request_id: row.request_id, source_id: sourceId, source_incarnation: row.source_incarnation,scope: 'page', slug, purge_epoch: epoch, content_hashes: [...hashes], facts: mirrorFacts, takes: mirrorTakes, lifetimes });const key = `${sourceId}:${row.request_id}`;purgeContext.delete(key);purgeContext.set(key, { needles, factIds, pageId: page.id, paths, ledgerClaims: inventory.claims, ledger });while (purgeContext.size > PURGE_CONTEXT_LIMIT) purgeContext.delete(purgeContext.keys().next().value!);return { status: 'purged', slug, source_id: sourceId, residuals: PURGE_RESIDUALS, journal_sweep: journalSweep, ...(retention ? { retention: true } : {}),- purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed, ...(retention ? {} : { mirror_request: row.id }),+ purge: { content_hash8: storedHash?.slice(0, 8) ?? null, tombstoned: hashes.size > 0, content_hashes_tombstoned: hashes.size, removed,...(ledger ? { ledger: { purged_events: ledger.purged_events, redacted_fields: ledger.redacted_fields.length, live_carriers: ledger.live_carriers.length, derived_hidden: ledger.derived_hidden, derived_walk: ledger.derived_walk } } : {}),derived: { ...derived, truncated: derivedFrom.truncated },blobs: files.map(f => f.storage_path).filter(Boolean) } };@@ -269,8 +269,7 @@ export async function finishPagePurge(ctx: Pick<OperationContext, 'engine' | 'co// A same-id replay in this process returns what the purge call returned (blobs and verification are not re-run).const finished = purgeReceipts.get(key);if (finished) return { ...result, ...finished };- const purge = (result.purge ?? {}) as { blobs?: string[]; removed?: Record<string, number>; mirror_request?: string };- if (purge.mirror_request) appendPurgeMirror({ kind: 'committed', request: purge.mirror_request });+ const purge = (result.purge ?? {}) as { blobs?: string[]; removed?: Record<string, number> };const remaining: string[] = [];if (purge.blobs?.length) {try {diff --git a/test/belief-ledger-purge-review.test.ts b/test/belief-ledger-purge-review.test.tsindex e85113d6db..31f9fe3f39 100644--- a/test/belief-ledger-purge-review.test.ts+++ b/test/belief-ledger-purge-review.test.ts@@ -5,6 +5,9 @@*/import { afterEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync } from 'node:fs';+import { purgeMirrorPath } from '../src/core/belief/purge-mirror.ts';+import { CODES } from '../src/core/error-registry.ts';import { __setBeliefEmitterFaultForTests } from '../src/core/belief/append.ts';import { withBeliefBatch } from '../src/core/belief/ledger.ts';import { redactCarryingFields, registerLiveCarriers } from '../src/core/belief/purge.ts';@@ -180,5 +183,28 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {}));expect(r).toEqual({ retention: 0, purge: 1 });}, 240_000);+ test('#22: an unwritable purge mirror refuses the purge with a typed error, with or without a ledger', async () => {+ const run = (enable: boolean) => collect<Record<string, unknown>>(report => beliefBrain(async b => {+ await b.put('companies/acme-example', beliefPage({ facts: [X, 'Acme sells widgets'] }));+ mkdirSync(purgeMirrorPath(), { recursive: true });+ const error = await purgeFact(b, X).then(() => null, (e: { code?: string }) => e.code ?? 'untyped');+ const live = (await b.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL', [b.sourceId, X]))[0]!.n;+ report({ error, live, registered: 'purge_mirror_unwritable' in CODES });+ }, { managed: true, enable, databaseUrl: engineCase.databaseUrl }));+ expect({ ledger: await run(true), none: await run(false) }).toEqual({+ ledger: { error: 'purge_mirror_unwritable', live: 1, registered: true }, none: { error: 'purge_mirror_unwritable', live: 1, registered: true } });+ }, 240_000);++ test('#23: a page purge\'s committed mirror line is written after the commit even when no op handler finishes the reply', async () => {+ const r = await collect<Record<string, unknown>>(report => brain(async b => {+ await b.put('notes/vault-example', beliefPage({ facts: [X] }));+ const snapshot = await b.engine.readPageSnapshot('notes/vault-example', { sourceId: b.sourceId });+ const done = await b.op('delete_page', { slug: 'notes/vault-example', purge: true, expected_revision: snapshot!.revision });+ const request = await requestOf(b, String(done.request_id));+ const lines = readFileSync(purgeMirrorPath(), 'utf8').trim().split('\n').map(l => JSON.parse(l) as { kind: string; request: string });+ report({ state: done.state, kinds: lines.filter(l => l.request === request).map(l => l.kind) });+ }));+ expect(r).toEqual({ state: 'committed', kinds: ['intent', 'committed'] });+ }, 240_000);});}