Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(maintenance): ghost pages and repeated refusals stop burning quota (#6696 A12)
garrytan26cc4175dcfa
diff --git a/src/commands/doctor/checks/maintenance-drift.ts b/src/commands/doctor/checks/maintenance-drift.tsindex c411f4bc14..9d53873d46 100644--- a/src/commands/doctor/checks/maintenance-drift.ts+++ b/src/commands/doctor/checks/maintenance-drift.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { agentFix, checkError } from '../check-fix.ts';+import { listSuppressedWrites, type SuppressedWrite } from '../../../core/persistence/refusal-breaker.ts';import { auditConflictsCommand, FILE_DRIFT_MESSAGE, fileDriftRepairCommand, liveFileDrift, readDriftSkips } from '../../../core/persistence/drift-conflicts.ts';/** Newest request sequences scanned for drift conflicts (one range read of the unique sequence index). */@@ -16,6 +17,8 @@ const LIVE_LIMIT = 100;* It measures the drift itself, not conflict-row growth: producers back off* before admission, so a drifted page stops adding receipts. Names the* read-only audit and the explicit-only `gbrain repair file-drift` preview.+ * #6696 (A12): also lists the maintenance writes the refusal breaker holds+ * back (`suppressed`, each with the action that releases it).*/export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {const docs = 'docs/guides/troubleshooting.md#maintenance-write-drift';@@ -25,7 +28,9 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?const floor = String(Math.max(0, Number(bounds?.top ?? 0) - WINDOW));const skips = await readDriftSkips(engine);const rows = [];+ const suppressed: SuppressedWrite[] = [];for (const sourceId of sources) {+ suppressed.push(...await listSuppressedWrites(engine, sourceId));const candidates = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT r.slug FROM persistence_requests rWHERE r.sequence > $2::bigint AND r.source_id=$1 AND r.state='conflict' AND r.error_code='source_changed' AND r.error_message=$3ORDER BY r.slug LIMIT ${LIVE_LIMIT + 1}`, [sourceId, floor, FILE_DRIFT_MESSAGE]);@@ -42,7 +47,14 @@ export async function maintenanceWriteDriftCheck(engine: BrainEngine, sourceIds?}const count = rows.reduce((sum, row) => sum + row.drifted, 0);const skipCount = rows.reduce((sum, row) => sum + row.concept_skips, 0);- const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs };+ const details = { count, concept_skips: skipCount, sources: rows, window_sequences: WINDOW, repair: 'file-drift', docs, suppressed };+ if (!count && !skipCount && suppressed.length) {+ return { name: 'maintenance_write_drift', status: 'warn', details,+ message: `${suppressed.length} maintenance write(s) are held back after repeated identical refusals (#6696), so they stop adding receipts: `+ + `${suppressed.slice(0, 5).map(row => `${row.source_id}:${row.slug} ${row.error_code} x${row.refusals}${row.cause ? ` (${row.cause})` : ''} -> ${row.exit}`).join('; ')}. `+ + 'Each is tried again once its page, planner or write changes, or after a day.',+ fix: agentFix(['gbrain', 'write-request', '--', suppressed[0]!.last_request_id], 'Read-only: the last refused attempt and what it names.', 'maintenance_write_drift', { docs }) };+ }if (!count && !skipCount) {const unknown = rows.reduce((sum, row) => sum + row.unknown, 0);return { name: 'maintenance_write_drift', status: 'ok', details,diff --git a/src/core/config.ts b/src/core/config.tsindex 0a61451a11..398c41f903 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1774,6 +1774,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['persistence.publication_ceiling_ms', 'persistence.terminal_failures.window_days', 'persistence.terminal_failures.spike_factor', 'persistence.terminal_failures.spike_min', // #6405: persistence/sync-drain.ts (in-pass publication ceiling); #6650: persistence/terminal-failures.ts'persistence.capacity.warn_days', 'persistence.capacity.fail_days', 'persistence.capacity.background_pause_pct', // #6696: persistence/capacity-forecast.ts, admission-origin.ts'persistence.maintenance.compaction_stale_hours', // #6696 (A11): persistence/compaction-pass.ts, doctor persistence_compaction+ 'persistence.maintenance.refusal_breaker_threshold', // #6696 (A12): persistence/refusal-breaker.ts'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 9cccd5c9e8..76389a8806 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -36,7 +36,7 @@ import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePerimport { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';-import { databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { CANONICAL_FILE_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { SYNC_CURSOR_REPLACED } from './sync-checkpoint-replaced.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { withdrawalFailureDetail } from '../facts/withdrawal.ts';@@ -130,7 +130,8 @@ export { fileHash as persistenceFileHash, publishFile as publishPersistenceFilefunction requestError(error: unknown): PublicationFailure {if (error instanceof OperationError) {// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.- const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined);+ const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined)+ ?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined);return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };}const refusal = databaseRefusal(error);diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.tsindex 675ee963e8..d10c8b4d3d 100644--- a/src/core/persistence/drift-conflicts.ts+++ b/src/core/persistence/drift-conflicts.ts@@ -89,6 +89,8 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:} catch (error) {if (!(error instanceof OperationError)) return { still_present: null, reason: 'error' };if (error.detail !== 'file_database_drift') {+ // #6696 (A12): a recorded canonical file that is gone is its own reason; a producer refuses before admission on it.+ if (error.detail === 'canonical_file_missing') return { still_present: null, reason: 'canonical_file_missing', db_revision: page.revision };return { still_present: null, reason: error.code === 'source_changed' ? 'file_missing' : error.code };}const path = await canonicalFilePath(engine, sourceId, root, page, slug);diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 7b0a07762d..aee74bd813 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -12,6 +12,7 @@ import type { Page, PageVersion } from '../types.ts';import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { OperationError, opError } from '../ops/contract.ts';+import { CANONICAL_FILE_MISSING } from './publication-failure.ts';import { readFix } from '../ops/op-fix.ts';import { isOpPageSlug } from '../ops/context.ts';import { shellQuote, type Action } from '../agent-output.ts';@@ -210,8 +211,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// missing still refuses below.if (publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;if (options.deleting === true && content === null && !snapshot.page.source_path && !capturedPath) return undefined;- throw new OperationError('source_changed', 'The canonical file was removed outside coordinated publication.',- 'Import the local deletion or recover the canonical file before editing this page.');+ // #6696 (A12): tagged, so a producer can refuse this before admission and the receipt says which refusal it was.+ throw opError('source_changed', 'The canonical file was removed outside coordinated publication.',+ 'Import the local deletion or recover the canonical file before editing this page.', { detail: CANONICAL_FILE_MISSING });}// A normal edit may replace only the bytes represented by its read snapshot.// Unknown local edits require explicit import/recovery, even for force writes.diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex fb8c8c6ffd..f2c2bbe2b0 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -16,6 +16,8 @@ import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';import { admitWrite, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';+import { assertRefusalBreakerClosed } from './refusal-breaker.ts';+import { CANONICAL_FILE_MISSING } from './publication-failure.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';import { preparePageMutation, prepareFileTarget } from './page-prepare.ts';import { prepareTakesMutation } from './takes-prepare.ts';@@ -171,10 +173,15 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuth}// #6643 (B1): a canonical file that already differs from the database refuses at publication; refuse before a request// exists, so a producer that runs every cycle stops adding a conflict receipt per cycle. A replay above still returns its receipt.- if (file && authority.binding && snapshot && !snapshot.page.deleted_at- && (await liveFileDrift(engine, authority.writer.sourceId, slug, snapshot)).still_present === true) {- throw maintenanceDriftRefusal(authority.writer.sourceId, slug);+ if (file && authority.binding && snapshot && !snapshot.page.deleted_at) {+ const live = await liveFileDrift(engine, authority.writer.sourceId, slug, snapshot);+ if (live.still_present === true) throw maintenanceDriftRefusal(authority.writer.sourceId, slug);+ // #6696 (A12): the recorded canonical file is gone, so publication would refuse source_changed; refuse before a request exists.+ if (live.reason === CANONICAL_FILE_MISSING) throw maintenanceGhostRefusal(authority.writer.sourceId, slug);}+ // #6696 (A12): the same write refused K times in the window is not admitted again until something it depends on changes.+ await assertRefusalBreakerClosed(engine, { principal: authority.writer.principal, sourceId: authority.writer.sourceId, slug,+ digest: intentDigest({ operation: 'submit_job', sourceId: authority.writer.sourceId, slug, callerIntent: intent }) });const row = await admitWrite(engine, { principal: authority.writer.principal, requestId, operation: 'submit_job',sourceId: authority.writer.sourceId, sourceIncarnation: authority.writer.sourceIncarnation, slug,pageId: snapshot?.page.id ?? null, authority: authority.writer, callerIntent: intent, intent,@@ -191,6 +198,15 @@ export function maintenanceDriftRefusal(sourceId: string, slug: string): Operati{ argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });}+/** #6696 (A12): `source_changed` / `canonical_file_missing` before admission: the page's recorded file is gone; never a new request. */+export function maintenanceGhostRefusal(sourceId: string, slug: string): OperationError {+ return opError('source_changed', 'The canonical file was removed outside coordinated publication.',+ `Maintenance submitted nothing for ${slug} in '${sourceId}': the page's canonical file is missing, so the write would only add another conflict receipt. `+ + `Import the deletion with gbrain sync --source ${sourceId}, or restore the file and preview the page with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview. Neither copy was changed.`,+ { detail: CANONICAL_FILE_MISSING, fix: readFix(`Previews how page ${slug} and its missing canonical file reconcile; read-only.`,+ { argv: ['gbrain', 'sources', 'reconcile', sourceId, slug, '--brain', 'host', '--preview', '--json'] }) });+}+/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 3e0529f254..8e66cb9286 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -47,7 +47,10 @@ export interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'st}/** A `fact_withdrawn` refusal's `withdrawn` object (`facts/withdrawal.ts`), plus the attempt stamp. */export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail }+/** #6696 (A12): the page's recorded canonical file is gone (`prepareFileTarget`); a producer refuses the same write before admission. */+export const CANONICAL_FILE_MISSING = 'canonical_file_missing';+export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;diff --git a/src/core/persistence/refusal-breaker.ts b/src/core/persistence/refusal-breaker.tsnew file mode 100644index 0000000000..0b25943a4e--- /dev/null+++ b/src/core/persistence/refusal-breaker.ts@@ -0,0 +1,78 @@+/**+ * #6696 (A12): known-failing maintenance writes stop burning quota.+ *+ * A producer that resubmits the same write under a fresh request id after it+ * was refused (an adoption attempt counter, a caller-chosen id) mints one+ * permanent request id and one receipt per cycle. After+ * `persistence.maintenance.refusal_breaker_threshold` (default 3; 0 turns it+ * off) terminal refusals with the same error code in the last 24 hours for+ * the same request digest, the next submission is refused before admission+ * (no request id, no receipt). The digest covers the source, the slug and+ * the producer's intent, which carries the page revision it expects and, for+ * planned writes, the planner version, so any change to those (an edited+ * page, a new planner, different content) releases it at once; otherwise the+ * window is the revalidation: the oldest refusal ages out and one more+ * attempt is admitted. Reads the request journal on its slug index; keeps no+ * state of its own.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Principal } from './model.ts';++export const REFUSAL_BREAKER_THRESHOLD_KEY = 'persistence.maintenance.refusal_breaker_threshold';+export const DEFAULT_REFUSAL_BREAKER_THRESHOLD = 3;+export const REFUSAL_BREAKER_WINDOW_HOURS = 24;++export async function readRefusalBreakerThreshold(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {+ const raw = await engine.getConfig(REFUSAL_BREAKER_THRESHOLD_KEY);+ const value = raw === null || raw === undefined || raw === '' ? DEFAULT_REFUSAL_BREAKER_THRESHOLD : Number(raw);+ return Number.isSafeInteger(value) && value >= 0 ? value : DEFAULT_REFUSAL_BREAKER_THRESHOLD;+}++interface PriorRefusals { count: number; error_code: string; request_id: string; detail_origin: string | null }++/** The same-digest refusals in the window, grouped by code, largest group first. */+async function priorRefusals(engine: BrainEngine, input: { principal: Principal; sourceId: string; slug: string; digest: string }): Promise<PriorRefusals | null> {+ const [row] = await engine.executeRaw<{ count: string; error_code: string; request_id: string; detail_origin: string | null }>(`SELECT count(*)::text AS count,error_code,+ (array_agg(request_id::text ORDER BY sequence DESC))[1] AS request_id,(array_agg(error_detail->>'origin' ORDER BY sequence DESC))[1] AS detail_origin+ FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent IS NOT NULL AND NOT compacted AND digest=$3+ AND principal_kind=$4 AND principal_id=$5 AND state IN ('failed','conflict') AND error_code IS NOT NULL+ AND completed_at > now()-($6::double precision*interval '1 hour')+ GROUP BY error_code ORDER BY count(*) DESC LIMIT 1`, [input.sourceId, input.slug, input.digest, input.principal.kind, input.principal.id, REFUSAL_BREAKER_WINDOW_HOURS]);+ return row ? { count: Number(row.count), error_code: row.error_code, request_id: row.request_id, detail_origin: row.detail_origin } : null;+}++/** Refuses before admission when the breaker is open for this write; returns otherwise. */+export async function assertRefusalBreakerClosed(engine: BrainEngine, input: { principal: Principal; sourceId: string; slug: string; digest: string }): Promise<void> {+ const threshold = await readRefusalBreakerThreshold(engine);+ if (threshold <= 0) return;+ const prior = await priorRefusals(engine, input);+ if (!prior || prior.count < threshold) return;+ throw refusalBreakerError(input.sourceId, input.slug, prior, threshold);+}++function refusalBreakerError(sourceId: string, slug: string, prior: PriorRefusals, threshold: number): OperationError {+ return opError(prior.error_code as Parameters<typeof opError>[0], 'The same maintenance write was already refused repeatedly.',+ `Maintenance submitted nothing for ${slug} in '${sourceId}': the same write was refused ${prior.count} time(s) with ${prior.error_code} in the last ${REFUSAL_BREAKER_WINDOW_HOURS} hours `+ + `(${REFUSAL_BREAKER_THRESHOLD_KEY}=${threshold}), so another attempt would only add a receipt. It is tried again once the page, the planner or the write changes, `+ + `or when the oldest refusal is ${REFUSAL_BREAKER_WINDOW_HOURS} hours old. Read the last refusal with gbrain write-request -- ${prior.request_id} and fix what it names.`,+ { detail: 'refusal_breaker', fix: readFix(`Reads the last refused attempt (request ${prior.request_id}), read-only.`, { argv: ['gbrain', 'write-request', '--', prior.request_id] }) });+}++export interface SuppressedWrite { source_id: string; slug: string; error_code: string; refusals: number; last_request_id: string; cause: string | null; exit: string }++/** Slugs whose maintenance writes the breaker is holding back right now, with the action that releases each (doctor `maintenance_write_drift`). */+export async function listSuppressedWrites(engine: BrainEngine, sourceId: string, limit = 20): Promise<SuppressedWrite[]> {+ const threshold = await readRefusalBreakerThreshold(engine);+ if (threshold <= 0) return [];+ const rows = await engine.executeRaw<{ slug: string; error_code: string; refusals: string; last_request_id: string; cause: string | null }>(`SELECT slug,error_code,+ count(*)::text AS refusals,(array_agg(request_id::text ORDER BY sequence DESC))[1] AS last_request_id,(array_agg(error_detail->>'origin' ORDER BY sequence DESC))[1] AS cause+ FROM persistence_requests WHERE source_id=$1 AND intent IS NOT NULL AND NOT compacted AND operation='submit_job' AND state IN ('failed','conflict')+ AND error_code IS NOT NULL AND completed_at > now()-($2::double precision*interval '1 hour')+ GROUP BY slug,digest,error_code HAVING count(*) >= $3 ORDER BY slug LIMIT $4`, [sourceId, REFUSAL_BREAKER_WINDOW_HOURS, threshold, limit]);+ return rows.map(row => ({ source_id: sourceId, slug: row.slug, error_code: row.error_code, refusals: Number(row.refusals), last_request_id: row.last_request_id, cause: row.cause,+ exit: row.cause === 'canonical_file_missing'+ ? `gbrain sources reconcile ${sourceId} ${row.slug} --brain host --preview (import the deletion or restore the file)`+ : `gbrain write-request -- ${row.last_request_id} (fix what it names; any page, planner or write change releases it)` }));+}diff --git a/test/maintenance-ghost-breaker-6696.test.ts b/test/maintenance-ghost-breaker-6696.test.tsnew file mode 100644index 0000000000..cb807636cd--- /dev/null+++ b/test/maintenance-ghost-breaker-6696.test.ts@@ -0,0 +1,109 @@+/**+ * #6696 (A12): known-failing maintenance writes stop burning quota.+ * - A page whose canonical file is gone (a ghost) refuses `source_changed` /+ * `canonical_file_missing` before admission: two maintenance cycles add no+ * request (before #6696, one conflict receipt each). A caller write still+ * gets its receipt, and the receipt's detail names the cause.+ * - The refusal breaker: after K (persistence.maintenance.refusal_breaker_threshold,+ * default 3) identical terminal refusals of the same write under fresh+ * request ids, the next one is refused before admission; a planner version+ * bump (a different intent) is admitted again. Doctor+ * `maintenance_write_drift` lists the suppressed slug with its exit.+ * PGLite; synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, unlinkSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+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 { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { maintenancePreflight, publishMaintenancePage, submitDatabaseMaintenanceIntent } from '../src/core/persistence/prepared-maintenance.ts';+import { liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';+import { REFUSAL_BREAKER_THRESHOLD_KEY } from '../src/core/persistence/refusal-breaker.ts';+import { maintenanceWriteDriftCheck } from '../src/commands/doctor/checks/maintenance-drift.ts';+import { withEnv } from './helpers/with-env.ts';++const logger = { info() {}, warn() {}, error() {} };++describe('#6696 A12 ghost refusal and refusal breaker', () => {+ let engine: BrainEngine;+ const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-6696-a12-db-'));+ beforeAll(async () => { const pglite = new PGLiteEngine(); await pglite.connect({ database_path: dataDir }); await pglite.initSchema(); engine = pglite; }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(dataDir, { recursive: true, force: true }); });++ async function fixture(run: (input: { root: string; sourceId: string; ctx: OperationContext }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6696-a12-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `a12-${randomUUID().slice(0, 8)}`;+ 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');+ await run({ root, sourceId, ctx: { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.unsetConfig(REFUSAL_BREAKER_THRESHOLD_KEY);+ rmSync(dir, { recursive: true, force: true });+ }+ }+ const put = (ctx: OperationContext, slug: string, content: string, expected_revision?: string) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...(expected_revision ? { expected_revision } : {}) } });+ const requests = async (sourceId: string, slug: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.n);++ test('two maintenance cycles on a ghost add no receipt; a caller write records canonical_file_missing', () => fixture(async ({ root, sourceId, ctx }) => {+ const slug = 'notes/ghost-example';+ await put(ctx, slug, '---\ntype: note\ntitle: Ghost\n---\nThe original text.\n');+ unlinkSync(join(root, 'notes', 'ghost-example.md'));+ expect(await liveFileDrift(engine, sourceId, slug)).toMatchObject({ still_present: null, reason: 'canonical_file_missing' });+ const authority = (await maintenancePreflight(engine, sourceId, root))!;+ const before = await requests(sourceId, slug);+ for (const cycle of [1, 2]) {+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const refused = await publishMaintenancePage(engine, authority, slug, `---\ntype: note\ntitle: Ghost\n---\nCycle ${cycle} text.\n`, { expectedRevision: snapshot.revision })+ .then(() => null, (error: { code?: string; detail?: string; fix?: { argv?: string[] } }) => error);+ expect(refused).toMatchObject({ code: 'source_changed', detail: 'canonical_file_missing', fix: { argv: ['gbrain', 'sources', 'reconcile', sourceId, slug, '--brain', 'host', '--preview', '--json'] } });+ }+ expect(await requests(sourceId, slug)).toBe(before);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ await put(ctx, slug, '---\ntype: note\ntitle: Ghost\n---\nA caller edit.\n', snapshot.revision).then(() => { throw new Error('committed'); }, (error: { code?: string }) => expect(error.code).toBe('source_changed'));+ const [receipt] = await engine.executeRaw<{ origin: string | null }>("SELECT error_detail->>'origin' AS origin FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='conflict' ORDER BY sequence DESC LIMIT 1", [sourceId, slug]);+ expect(receipt?.origin).toBe('canonical_file_missing');+ }), 240_000);++ test('the same refused write is held back after K refusals and admitted again after a planner bump; doctor lists it', () => fixture(async ({ root, sourceId, ctx }) => {+ const slug = 'notes/breaker-example';+ await put(ctx, slug, '---\ntype: note\ntitle: Breaker\n---\nText.\n');+ const authority = (await maintenancePreflight(engine, sourceId, root))!;+ const revision = (await engine.readPageSnapshot(slug, { sourceId }))!.revision;+ // A malformed adoption plan (one fact assigned twice) is refused at preparation every time.+ const intent = (planner: number) => ({ kind: 'managed_maintenance_adopt_fact_fence', expected_revision: revision, source_incarnation: authority.writer.sourceIncarnation,+ content: 'x', facts: [{ id: 1, row_num: 1, hash: 'h' }, { id: 1, row_num: 2, hash: 'h' }], planner });+ const submit = (planner: number) => submitDatabaseMaintenanceIntent(engine, authority, slug, intent(planner), randomUUID())+ .then(receipt => ({ admitted: true, receipt }), (error: { code?: string; detail?: string }) => ({ admitted: !error.detail || error.detail !== 'refusal_breaker', error }));+ for (let i = 0; i < 3; i++) expect((await submit(2)).admitted).toBe(true);+ const failed = await requests(sourceId, slug);+ const held = await submit(2);+ expect(held).toMatchObject({ admitted: false, error: { code: 'invalid_params', detail: 'refusal_breaker' } });+ expect(await requests(sourceId, slug)).toBe(failed);+ const doctor = await maintenanceWriteDriftCheck(engine, [sourceId]);+ expect(doctor).toMatchObject({ status: 'warn', details: { suppressed: [{ slug, error_code: 'invalid_params', refusals: 3 }] } });+ // A planner bump is a different write: admitted at once.+ expect((await submit(3)).admitted).toBe(true);+ expect(await requests(sourceId, slug)).toBe(failed + 1);+ // Threshold 0 turns the breaker off.+ await engine.setConfig(REFUSAL_BREAKER_THRESHOLD_KEY, '0');+ expect((await submit(2)).admitted).toBe(true);+ }), 240_000);+});