Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): receipt-compaction on demand; compaction skips open sync runs (#6696 A9)
garrytanb94d3b3ae84c
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 57f0741277..25d05476c7 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -143,6 +143,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `planner-stats` | `planner_stats_stale` | Runs `ANALYZE` on the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale, so search and graph reads stop planning as slow nested loops. PGLite also resets each table's pending row count; Postgres runs each `ANALYZE` with a 60 s statement timeout and a 2 s lock timeout. No journal admission, no user data changes, brain-wide. | none || `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. || `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |+| `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -242,6 +243,39 @@ one more year, the same value `persistence_capacity` prints) and the check tore-run. Request IDs are permanent, so raising the limit is the intervention;nothing is evicted.+<a id="receipt-compaction"></a>+### Receipt compaction++A brain whose receipt-bytes cap is close (doctor `persistence_capacity`, a+`write_quota_exhausted` refusal with reason `terminal_bytes`) gets bytes back+by compacting terminal receipts, which the resident consumer otherwise does+on idle ticks once a receipt is older than `persistence.receipt_retention_days`+(default 30). The repair runs the same per-receipt compaction on demand:++```bash+gbrain repair receipt-compaction --json # preview at the retention floor+gbrain repair receipt-compaction --apply --expect <hash> --yes+```++- `--older-than <72h|30d>` sets the age; it may not be younger than the+ configured retention unless `--force` (a younger receipt is how a caller+ replays its request id in full). With retention 90 days, `--older-than 30d`+ is refused and the refusal's fix is the preview at `90d`.+- Committed receipts only, unless `--include-failures` (a failed receipt's+ error message is what `gbrain write-request` shows; the code and detail stay).+- A receipt of a run whose managed-sync cursor is still open, and the newest+ committed sync receipt of each worktree, are never compacted: a resumed run+ finds what it committed through them.+- The preview binds an absolute cutoff and the newest request it saw; the apply+ compacts only receipts of that set, each in its own short transaction+ (counters locked first, `lock_timeout` 2 s, `statement_timeout` 15 s), and a+ rerun of the same apply resumes after an interruption.+- No admission and no receipt of its own, so it runs at a full cap and its+ preview charges nothing. Brain-wide.++Verify with `gbrain doctor --only persistence_capacity --json`: the+`terminal_bytes` row drops by the bytes the apply freed.+<a id="projection-drain"></a>### Drain queued text projectionsdiff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 70bf7e306c..50a6dd732a 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -22,6 +22,7 @@ import { clearHealthMemo } from '../core/health-memo.ts';import { OperationError, opError } from '../core/ops/contract.ts';import { readFix } from '../core/ops/op-fix.ts';import { shellQuote } from '../core/agent-output.ts';+import { OLDER_THAN_RE } from '../cli/strict-args.ts';import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,@@ -63,6 +64,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--apply --expect <preview-hash> --yes] [--json]gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff][--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]+ gbrain repair receipt-compaction [--older-than <72h|30d>] [--include-failures] [--force]+ [--apply --expect <preview-hash> --yes] [--limit <n>] [--json]gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>])--prefer file|database [--apply --expect <preview-hash>] [--json]gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]@@ -117,17 +120,18 @@ Held files (the content lane, then the two-pass frontmatter repair): docs/guidesMalformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.`;-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted']);-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id']);+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id', '--older-than']);/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery'],'--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],+ '--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],};const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md','--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--keep': 'prior',- '--request-id': '123e4567-e89b-42d3-a456-426614174000' };+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d' };/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });@@ -135,7 +139,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbrainterface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string;- keep?: 'prior' | 'disk'; requestId?: string }+ keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean }/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {@@ -148,7 +152,7 @@ function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | und/** Strict parse: every flag is known, value flags carry a value, at most one kind. */export function parseRepairArgs(args: string[]): RepairArgs {const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],- allDrifted: false, requests: [] };+ allDrifted: false, requests: [], includeFailures: false, force: false };const used = new Set<string>();const positional: string[] = [];let maxUsdText: string | undefined;@@ -174,6 +178,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {else if (flag === '--yes') parsed.yes = true;else if (flag === '--no-llm') parsed.noLlm = true;else if (flag === '--all-drifted') parsed.allDrifted = true;+ else if (flag === '--include-failures') parsed.includeFailures = true;+ else if (flag === '--force') parsed.force = true;else parsed.noEmbed = true;continue;}@@ -193,6 +199,11 @@ export function parseRepairArgs(args: string[]): RepairArgs {}else if (flag === '--request') parsed.requests.push(value);else if (flag === '--class') parsed.driftClass = value;+ else if (flag === '--older-than') {+ if (!OLDER_THAN_RE.test(value)) throw invalid(`--older-than takes hours (72 or 72h) or days (30d) (got "${value}").`, 'Pass the age, e.g. --older-than 30d.',+ ['gbrain', 'repair', 'receipt-compaction', '--json']);+ parsed.olderThan = value;+ }else if (flag === '--keep') {if (value !== 'prior' && value !== 'disk') throw invalid(`--keep must be prior or disk (got "${value}").`,'Pass --keep prior to write the recorded prior bytes back, or --keep disk to keep the bytes on disk; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);@@ -280,7 +291,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,- prefer, requests, allDrifted, driftClass, keep, requestId } = parseRepairArgs(args);+ prefer, requests, allDrifted, driftClass, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');if (kind === CONTENT_LANE) {@@ -301,7 +312,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst scope = await resolveRepairScope(engine, source);if (apply && kind && expect && repairSpec(kind as RepairKind).consent === 'destructive') {const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),- ...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : [])];+ ...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : []),+ ...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : [])];const custom = repairSpec(kind as RepairKind).consentText;const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {what: `Rewrite the previewed ${kind} changes on disk and import them`,@@ -319,7 +331,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass } : {}),- ...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}) });+ ...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),+ ...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}) });results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 481f3bb0c6..ba81f59549 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { WRITE_SWITCHES, writeSwitchOn } from './switches.ts';import type { BrainEngine } from '../engine.ts';+import { getCode } from '../retry-matcher.ts';import { assertRecoveryStagingAbsent } from './staging.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';@@ -936,6 +937,21 @@ export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<numbreturn Number(requests?.rows ?? 0);}+/**+ * #6696 (A9): compaction drops the intent, and a sync receipt's `intent.runId`+ * is how a resumed run finds what it committed. A receipt of a run whose+ * managed-sync cursor is still open (not done) is never compacted, nor the newest+ * committed sync receipt of its worktree.+ */+export const OPEN_SYNC_CURSOR_EXCLUSION = (r: string) => `AND NOT (${r}.intent ? 'runId' AND EXISTS (SELECT 1 FROM op_checkpoints c+ WHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=${r}.intent->>'runId' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'))`;+export async function newestSyncReceipt(tx: SqlEngine, row: Pick<WriteRequest, 'id' | 'state' | 'intent' | 'worktree_id'>): Promise<boolean> {+ const intent = row.intent as { runId?: unknown; kind?: unknown } | null;+ if (row.state !== 'committed' || !row.worktree_id || typeof intent?.runId !== 'string' || !String(intent.kind ?? '').startsWith('managed_sync_')) return false;+ const [newest] = await tx.executeRaw<{ id: string }>(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND state='committed'+ AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%' ORDER BY completed_at DESC, sequence DESC LIMIT 1`, [row.worktree_id]);+ return newest?.id === row.id;+}/** What one compaction pass did (#6696 A11): receipts compacted, reservation bytes it freed, candidates it left and why. */export interface ReceiptCompactionResult { compacted: number; freed_bytes: number; skipped_by_reason: Record<string, number> }export async function compactWriteReceipts(engine: BrainEngine, retentionDays?: number): Promise<number> {@@ -950,27 +966,54 @@ export async function compactWriteReceiptsDetailed(engine: BrainEngine, retentioWHERE state IN ('committed','conflict','failed','cancelled') AND recovery IS NULL AND NOT compactedAND completed_at < now()-($1::double precision*interval '1 day')AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state<>'committed')+ ${OPEN_SYNC_CURSOR_EXCLUSION('r')}ORDER BY sequence LIMIT 100`, [retentionDays]);const result: ReceiptCompactionResult = { compacted: 0, freed_bytes: 0, skipped_by_reason: {} };- const skip = (reason: string) => { result.skipped_by_reason[reason] = (result.skipped_by_reason[reason] ?? 0) + 1; return 0; };- for(const row of rows) result.freed_bytes+=await engine.transaction(async tx=>{+ for (const row of rows) {+ const done = await compactReceipt(engine, row).catch(error => {+ if (['55P03', '57014'].includes(getCode(error) ?? '')) return { skipped: 'lock_timeout' };+ throw error;+ });+ if ('skipped' in done) result.skipped_by_reason[done.skipped] = (result.skipped_by_reason[done.skipped] ?? 0) + 1;+ else { result.compacted++; result.freed_bytes += done.freed_bytes; }+ }+ return result;+}+/** Terminal states a compaction may take; the receipt-compaction repair keeps failures unless asked. */+export const COMPACTABLE_STATES = ['committed', 'conflict', 'failed', 'cancelled'] as const;+/**+ * Compacts one terminal receipt in its own short transaction (#6696 A9, A11): counters locked first in key order, then+ * the request row, with transaction-local lock and statement timeouts so a concurrent admission waits at most that+ * long. Every eligibility rule is rechecked under the lock: terminal, no recovery, not compacted, `states`,+ * `completedBefore`, no unfinished effect, no open sync cursor for its run, not the worktree's newest sync receipt.+ */+export async function compactReceipt(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'principal_kind' | 'principal_id'>,+ opts: { states?: readonly string[]; completedBefore?: string } = {}): Promise<{ freed_bytes: number } | { skipped: string }> {+ return engine.transaction(async tx => {await declarePersistenceProtocol(tx);- const keys=['brain',principalKey(requestPrincipal(row))];- await lockCounters(tx,keys);- const [current]=await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE',[row.id]);- if(!current || current.compacted || current.recovery || !isTerminal(current)) return skip('changed');- const unfinished=await tx.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state<>'committed' LIMIT 1",[row.id]);- if(unfinished.length) return skip('unfinished_effect');- const [effects]=await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytes- FROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);- const retained=Math.min(Number(current.terminal_reservation),retainedReceiptBytes(current,{stage:'compacted',effects:Number(effects.bytes)}));- const freed=Number(current.terminal_reservation)-retained;- await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid',[row.id,retained]);- await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-LEAST($2::bigint,terminal_bytes) WHERE key=ANY($1::text[])',[keys,freed]);- result.compacted++;- return freed;+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");+ await tx.executeRaw("SET LOCAL statement_timeout = '15s'");+ const keys = ['brain', principalKey(requestPrincipal(row as WriteRequest))];+ await lockCounters(tx, keys);+ const [current] = await tx.executeRaw<WriteRequest & { eligible_age: boolean; open_cursor: boolean }>(`SELECT r.*,+ ($2::timestamptz IS NULL OR r.completed_at < $2::timestamptz) AS eligible_age,+ EXISTS (SELECT 1 FROM op_checkpoints c WHERE r.intent ? 'runId' AND c.op='managed-sync' AND c.completed_keys->0->>'runId'=r.intent->>'runId'+ AND COALESCE(c.completed_keys->0->>'done','false')<>'true') AS open_cursor+ FROM persistence_requests r WHERE r.id=$1::uuid FOR UPDATE OF r`, [row.id, opts.completedBefore ?? null]);+ if (!current || current.compacted || current.recovery || !isTerminal(current)) return { skipped: 'changed' };+ if (!(opts.states ?? COMPACTABLE_STATES).includes(current.state) || !current.eligible_age) return { skipped: 'changed' };+ const unfinished = await tx.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state<>'committed' LIMIT 1", [row.id]);+ if (unfinished.length) return { skipped: 'unfinished_effect' };+ if (current.open_cursor) return { skipped: 'open_sync_cursor' };+ if (await newestSyncReceipt(tx, current)) return { skipped: 'newest_sync_receipt' };+ const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytes+ FROM persistence_effects WHERE request_id=$1::uuid`, [row.id]);+ const retained = Math.min(Number(current.terminal_reservation), retainedReceiptBytes(current, { stage: 'compacted', effects: Number(effects.bytes) }));+ const freed = Number(current.terminal_reservation) - retained;+ await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid', [row.id, retained]);+ await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-LEAST($2::bigint,terminal_bytes) WHERE key=ANY($1::text[])', [keys, freed]);+ return { freed_bytes: freed };});- return result;}export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Date.now()) {return {diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex ddf5d3dbd7..e5fc942b41 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'receipt-compaction';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 8b10af682b..ddec179fd2 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'receipt-compaction'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -92,7 +92,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `file-drift` (#6643): the side that wins, conflict receipt ids, every still-drifted page, and the one drift class kept. */prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */- keep?: 'prior' | 'disk'; requestId?: string }+ keep?: 'prior' | 'disk'; requestId?: string;+ /** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */+ olderThan?: string; includeFailures?: boolean; force?: boolean }export interface RepairHandler {kind: RepairKind;@@ -272,7 +274,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sopts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;- keep?: 'prior' | 'disk'; requestId?: string;+ keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {@@ -293,7 +295,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}),- ...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}) };+ ...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),+ ...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/receipt-compaction.ts b/src/core/repair/receipt-compaction.tsnew file mode 100644index 0000000000..ac8f0bce82--- /dev/null+++ b/src/core/repair/receipt-compaction.ts@@ -0,0 +1,111 @@+/**+ * `gbrain repair receipt-compaction` (#6696 A9): compact terminal write+ * receipts now instead of waiting for the idle maintenance tick, so a brain+ * at its receipt-bytes cap gets its reservations back. Thin over the same+ * per-receipt compaction the consumer runs (`compactReceipt`, journal.ts):+ * the intent and error message are dropped, the outcome, error code and+ * detail stay, and the reservation shrinks to what the row keeps.+ *+ * Explicit-only, preview-bound and destructive. `--older-than` (hours `72h`+ * or days `30d`, the `pages purge-deleted` grammar) is floored at the+ * configured retention (`persistence.receipt_retention_days`) unless+ * `--force`; committed receipts only unless `--include-failures`. A receipt+ * of a run whose managed-sync cursor is still open, and the newest committed+ * sync receipt of each worktree, are never compacted. The preview binds the+ * selection (an absolute cutoff and the newest sequence it saw); the apply+ * compacts only receipts of that set, rechecking each under its lock.+ * `publication: 'projection'`: no admission, so the preview charges no+ * capacity. Brain-wide.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { OLDER_THAN_RE } from '../../cli/strict-args.ts';+import { COMPACTABLE_STATES, compactReceipt, OPEN_SYNC_CURSOR_EXCLUSION } from '../persistence/journal.ts';+import { readReceiptRetentionDays, RECEIPT_RETENTION_KEY } from '../persistence/limits.ts';+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';++interface Selection { cutoff: string; max_sequence: string; states: string[] }++/** `72h`, `72` (hours) or `30d` as hours; null when it does not parse. */+export function parseOlderThanHours(raw: string): number | null {+ if (!OLDER_THAN_RE.test(raw)) return null;+ const n = Number.parseInt(raw, 10);+ return raw.endsWith('d') ? n * 24 : n;+}++function command(opts: RepairPlanOptions): string {+ return ['gbrain repair receipt-compaction', ...(opts.olderThan ? ['--older-than', opts.olderThan] : []),+ ...(opts.includeFailures ? ['--include-failures'] : []), ...(opts.force ? ['--force'] : [])].join(' ');+}++async function selection(engine: BrainEngine, opts: RepairPlanOptions): Promise<Selection> {+ const retentionDays = await readReceiptRetentionDays(engine);+ const hours = opts.olderThan === undefined ? retentionDays * 24 : parseOlderThanHours(opts.olderThan);+ if (hours === null) throw new OperationError('invalid_params', `--older-than takes hours (72 or 72h) or days (30d) (got "${opts.olderThan}").`,+ `Pass the age in days, e.g. --older-than ${retentionDays}d; preview: gbrain repair receipt-compaction --older-than ${retentionDays}d --json`);+ if (hours < retentionDays * 24 && !opts.force) {+ throw Object.assign(new OperationError('invalid_params', `--older-than ${opts.olderThan} is inside the receipt retention window (${retentionDays} days, ${RECEIPT_RETENTION_KEY}), so nothing was compacted.`,+ `A retained receipt is how a caller replays a request id and reads its outcome in full. Preview the window's edge: gbrain repair receipt-compaction --older-than ${retentionDays}d --json. `+ + 'Compacting younger receipts drops their intent early; only with the user\'s agreement add --force.'), {+ fix: { argv: ['gbrain', 'repair', 'receipt-compaction', '--older-than', `${retentionDays}d`, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Previews compaction at the configured retention; it writes nothing.' } });+ }+ const [row] = await engine.executeRaw<{ cutoff: string; max_sequence: string | null }>(`SELECT to_char((now()-($1::double precision*interval '1 hour')) AT TIME ZONE 'UTC',+ 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS cutoff,(SELECT max(sequence)::text FROM persistence_requests) AS max_sequence`, [hours]);+ return { cutoff: row!.cutoff, max_sequence: row!.max_sequence ?? '0', states: opts.includeFailures ? [...COMPACTABLE_STATES] : ['committed'] };+}++async function candidates(engine: BrainEngine, sel: Selection) {+ return engine.executeRaw<{ id: string; request_id: string; sequence: string; source_id: string | null; principal_kind: string; principal_id: string;+ state: string; terminal_reservation: string }>(`SELECT r.id,r.request_id,r.sequence::text,r.source_id,r.principal_kind,r.principal_id,r.state,r.terminal_reservation::text+ FROM persistence_requests r+ WHERE r.state=ANY($1::text[]) AND r.recovery IS NULL AND NOT r.compacted AND r.completed_at < $2::timestamptz AND r.sequence <= $3::bigint+ AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state<>'committed')+ ${OPEN_SYNC_CURSOR_EXCLUSION('r')}+ AND r.id NOT IN (SELECT DISTINCT ON (worktree_id) id FROM persistence_requests WHERE state='committed' AND worktree_id IS NOT NULL+ AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%' ORDER BY worktree_id,completed_at DESC,sequence DESC)+ ORDER BY r.sequence`, [sel.states, sel.cutoff, sel.max_sequence]);+}++const toItem = (sel: Selection) => (row: Awaited<ReturnType<typeof candidates>>[number]): RepairItem => ({ cursor: { phase: 0, id: Number(row.sequence) },+ source_id: row.source_id ?? 'brain', slug: `receipt:${row.request_id}`, chars: 0, action: `compact_${row.state}`,+ change: { from: JSON.stringify({ id: row.id, principal_kind: row.principal_kind, principal_id: row.principal_id, states: sel.states, cutoff: sel.cutoff }), to: 'compacted' } });++const hashOf = (scope: RepairScope, sel: Selection) => previewHash({ kind: 'receipt-compaction-v1', brain_id: scope.brain_id, selection: sel });++export const receiptCompactionRepair: RepairHandler = {+ kind: 'receipt-compaction',+ publication: 'projection',+ embeds: false,+ outcomeItemsLimit: 0,+ async plan(engine, scope, after, opts = { apply: false }): Promise<RepairPlan> {+ const preview = command(opts);+ if (opts.apply) {+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair receipt-compaction --apply needs the preview hash.',+ `Preview first: ${preview} — then run the apply command it prints: ${preview} --apply --expect <preview-hash> --yes`, 'docs/guides/repair.md#receipt-compaction');+ const [sel] = (await loadApprovedSet<Selection>(engine, { command: 'receipt-compaction', hash: opts.expect, previewCommand: preview })).items;+ const items = (await candidates(engine, sel!)).map(toItem(sel!)).filter(item => afterCursor(item.cursor, after));+ if (!items.length) await clearApprovedSet(engine, { command: 'receipt-compaction', hash: opts.expect });+ return { items, preview_hash: opts.expect, residuals: {} };+ }+ const sel = await selection(engine, opts);+ const rows = await candidates(engine, sel);+ const hash = hashOf(scope, sel);+ await saveApprovedSet<Selection>(engine, { command: 'receipt-compaction', hash }, [sel]);+ const [failures] = opts.includeFailures ? [] : await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM persistence_requests+ WHERE state IN ('conflict','failed','cancelled') AND recovery IS NULL AND NOT compacted AND completed_at < $1::timestamptz`, [sel.cutoff]);+ return { items: rows.map(toItem(sel)), preview_hash: hash, residuals: Number(failures?.n ?? 0) ? { failures_kept: Number(failures!.n) } : {},+ details: { cutoff: sel.cutoff, states: sel.states, reserved_bytes: rows.reduce((n, row) => n + Number(row.terminal_reservation), 0) } };+ },+ async apply(ctx, item) {+ const row = JSON.parse(item.change!.from!) as { id: string; principal_kind: WriteRequest['principal_kind']; principal_id: string; states: string[]; cutoff: string };+ const done = await compactReceipt(ctx.engine, row, { states: row.states, completedBefore: row.cutoff });+ return 'skipped' in done ? { applied: false, outcome: done.skipped } : { applied: true, outcome: 'compacted', detail: { freed_bytes: done.freed_bytes } };+ },+ render(details) {+ const d = details as { cutoff?: string; states?: string[]; reserved_bytes?: number };+ return [` receipts completed before ${d.cutoff} (${d.states?.join(', ')}); they reserve ${d.reserved_bytes ?? 0} bytes now and keep their outcome, error code and detail`];+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex b3f5093ddd..6aa905dc4e 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -63,6 +63,7 @@ import { slugConflictsRepair } from './slug-conflicts.ts';import { frontmatterKeysRepair } from './frontmatter-keys.ts';import { fileDriftRepair } from './file-drift.ts';import { stuckRecoveryRepair } from './stuck-recovery.ts';+import { receiptCompactionRepair } from './receipt-compaction.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -293,6 +294,20 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'bytes back and the accepted write publishes again, disk keeps the edit and abandons the write (reconcile the page afterwards). A terminal request is '+ 'refused (recovery_choice_refused). Runs only when named.',},+ 'receipt-compaction': {+ handler: receiptCompactionRepair, embeds: 'none', checks: ['persistence_capacity'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: {+ what: 'Compact the previewed terminal write receipts now',+ why: 'The preview selected terminal receipts older than the cutoff it printed; compacting them drops each one\'s intent and error message and returns its unused receipt bytes to the capacity counters.',+ risk: 'Database rows only. A compacted receipt still answers its request id with its outcome, error code and detail, but its original intent is gone and cannot be restored. Open sync runs and the newest sync receipt of each worktree are never touched.',+ user_message: 'Compact the previewed write receipts? Their original request bodies are dropped for good; outcomes stay',+ },+ summary: 'Compact terminal write receipts now instead of waiting for idle maintenance (#6696), returning their unused receipt bytes. Same compaction as the '+ + 'consumer: the intent and error message go, the outcome, error code and detail stay. --older-than <72h|30d> is floored at the configured retention '+ + '(persistence.receipt_retention_days) unless --force; committed receipts only unless --include-failures. Receipts of a run whose sync cursor is '+ + 'open, and the newest sync receipt per worktree, are kept. Preview-bound and destructive: --apply --expect <hash> --yes compacts only the '+ + 'previewed set. No admission, so it runs at a full cap. Brain-wide. Runs only when named.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));@@ -377,14 +392,15 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;- keep?: 'prior' | 'disk'; requestId?: string } = {}): Promise<RepairResult> {+ keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,- embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],+ embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),+ ...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : [])],explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass,- keep: run.keep, requestId: run.requestId });+ keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force });},};}diff --git a/test/repair-receipt-compaction.test.ts b/test/repair-receipt-compaction.test.tsnew file mode 100644index 0000000000..99af6a0884--- /dev/null+++ b/test/repair-receipt-compaction.test.ts@@ -0,0 +1,126 @@+/**+ * #6696 (A9): `gbrain repair receipt-compaction` compacts terminal receipts on+ * demand. `--older-than` is floored at the configured retention unless+ * `--force` (retention 90 days: a 30-day request is refused, and the refusal's+ * fix is the preview at the floor); failures stay unless+ * `--include-failures`; a receipt of a run whose sync cursor is open is never+ * compacted. Refusal -> preview -> apply -> verify through the fix objects; an+ * interrupted apply resumes; an admission racing the apply waits under 1 s.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { repairRunner, repairSpec } from '../src/core/repair/registry.ts';+import { parseRepairArgs } from '../src/commands/repair.ts';+import { parseOlderThanHours } from '../src/core/repair/receipt-compaction.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { editRequest, freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;++test('flags parse with the purge-deleted duration grammar and belong to receipt-compaction only', () => {+ expect(parseRepairArgs(['receipt-compaction', '--older-than', '90d', '--include-failures', '--force'])).toMatchObject({ kind: 'receipt-compaction', olderThan: '90d', includeFailures: true, force: true });+ expect(() => parseRepairArgs(['receipt-compaction', '--older-than', '3w'])).toThrow(/hours \(72 or 72h\) or days \(30d\)/);+ expect(() => parseRepairArgs(['timeline', '--older-than', '30d'])).toThrow(/applies only to gbrain repair receipt-compaction/);+ expect([parseOlderThanHours('72'), parseOlderThanHours('72h'), parseOlderThanHours('30d'), parseOlderThanHours('x')]).toEqual([72, 72, 720, null]);+ expect(repairSpec('receipt-compaction')).toMatchObject({ explicit_only: true, preview_bound: true, consent: 'destructive' });+ expect(repairSpec('receipt-compaction').handler.publication).toBe('projection');+});++for (const kind of testBackends()) {+ describe(`receipt-compaction repair ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-receipt-compaction-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });++ test('refusal -> preview -> apply -> verify; failures and open sync runs kept; an interrupted apply resumes', () => withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const engine: BrainEngine = await factory.fresh();+ const requests = await requestFixture(engine);+ const terminal = async (slug: string, state: 'committed' | 'failed', days: number, intent?: Record<string, unknown>) => {+ const row = await requests.admit(slug);+ await editRequest(engine, row.id, `state=$2,completed_at=now()-($3::double precision*interval '1 day'),published_at=now(),claim_expires_at=NULL+ ${state === 'failed' ? ",error_code='source_changed',error_message='the file moved'" : ''}${intent ? ',intent=$4::text::jsonb' : ''}`,+ [state, days, ...(intent ? [JSON.stringify(intent)] : [])]);+ await engine.executeRaw('DELETE FROM persistence_effects WHERE request_id=$1::uuid', [row.id]);+ return row.id;+ };+ const old = await terminal('old', 'committed', 100);+ const month = await terminal('month', 'committed', 40);+ const failed = await terminal('failed', 'failed', 100);+ const open = await terminal('open-run', 'committed', 100, { kind: 'managed_sync_import', runId: 'run-open-example', content: 'x' });+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync','cursor-example',$1::text::jsonb)`,+ [JSON.stringify([{ runId: 'run-open-example', done: false }])]);+ await engine.setConfig('persistence.receipt_retention_days', '90');+ const row = async (id: string) => (await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id]))[0]!;+ const bytes = async () => Number((await engine.executeRaw<{ n: string }>("SELECT terminal_bytes::text AS n FROM persistence_counters WHERE key='brain'"))[0]!.n);+ const scope = await resolveRepairScope(engine, undefined);+ const run = (apply: boolean, args: { olderThan?: string; force?: boolean; includeFailures?: boolean; expect?: string; limit?: number }) =>+ repairRunner(engine, { apply }).then(runner => runner.run('receipt-compaction', scope, { explicit: true, ...args }));++ // 30 days inside a 90-day retention: refused, and the fix is the preview at the floor.+ const refusal = await run(false, { olderThan: '30d' }).then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'repair', 'receipt-compaction', '--older-than', '90d', '--json'] } });+ const floor = await run(false, { olderThan: refusal.fix.argv[4] });+ expect(floor).toMatchObject({ affected: 1, residuals: { failures_kept: 1 }, cost: { lifetime_ids: 0, receipt_bytes: 0 } });+ expect(floor.sample).toEqual([`${requests.sourceId}:receipt:${(await row(old)).request_id}`]);+ expect((await run(false, { olderThan: '90d', includeFailures: true })).affected).toBe(2);++ // --force reaches inside the window; the apply is bound to the preview and resumes after an interruption.+ const preview = await run(false, { olderThan: '30d', force: true });+ expect(preview.affected).toBe(2);+ expect(preview.apply_command).toBe(`gbrain repair receipt-compaction --older-than 30d --force --apply --expect ${preview.preview_hash} --yes`);+ const before = await bytes();+ const reserved = Number((await row(old)).terminal_reservation) + Number((await row(month)).terminal_reservation);+ const first = await run(true, { olderThan: '30d', force: true, expect: preview.preview_hash, limit: 1 });+ expect(first).toMatchObject({ applied: 1, complete: false });+ const second = await run(true, { olderThan: '30d', force: true, expect: preview.preview_hash });+ expect(second).toMatchObject({ applied: 1, outcomes: { compacted: 1 } });+ expect(second.resumed_from).not.toBeNull();+ for (const id of [old, month]) expect(await row(id)).toMatchObject({ compacted: true, intent: null });+ for (const id of [failed, open]) expect((await row(id)).compacted).toBe(false);+ const kept = Number((await row(old)).terminal_reservation) + Number((await row(month)).terminal_reservation);+ expect(kept).toBeLessThan(reserved);+ expect(before - await bytes()).toBe(reserved - kept);+ // Verify: the same preview now finds nothing.+ expect((await run(false, { olderThan: '30d', force: true })).affected).toBe(0);+ // The open run's cursor finishes: its receipt becomes compactable.+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$1::text::jsonb WHERE op='managed-sync' AND fingerprint='cursor-example'",+ [JSON.stringify([{ runId: 'run-open-example', done: true }])]);+ expect((await run(false, { olderThan: '90d' })).affected).toBe(1);+ }), 120_000);++ test('an admission racing the apply waits under a second', () => withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const engine: BrainEngine = await factory.fresh();+ const requests = await requestFixture(engine);+ for (let i = 0; i < 40; i++) {+ const row = await requests.admit(`bulk-${i}`);+ await editRequest(engine, row.id, "state='committed',completed_at=now()-interval '60 days',published_at=now(),claim_expires_at=NULL");+ await engine.executeRaw('DELETE FROM persistence_effects WHERE request_id=$1::uuid', [row.id]);+ }+ const scope = await resolveRepairScope(engine, undefined);+ const preview = await (await repairRunner(engine, { apply: false })).run('receipt-compaction', scope, { explicit: true });+ expect(preview.affected).toBe(40);+ const apply = (await repairRunner(engine, { apply: true })).run('receipt-compaction', scope, { explicit: true, expect: preview.preview_hash });+ const latencies: number[] = [];+ for (let i = 0; i < 5; i++) {+ const started = performance.now();+ await requests.admit(`racing-${i}`);+ latencies.push(performance.now() - started);+ }+ expect((await apply).applied).toBe(40);+ expect(Math.max(...latencies)).toBeLessThan(1000);+ }), 120_000);+ });+}