Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): stuck-recovery resolves withdrawal-mirror effect and skill-bundle recoveries

garrytana4e01b1ef375
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 9a8b4639f4..bf4d425278 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -72,7 +72,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>])
[--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]
gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
- [--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
+ [--keep prior|disk|withdrawn --apply --expect <preview-hash> --yes] [--json]
gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]
gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
[--apply --expect <preview-hash> --yes]] [--json]
@@ -119,8 +119,9 @@ Options:
model-tier items stay held with llm_disabled.
--max-usd <n> Kinds that may call a paid model (${llmKinds}) and the content lane: spend at most n USD on the
model in this run. It only lowers the cap (the daily fences.repair cap still applies); never raises it.
- --keep prior|disk
- stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).
+ --keep prior|disk|withdrawn
+ stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview;
+ withdrawn is a withdrawal-mirror effect's only choice).
--request-id <uuid>
stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).
--yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, rename-identity --apply: the user agreed to the previewed changes (destructive
@@ -156,7 +157,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbra
interface 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; since?: string;
- keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean }
+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: 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 {
@@ -271,8 +272,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {
`Preview it by name: gbrain repair ${kinds[kinds.length - 1]}${parsed.source ? ` --source ${parsed.source}` : ''}`);
}
if (keepText !== undefined) {
- if (keepText !== 'prior' && keepText !== 'disk') throw invalid(`--keep must be prior or disk (got "${keepText}").`,
- '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']);
+ if (keepText !== 'prior' && keepText !== 'disk' && keepText !== 'withdrawn') throw invalid(`--keep must be prior, disk or withdrawn (got "${keepText}").`,
+ 'Pass --keep prior to write the recorded prior bytes back, --keep disk to keep the bytes on disk, or --keep withdrawn to write a withdrawal mirror\'s withdrawn bytes; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
parsed.keep = keepText;
}
const llmKind = LLM_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind) || parsed.kind === CONTENT_LANE;
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index d1706ca832..d38cd59464 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -554,6 +554,23 @@ const GIT_GROUP_SIZE = 100;
const GIT_YIELD_ATTEMPTS = 20;
const GIT_YIELD_MS = 250;
+/**
+ * Claims one effect recovery and finishes it forward (`recoverEffectPublication`); a failure is recorded on the effect,
+ * whose record stays. The caller holds the worktree's native lock: any old process holding it has exited, so no lease
+ * timeout is needed and no second process can steal this claim. Returns the claimed row, or undefined when the effect
+ * no longer holds a recovery record.
+ */
+export async function claimAndRecoverEffect(engine: BrainEngine, id: string | number, hostId: string,
+ hooks: Parameters<typeof recoverEffectPublication>[3] = {}): Promise<PersistenceEffect | undefined> {
+ let claimed: PersistenceEffect | undefined;
+ try {
+ [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
+ claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID()]);
+ if (claimed) await recoverEffectPublication(engine, claimed, hostId, hooks);
+ } catch (error) { if (claimed) await recordFailure(engine, claimed, error); }
+ return claimed;
+}
+
/**
* Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim.
* Resolves with the number of effects attempted, so a caller can keep draining.
@@ -575,15 +592,10 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
if (!binding) continue;
const lock = await acquireWorktree(binding, 0, undefined, engine);
if (!lock) continue;
- let claimed: PersistenceEffect | undefined;
try {
- // Any old process holding this native lock has exited. No lease timeout
- // can provide that proof and no second process can steal this claim now.
- [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
- claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [recovery.id, randomUUID()]);
- if (claimed) { attempted++; touched.add(claimed.request_id); await recoverEffectPublication(engine, claimed, opts.hostId, opts); }
- } catch (error) { if (claimed) await recordFailure(engine, claimed, error); }
- finally { await lock.release(); }
+ const claimed = await claimAndRecoverEffect(engine, recovery.id, opts.hostId, opts);
+ if (claimed) { attempted++; touched.add(claimed.request_id); }
+ } finally { await lock.release(); }
}
const run = async (claimed: PersistenceEffect, binding: WorktreeBinding | null, hardened?: boolean) => {
let effect = claimed;
diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.ts
index ce6bcb043c..e0f64bff99 100644
--- a/src/core/persistence/recovery-resolve.ts
+++ b/src/core/persistence/recovery-resolve.ts
@@ -1,42 +1,52 @@
/**
- * `gbrain repair stuck-recovery` (#6650 §1.10, #6640 §B): resolve a page publication recovery that the owner's
- * recovery pass refuses with `unexpected_file_bytes` (a canonical file matches neither its recorded prior nor its
+ * `gbrain repair stuck-recovery` (#6650 §1.10, #6640 §B; GBRA-130 C-1, C-4): resolve a publication recovery that the
+ * owner's recovery pass refuses with `unexpected_file_bytes` (a canonical file matches neither its recorded prior nor its
* published bytes, usually a human edit made while the write was publishing). Until it is resolved its worktree
- * claims nothing, and the resident consumer re-parks it every 30 s.
+ * claims nothing, and the resident consumer re-parks it every 30 s. Three record kinds resolve: a page write's
+ * recovery, a shared-skill bundle publication's (version 2, every file of the bundle) and a withdrawal-mirror effect's.
*
* The preview starts from the head blocker's `request_recovery` ids (the recovery records on the source's
- * worktree), lists every file of each record with its prior and disk fingerprints, and writes a private diff of the
- * two into the owner host's backup directory. Its hash binds each record's identity, each file's disk bytes and the
- * page's database revision.
+ * worktree) plus every effect recovery on it, lists every file of each record with its recorded and disk
+ * fingerprints, and writes a private diff of the two into the owner host's backup directory. Its hash binds each
+ * record's identity, each file's disk bytes and the page's database revision.
*
* Only a live (non-terminal) request is resolved: its database transaction never committed, so neither choice rolls back
* committed bytes. `--keep prior` writes the prior bytes back through the coordinator's confined durable publication
* (`publishPersistenceFile`, staged at the record's reserved restoration path, which `upgradeRecoveryStaging` reserves
* and accounts for older records) and recovery finishes by its own rule (a request with no recorded failure is requeued
- * and its write publishes again; one with a failure ends terminal). `--keep disk` (#6640's `drop`) keeps the edited
- * bytes and abandons the publication: it completes the request terminal (`completeWrite`; `source_changed`, so
- * `conflict`, when it recorded no failure, else that failure by the owner's rule via `finishUnpublishedFailure`), and
- * recovery's terminal path then only cleans its staging and clears the record (`clearResolvedRecovery`), releasing its
- * reserved bytes. The record is never rewritten, so no recovery bytes move outside the accounting.
+ * and its write publishes again; one with a failure ends terminal; recovery restores every other file of a bundle).
+ * `--keep disk` (#6640's `drop`) keeps the bytes on disk (every file of a bundle) and abandons the publication: it
+ * completes the request terminal (`completeWrite`; `source_changed`, so `conflict`, when it recorded no failure, else
+ * that failure by the owner's rule via `finishUnpublishedFailure`), and recovery's terminal path then only cleans its
+ * staging and clears the record (`clearResolvedRecovery`), releasing its reserved bytes. The record is never rewritten,
+ * so no recovery bytes move outside the accounting.
* A terminal request whose recovery record is still set is refused (`recovery_choice_refused`): its outcome is immutable,
- * recovery never restores its canonical file, and `--keep prior` would roll back a committed write. A withdrawal-mirror
- * effect recovery blocking the worktree is listed as refused (`recovery_effect_unsupported`): it only finishes forward,
- * and either choice could put withdrawn content back on disk. So is a page recovery whose prior file is over the
- * single-string ceiling (`recovery_large_file_unsupported`: its diff would read both files whole), when it is blocked on
- * unexpected bytes or its file (hashed in pieces) matches neither recorded version.
+ * recovery never restores its canonical file, and `--keep prior` would roll back a committed write. So is a page
+ * recovery whose prior file is over the single-string ceiling (`recovery_large_file_unsupported`: its diff would read
+ * both files whole), when it is blocked on unexpected bytes or its file (hashed in pieces) matches neither recorded
+ * version, and a bundle record this binary cannot read (`recovery_bundle_unsupported`).
+ *
+ * A withdrawal-mirror effect only finishes forward: its withdrawal is committed, and keeping the edited file (or the
+ * pre-withdrawal bytes) would leave the forgotten fact on disk for the next sync to import again. Its only choice is
+ * `--keep withdrawn`: the edited bytes are backed up, the recorded post-withdrawal bytes are written through the
+ * record's reserved publication stage, and the effect's own `recoverEffectPublication` finishes it. A record without
+ * usable post-withdrawal bytes (or bound to another owner, root or incarnation) stays refused
+ * (`recovery_effect_unsupported`) with an ask_user fix naming the exact preview.
*
* The apply runs on the owner host under the worktree lock, so the resident recovery pass cannot interleave. Each
- * record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by request and preview
- * hash): `backed_up` (the disk and prior bytes are in the backup directory, always), then `written` (`--keep
- * prior`: the prior bytes are back on disk, an absent prior unlinked) or `abandoned` (`--keep disk`: the request is
- * terminal), then `done` once `recoverPublication` finished it by its unchanged rule. Every step is idempotent, so a
- * run killed at any boundary resumes, and an older resident consumer can finish a resolution this command started.
- * The finished journal row is the resolution's audit entry; a terminal receipt is never rewritten.
+ * record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by record and preview
+ * hash): `backed_up` (the disk and recorded bytes are in the backup directory, always), then `written` (`--keep
+ * prior`: the prior bytes are back on disk, an absent prior unlinked; `--keep withdrawn`: the withdrawn bytes are on
+ * disk) or `abandoned` (`--keep disk`: the request is terminal), then `done` once the owner's recovery finished it by
+ * its unchanged rule. Every step is idempotent, so a run killed at any boundary resumes, and an older resident consumer
+ * can finish a resolution this command started. The finished journal row is the resolution's audit entry; a terminal
+ * receipt is never rewritten.
*/
-import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
-import { dirname, join, relative } from 'node:path';
+import { chmodSync, closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { catalogueError } from '../error-catalogue.ts';
@@ -50,8 +60,12 @@ import { localHostId } from './identity.ts';
import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { completeWrite, getWriteRequestById } from './journal.ts';
-import { isTerminal, recoveryFiles, type FileRecoveryRecord, type WriteRequest } from './model.ts';
+import { isTerminal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
+import type { EffectRecovery } from './effect-model.ts';
import { finishUnpublishedFailure, publishPersistenceFile, recoverPublication, transientDatabaseFailure } from './coordinator.ts';
+import { claimAndRecoverEffect } from './effects.ts';
+import { trueUpRequests } from './receipt-true-up.ts';
+import { bundleFileHash } from './bundle-files.ts';
import { mayReprepare } from './semantic.ts';
import { cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';
import { hashFile } from './large-file.ts';
@@ -62,7 +76,10 @@ import { faultPoint } from './fault-points.ts';
import { KEEP_DISK_ABANDONED_PREFIX } from './verb-errors.ts';
export const RESOLUTION_OP = 'stuck-recovery-resolution';
-export type KeepChoice = 'prior' | 'disk';
+export type KeepChoice = 'prior' | 'disk' | 'withdrawn';
+export const KEEP_CHOICES: readonly KeepChoice[] = ['prior', 'disk', 'withdrawn'];
+/** What the record publishes: one page file, every file of a shared-skill bundle, or a withdrawal mirror of a page file. */
+export type RecoveryTarget = 'page' | 'skill_bundle' | 'withdrawal_mirror';
export type PriorView = { absent: true } | { absent: false; sha256: string; size: number | null; mode: number | null; stored: boolean };
export type DiskView = { deleted: true } | { deleted: false; kind: 'file' | 'symlink' | 'directory' | 'other'; sha256: string | null; size: number; mode: number };
@@ -70,13 +87,17 @@ export interface RecoveryFileView {
path: string; root: string; relative: string; prior: PriorView; disk: DiskView;
/** What recovery itself makes of the disk bytes: the prior, the published bytes, or neither (the blocked case). */
matches: 'prior' | 'published' | 'neither';
+ /** A withdrawal-mirror effect only: the recorded post-withdrawal bytes `--keep withdrawn` writes (`prior` is the pre-withdrawal file). */
+ withdrawn?: { sha256: string; size: number };
/** Preview only: the private diff and the command that reproduces it (absent for a remote caller). */
diff_path?: string; diff_command?: string;
}
/** The identity the hash binds: the publication attempt, its owner epoch and each file's path and published hash. */
export interface RecoveryIdentity { attempt: string; owner_epoch: string; files: Array<{ path: string; after_hash: string | null }> }
export interface StuckRecovery {
- id: string; request_id: string; source_id: string; slug: string; operation: string; state: string; blocked_reason: string | null;
+ /** The request's internal id, or `effect:<id>` for a withdrawal-mirror effect recovery. */
+ id: string; target: RecoveryTarget; effect_id?: string;
+ request_id: string; source_id: string; slug: string; operation: string; state: string; blocked_reason: string | null;
worktree_id: string; sequence: string; page_revision: string | null; identity: RecoveryIdentity;
/** The failure the request already recorded, if any: with one, either choice ends the request terminal with it. */
recorded_error: string | null;
@@ -86,11 +107,13 @@ export interface StuckRecovery {
digest: string;
}
/**
- * A blocked terminal request, a withdrawal-mirror effect recovery or a page recovery whose prior file is over the
- * single-string ceiling: listed, never resolved (see the module comment).
+ * A blocked terminal request, an unusable withdrawal-mirror effect or bundle record, or a page recovery whose prior file
+ * is over the single-string ceiling: listed, never resolved (see the module comment).
*/
-export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_large_file_unsupported'; request_id: string; source_id: string; slug: string; state: string;
- blocked_reason: string | null; reason: string; effect_id?: string }
+export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_large_file_unsupported' | 'recovery_bundle_unsupported';
+ request_id: string; source_id: string; slug: string; state: string; blocked_reason: string | null; reason: string; effect_id?: string;
+ /** The next step when it is not the read-only writer status: an ask_user action naming the exact preview. */
+ fix?: Action }
export interface StuckRecoveryScan { items: StuckRecovery[]; residuals: Record<string, number>; refused: RefusedRecovery[];
heads: Array<{ source_id: string; queued_request_id: string | null; blocked_by: string | null }> }
@@ -103,17 +126,29 @@ export interface ResolutionResult {
outcome: 'resolved' | 'still_blocked'; keep: KeepChoice; request_state: string; blocked_reason: string | null;
finished_by: 'this_run' | 'another_pass'; backup_dir: string; next: string;
}
+interface EffectRow { id: string; request_ref: string; request_id: string | null; kind: string; state: string; error_code: string | null; worktree_id: string;
+ recovery: EffectRecovery | null }
+/** What `writeArtifacts` compares each disk file against: the recorded prior bytes, or a mirror's withdrawn bytes. */
+type Reference = { label: 'prior' | 'withdrawn'; bytes: Buffer | null };
const statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s canonical owner with its recovering write requests, read-only.`,
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
-export const stuckRecoveryPreviewCommand = (sourceIds: string[], requestId?: string) =>
- `gbrain repair stuck-recovery${sourceIds.length === 1 ? ` --source ${sourceIds[0]}` : ''}${requestId ? ` --request-id ${requestId}` : ''}`;
+export const stuckRecoveryPreviewArgv = (sourceIds: string[], requestId?: string) =>
+ ['gbrain', 'repair', 'stuck-recovery', ...(sourceIds.length === 1 ? ['--source', sourceIds[0]!] : []), ...(requestId ? ['--request-id', requestId] : [])];
+export const stuckRecoveryPreviewCommand = (sourceIds: string[], requestId?: string) => stuckRecoveryPreviewArgv(sourceIds, requestId).join(' ');
const backupRoot = () => gbrainPath('backups', 'stuck-recovery');
const fileMode = (mode: number) => mode & 0o777;
function identityOf(files: FileRecoveryRecord[], record: { attempt: string; ownerEpoch: string }): RecoveryIdentity {
return { attempt: record.attempt, owner_epoch: String(record.ownerEpoch), files: files.map(file => ({ path: file.path, after_hash: file.afterHash })) };
}
+function effectIdentity(effectId: string, record: EffectRecovery): RecoveryIdentity {
+ return { attempt: `effect:${effectId}:${record.revision}`, owner_epoch: String(record.ownerEpoch), files: [{ path: record.path, after_hash: record.afterHash }] };
+}
+/** The record's files, or null for a bundle record this binary cannot read. */
+function filesOf(record: RecoveryRecord): FileRecoveryRecord[] | null {
+ try { return recoveryFiles(record); } catch { return null; }
+}
function diskView(path: string): { view: DiskView; bytes: Buffer | null } {
let stat;
@@ -122,6 +157,7 @@ function diskView(path: string): { view: DiskView; bytes: Buffer | null } {
const bytes = readFileSync(path);
return { view: { deleted: false, kind: 'file', sha256: sha256(bytes), size: bytes.length, mode: fileMode(stat.mode) }, bytes };
}
+const diskHash = (view: DiskView) => view.deleted ? null : view.sha256;
function priorBytes(record: FileRecoveryRecord): Buffer | null { return record.before === null ? null : Buffer.from(record.before, 'base64'); }
function priorView(record: FileRecoveryRecord): PriorView {
@@ -161,50 +197,97 @@ function writePrivateFile(path: string, bytes: Buffer): void {
`Nothing was changed on disk or in the journal. Check free space and the filesystem under ${dirname(path)}, then run the same command again.`);
}
-/** Prior and disk bytes of every unexpected file (and their diff) under `dir`; returns the paths by file index. */
-function writeArtifacts(dir: string, item: { files: RecoveryFileView[] }, records: FileRecoveryRecord[], disks: Array<Buffer | null>) {
- return item.files.map((file, index) => {
- const prior = priorBytes(records[index]);
- const priorPath = prior === null ? null : join(dir, `${index}.prior`);
+/** Each file's recorded and disk bytes (and their diff) under `dir`; returns the diff paths by file index. */
+function writeArtifacts(dir: string, files: RecoveryFileView[], references: Reference[], disks: Array<Buffer | null>) {
+ return files.map((file, index) => {
+ const { label, bytes } = references[index]!;
+ const referencePath = bytes === null ? null : join(dir, `${index}.${label}`);
const diskPath = disks[index] === null ? null : join(dir, `${index}.disk`);
- if (priorPath) writePrivateFile(priorPath, prior!);
+ if (referencePath) writePrivateFile(referencePath, bytes!);
if (diskPath) writePrivateFile(diskPath, disks[index]!);
const diffPath = join(dir, `${index}.diff`);
- writePrivateFile(diffPath, Buffer.from(unifiedDiff(prior?.toString('utf8') ?? '', disks[index]?.toString('utf8') ?? '',
- { oldPath: `prior/${file.relative}`, newPath: `disk/${file.relative}` })));
- return { diff_path: diffPath, diff_command: `diff -u ${priorPath ?? '/dev/null'} ${diskPath ?? '/dev/null'}` };
+ writePrivateFile(diffPath, Buffer.from(unifiedDiff(bytes?.toString('utf8') ?? '', disks[index]?.toString('utf8') ?? '',
+ { oldPath: `${label}/${file.relative}`, newPath: `disk/${file.relative}` })));
+ return { diff_path: diffPath, diff_command: `diff -u ${referencePath ?? '/dev/null'} ${diskPath ?? '/dev/null'}` };
});
}
+const priorReferences = (records: FileRecoveryRecord[]): Reference[] => records.map(record => ({ label: 'prior', bytes: priorBytes(record) }));
+
+/** What recovery makes of a file's disk bytes; a bundle file also needs its recorded mode and a regular, unaliased file. */
+function recoveryMatch(record: FileRecoveryRecord, view: DiskView, bundle: boolean): RecoveryFileView['matches'] {
+ if (!view.deleted && view.kind !== 'file') return 'neither';
+ const hash = diskHash(view);
+ const match = hash === record.beforeHash ? 'prior' : hash === record.afterHash ? 'published' : 'neither';
+ if (match === 'neither' || !bundle) return match;
+ try { bundleFileHash(record); return match; } catch (error) {
+ if (error instanceof OperationError && ['unexpected_file_bytes', 'storage_error'].includes(error.code)) return 'neither';
+ throw error;
+ }
+}
-/** One record's current view: its files with disk fingerprints, the page revision and the state digest. */
+/** One page or bundle record's current view: its files with disk fingerprints, the page revision and the state digest. */
async function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; disks: Array<Buffer | null> }> {
- if (row.recovery?.version === 2) throw catalogueError('recovery_bundle_unsupported', `Request ${row.request_id} in source ${row.source_id} is a shared-skill bundle recovery, which gbrain repair stuck-recovery does not resolve.`,
- `Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of each skill file to keep; resolve the bundle by hand, then let the resident writer finish its recovery.`);
if (row.recovery?.version === 1 && row.recovery.staging?.before) throw catalogueError('recovery_large_file_unsupported', largeFileReason(row),
`Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of the file to keep; its prior bytes are the staged copy the record names. Put the chosen bytes in place by hand, then let the resident writer finish its recovery.`);
- const records = recoveryFiles(row.recovery!);
+ const records = filesOf(row.recovery!);
+ if (!records) throw refusalError(bundleRefusal(row));
+ const bundle = row.recovery!.version === 2;
const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
const disks: Array<Buffer | null> = [];
const files = records.map(record => {
const contained = isWriteTargetContained(record.path, record.root) && !!binding.local_path && isWriteTargetContained(record.path, binding.local_path);
const { view, bytes } = contained ? diskView(record.path) : { view: { deleted: false, kind: 'other', sha256: null, size: 0, mode: 0 } as DiskView, bytes: null };
disks.push(bytes);
- const hash = view.deleted ? null : view.sha256;
- const matches = (view.deleted || view.kind === 'file') && hash === record.beforeHash ? 'prior' : (view.deleted || view.kind === 'file') && hash === record.afterHash ? 'published' : 'neither';
- return { path: record.path, root: record.root, relative: relative(binding.local_path ?? record.root, record.path), prior: priorView(record), disk: view, matches } as RecoveryFileView;
+ return { path: record.path, root: record.root, relative: relative(binding.local_path ?? record.root, record.path), prior: priorView(record), disk: view,
+ matches: recoveryMatch(record, view, bundle) } as RecoveryFileView;
});
const writable = (file: RecoveryFileView) => file.disk.deleted || file.disk.kind === 'file';
const unexpected = files.filter(file => file.matches === 'neither');
- const choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(writable) };
+ const choices = { prior: unexpected.every(file => writable(file) && (file.prior.absent || file.prior.stored)), disk: unexpected.every(writable), withdrawn: false };
const identity = identityOf(records, row.recovery!);
const page_revision = page?.revision ?? null;
- return { records, disks, item: { id: row.id, request_id: row.request_id, source_id: row.source_id, slug: row.slug, operation: row.operation, state: row.state,
+ return { records, disks, item: { id: row.id, target: bundle ? 'skill_bundle' : 'page', request_id: row.request_id, source_id: row.source_id, slug: row.slug, operation: row.operation, state: row.state,
blocked_reason: row.blocked_reason ?? null, worktree_id: row.worktree_id!, sequence: String(row.sequence),
page_revision, identity, recorded_error: row.error_code ?? null, prior_hashes: records.map(record => record.beforeHash), files, choices,
digest: digest({ v: 'stuck-recovery-item-v1', id: row.id, request_id: row.request_id, identity, prior_hashes: records.map(record => record.beforeHash),
disk: files.map(file => file.disk), page_revision }) } };
}
+const EFFECT_SQL = `SELECT e.id::text AS id, e.request_id::text AS request_ref, r.request_id::text AS request_id, e.kind, e.state, e.error_code,
+ e.worktree_id::text AS worktree_id, e.recovery FROM persistence_effects e LEFT JOIN persistence_requests r ON r.id=e.request_id`;
+
+/**
+ * One withdrawal-mirror effect recovery's view: null when its file holds a recorded version (it recovers on its own),
+ * a refusal when the record cannot be written forward on this binding, else the item with its withdrawn and disk bytes.
+ */
+async function readEffectItem(engine: BrainEngine, effect: EffectRow, binding: WorktreeBinding, sourceId: string):
+Promise<{ item: StuckRecovery; reference: Buffer; disk: Buffer | null } | RefusedRecovery | null> {
+ const record = effect.recovery;
+ const slug = typeof record?.slug === 'string' ? record.slug : '';
+ const refused: RefusedRecovery = { code: 'recovery_effect_unsupported', request_id: effect.request_id ?? '', effect_id: effect.id, source_id: sourceId, slug,
+ state: effect.state, blocked_reason: effect.error_code, reason: effectReason(effect.kind), fix: effectFix(sourceId, effect.request_id) };
+ if (!record || effect.kind !== 'withdrawal-mirror' || record.kind !== 'withdrawal-mirror' || typeof record.after !== 'string' || typeof record.afterHash !== 'string'
+ || typeof record.path !== 'string' || typeof record.root !== 'string' || !binding.local_path) return refused;
+ const after = Buffer.from(record.after, 'base64');
+ if (sha256(after) !== record.afterHash || record.ownerEpoch !== String(binding.owner_epoch) || record.sourceIncarnation !== binding.source_incarnation
+ || !isWriteTargetContained(record.path, record.root) || !isWriteTargetContained(record.path, binding.local_path)
+ || resolve(record.root) !== resolve(join(binding.local_path, binding.relative_path))) return refused;
+ const { view, bytes } = diskView(record.path);
+ const regular = !view.deleted && view.kind === 'file';
+ if (regular && (diskHash(view) === record.beforeHash || diskHash(view) === record.afterHash)) return null;
+ const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ const identity = effectIdentity(effect.id, record);
+ const page_revision = page?.revision ?? null;
+ const file: RecoveryFileView = { path: record.path, root: record.root, relative: relative(binding.local_path, record.path),
+ prior: record.beforeHash === null ? { absent: true } : { absent: false, sha256: record.beforeHash, size: null, mode: record.mode, stored: false },
+ disk: view, matches: 'neither', withdrawn: { sha256: record.afterHash, size: after.length } };
+ return { reference: after, disk: bytes, item: { id: `effect:${effect.id}`, target: 'withdrawal_mirror', effect_id: effect.id, request_id: effect.request_id ?? '',
+ source_id: sourceId, slug, operation: 'withdrawal-mirror', state: effect.state, blocked_reason: effect.error_code, worktree_id: effect.worktree_id,
+ sequence: effect.id, page_revision, identity, recorded_error: null, prior_hashes: [record.beforeHash], files: [file],
+ choices: { prior: false, disk: false, withdrawn: regular },
+ digest: digest({ v: 'stuck-recovery-effect-v1', id: effect.id, identity, disk: view, page_revision }) } };
+}
+
function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId: string): WorktreeBinding {
if (binding?.owner_host_id === hostId && binding.local_path) return binding;
throw opError('owner_unavailable', `Source ${sourceId}'s canonical worktree is not owned by this host, so its recovery files cannot be read or resolved here.`,
@@ -213,9 +296,10 @@ function ownerBinding(binding: WorktreeBinding | null, sourceId: string, hostId:
}
/**
- * The resolvable recoveries in `sourceIds` (owner host only): every non-terminal page recovery record on each
- * source's worktree that is blocked on unexpected bytes or whose file matches neither recorded version. `requestId`
- * narrows to one request. `artifacts` writes each file's private diff (a remote caller's preview never does).
+ * The resolvable recoveries in `sourceIds` (owner host only): every non-terminal page or bundle recovery record on each
+ * source's worktree that is blocked on unexpected bytes or whose file matches neither recorded version, and every
+ * withdrawal-mirror effect recovery whose file matches neither. `requestId` narrows to one request. `artifacts` writes
+ * each file's private diff (a remote caller's preview never does).
*/
export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string[], opts: { requestId?: string; artifacts?: boolean; hostId?: string } = {}): Promise<StuckRecoveryScan> {
const hostId = opts.hostId ?? localHostId();
@@ -225,20 +309,28 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string
const found = await getWorktreeBinding(engine, sourceId, hostId);
if (!found?.worktree_id) continue;
const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL ORDER BY sequence', [found.worktree_id]);
- const effects = await engine.executeRaw<{ id: string; request_id: string | null; kind: string; state: string; slug: string | null }>(`SELECT e.id::text,r.request_id::text,e.kind,e.state,
- COALESCE(e.recovery->>'slug',r.slug) AS slug FROM persistence_effects e LEFT JOIN persistence_requests r ON r.id=e.request_id
- WHERE e.worktree_id=$1::uuid AND e.recovery IS NOT NULL ORDER BY e.id`, [found.worktree_id]);
+ const effects = await engine.executeRaw<EffectRow>(`${EFFECT_SQL} WHERE e.worktree_id=$1::uuid AND e.recovery IS NOT NULL ORDER BY e.id`, [found.worktree_id]);
+ if (!rows.length && !effects.length) continue;
+ const binding = sourceIds.length === 1 || opts.requestId ? ownerBinding(found, sourceId, hostId) : found.owner_host_id === hostId && found.local_path ? found : null;
+ if (!binding) { residual('owned_by_other_host'); continue; }
for (const effect of effects) {
if (opts.requestId && effect.request_id !== opts.requestId) continue;
- const refused: RefusedRecovery = { code: 'recovery_effect_unsupported', request_id: effect.request_id ?? '', effect_id: effect.id, source_id: sourceId, slug: effect.slug ?? '',
- state: effect.state, blocked_reason: null, reason: effectReason(effect.kind) };
- if (opts.requestId && !rows.some(row => row.request_id === opts.requestId)) throw catalogueError('recovery_effect_unsupported', refused.reason, effectGuidance(sourceId));
- scan.refused.push(refused);
- residual('effect_recovery');
+ const read = await readEffectItem(engine, effect, binding, sourceId);
+ if (!read) { residual('recovers_on_its_own'); continue; }
+ if ('code' in read) {
+ if (opts.requestId) throw refusalError(read);
+ scan.refused.push(read);
+ residual('effect_recovery');
+ continue;
+ }
+ if (opts.artifacts) {
+ const paths = writeArtifacts(await privateBackupDir(engine, read.item.request_id || read.item.id, read.item.digest.slice(0, 16)), read.item.files,
+ [{ label: 'withdrawn', bytes: read.reference }], [read.disk]);
+ read.item.files = read.item.files.map((file, index) => ({ ...file, ...paths[index] }));
+ }
+ scan.items.push(read.item);
}
if (!rows.length) continue;
- const binding = sourceIds.length === 1 || opts.requestId ? ownerBinding(found, sourceId, hostId) : found.owner_host_id === hostId && found.local_path ? found : null;
- if (!binding) { residual('owned_by_other_host'); continue; }
const [head] = await engine.executeRaw<{ id: string; request_id: string }>("SELECT id::text, request_id::text FROM persistence_requests WHERE worktree_id=$1::uuid AND state='queued' ORDER BY sequence LIMIT 1", [binding.worktree_id]);
const read = head ? (await readHeadBlockers(engine, [head.id], hostId).catch(() => null))?.get(head.id) : undefined;
const blocker = read?.status === 'blocked' ? read.blocker : null;
@@ -257,6 +349,13 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string
continue;
}
if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }
+ if (row.recovery?.version === 2 && !filesOf(row.recovery)) {
+ const refused = bundleRefusal(row);
+ if (opts.requestId) throw refusalError(refused);
+ scan.refused.push(refused);
+ residual('bundle_refused');
+ continue;
+ }
if (!opts.requestId && row.recovery?.version === 1 && row.recovery.staging?.before) {
const record = row.recovery;
const contained = isWriteTargetContained(record.path, record.root) && isWriteTargetContained(record.path, binding.local_path!);
@@ -271,7 +370,7 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string
const { item, records, disks } = await readItem(engine, row, binding);
if (row.blocked_reason !== 'unexpected_file_bytes' && item.files.every(file => file.matches !== 'neither')) { residual('recovers_on_its_own'); continue; }
if (opts.artifacts) {
- const paths = writeArtifacts(await privateBackupDir(engine, row.request_id, item.digest.slice(0, 16)), item, records, disks);
+ const paths = writeArtifacts(await privateBackupDir(engine, row.request_id, item.digest.slice(0, 16)), item.files, priorReferences(records), disks);
item.files = item.files.map((file, index) => ({ ...file, ...paths[index] }));
}
scan.items.push(item);
@@ -291,11 +390,30 @@ function largeFileReason(row: WriteRequest): string {
return `Request ${row.request_id} in source ${row.source_id} holds a page recovery whose prior file is over the single-string ceiling, which gbrain repair stuck-recovery does not resolve.`;
}
function effectReason(kind: string): string {
- return `A ${kind} effect recovery blocks the worktree. It only finishes forward (it never restores the bytes from before a withdrawal), and either `
- + '--keep choice could put withdrawn content back on disk, so gbrain repair stuck-recovery does not resolve it.';
+ return `A ${kind} effect recovery blocks the worktree, and its record does not hold usable withdrawn bytes for this canonical binding (missing, corrupt, `
+ + 'or recorded for another owner epoch, root or source incarnation), so gbrain repair stuck-recovery cannot write them back; it never restores the bytes from before a withdrawal.';
+}
+const effectFix = (sourceId: string, requestId: string | null): Action => ({ ask_user: true, argv: stuckRecoveryPreviewArgv([sourceId], requestId ?? undefined), consent: [],
+ actor: 'agent', requires_exclusive: false,
+ why: `A withdrawal mirror in source ${sourceId} stopped with its file edited, and its recovery record cannot write the withdrawn version back, so every write on the worktree waits. `
+ + 'The preview (read-only) lists the effect and its file; only the user can decide how the file is put back.',
+ user_message: `A file in source ${sourceId} was edited while gbrain was removing a forgotten fact from it, and gbrain cannot finish that on its own, so writes to the source are paused. `
+ + 'Copy the edited file somewhere safe and put it back to its committed version (do not delete it); gbrain then finishes removing the forgotten fact. Make the edit again afterwards, leaving that fact out.' });
+function bundleRefusal(row: WriteRequest): RefusedRecovery {
+ return { code: 'recovery_bundle_unsupported', request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state, blocked_reason: row.blocked_reason ?? null,
+ reason: `Request ${row.request_id} in source ${row.source_id} holds a shared-skill bundle recovery record this binary cannot read (an unknown shape or more files than a bundle holds).`,
+ fix: { ask_user: true, argv: stuckRecoveryPreviewArgv([row.source_id], row.request_id), consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Shared-skill request ${row.request_id} is stuck in recovery with a record gbrain repair stuck-recovery cannot read, so every write on source ${row.source_id} waits. `
+ + 'The preview (read-only) lists it; which version of each skill file to keep is the user\'s call.',
+ user_message: `A shared-skill publication in source ${row.source_id} is stuck and this gbrain cannot resolve it. Upgrade gbrain on the brain host and run the preview again; `
+ + 'or decide which version of each skill file to keep and put those bytes in place by hand.' } };
+}
+/** A listed refusal as the error a request-id preview throws. */
+function refusalError(refused: RefusedRecovery): OperationError {
+ const error = catalogueError(refused.code, refused.reason, `Nothing was changed. ${refused.fix?.user_message ?? `Inspect it read-only with gbrain sources writer status --source ${refused.source_id} --json.`}`);
+ if (refused.fix) error.fix = refused.fix;
+ return error;
}
-const effectGuidance = (sourceId: string) => `Nothing was changed. Inspect the effect read-only with gbrain sources writer status --source ${sourceId} --json and ask the user `
- + 'whether the edited file may be replaced by its withdrawn version; the resident writer finishes the effect once the file matches one of its recorded versions.';
const choiceRefused = (reason: string, sourceId: string) => catalogueError('recovery_choice_refused', reason,
`Nothing was changed. Inspect the request read-only with gbrain sources writer status --source ${sourceId} --json and follow the guidance for its blocked reason.`);
@@ -331,12 +449,19 @@ async function abandonWrite(engine: BrainEngine, row: WriteRequest, previewHash:
await engine.transaction(tx => completeWrite(tx, row, mayReprepare(row, recorded) ? 'conflict' : 'failed', {}, { code: recorded.code, message: recorded.message }));
}
-const sameIdentity = (row: WriteRequest | null, item: StuckRecovery) => !!row?.recovery && row.recovery.version === 1
- && digest(identityOf(recoveryFiles(row.recovery), row.recovery)) === digest(item.identity);
+const sameIdentity = (row: WriteRequest | null, item: StuckRecovery) => {
+ const files = row?.recovery ? filesOf(row.recovery) : null;
+ return !!files && digest(identityOf(files, row!.recovery!)) === digest(item.identity);
+};
function nextStep(item: StuckRecovery, keep: KeepChoice, request: WriteRequest): string {
const state = request.state;
const sync = `gbrain sync --source ${item.source_id} --no-pull`;
+ if (item.target === 'skill_bundle') return keep === 'disk'
+ ? `Every skill file is kept as it is on disk and the bundle's publication was abandoned (request ${state}); the shared-skill records keep the version from before it. `
+ + `The backup holds each file's prior and disk bytes. Read the receipt with gbrain write-request -- ${item.request_id}; publish the skill again if the files on disk should become its new version.`
+ : state === 'queued' ? 'The prior bytes of every skill file are back on disk and the publication was requeued: the resident writer publishes it again on its next pass.'
+ : `The prior bytes of every skill file are back on disk and the publication ended ${state}; read its receipt with gbrain write-request -- ${item.request_id}.`;
// #6858: a managed sync import is the next sync's to finish: it retries the page after the manifest end (sync-page-fault.ts fileChangedAfterAdmission).
if (keep === 'disk' && request.intent?.kind === 'managed_sync_import') return `The bytes on disk are kept and the sync import's publication was abandoned (request ${state}). This command does not mark the page repaired. `
+ `Next: ${sync}. That sync retries ${item.slug} after the rest of its run and imports the kept file when it is committed at the run's target; an uncommitted edit is held (worktree_dirty) and the rest of the source syncs. `
@@ -350,23 +475,36 @@ function nextStep(item: StuckRecovery, keep: KeepChoice, request: WriteRequest):
: `The prior bytes are back on disk and the write ended ${state}; read its receipt with gbrain write-request -- ${item.request_id}.`;
}
+async function startedJournal(engine: BrainEngine, key: string, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string }, command: string): Promise<Journal | null> {
+ const journal = await readJournal(engine, key);
+ if (journal && journal.keep !== opts.keep) throw opError('idempotency_conflict', `Preview ${opts.previewHash.slice(0, 12)} of request ${item.request_id} was ${journal.phase === 'done' ? 'resolved' : 'started'} with --keep ${journal.keep}.`,
+ `Nothing was changed. ${journal.phase === 'done' ? 'That resolution is final' : `Finish it with the same choice: rerun the apply with --keep ${journal.keep}`}; for a different choice, preview again (${command}) and apply the new hash.`);
+ return journal;
+}
+async function lockOwner(engine: BrainEngine, item: StuckRecovery, hostId: string, lockWaitMs: number | undefined) {
+ const binding = ownerBinding(await getWorktreeBinding(engine, item.source_id, hostId), item.source_id, hostId);
+ const lock = await acquireWorktree(binding, lockWaitMs ?? 10_000, undefined, engine, { yieldLanes: true });
+ if (!lock) throw opError('writer_lock_unavailable', `Source ${item.source_id}'s worktree lock is held by another writer, so the recovery of request ${item.request_id} was not resolved.`,
+ `Nothing was changed. Rerun the same apply in a few seconds; if it stays busy, inspect the holder with gbrain sources writer status --source ${item.source_id} --json.`, { fix: statusFix(item.source_id) });
+ return { binding, lock };
+}
+const changedAgain = (item: StuckRecovery, backupDir: string, command: string) => opError('unexpected_file_bytes',
+ `A canonical file of request ${item.request_id} changed again after the preview, so the resolution stopped before touching it.`,
+ `Nothing more was changed; the bytes from the preview are backed up under ${backupDir}. Preview again (${command}), show the user the new diff and apply the new hash.`, { fix: statusFix(item.source_id) });
+
/**
* Resolves one approved record (see the module comment). Runs on the owner host under the worktree lock; a run
* killed at any step resumes from its journal, and an identical apply after success returns the recorded result.
*/
export async function resolveStuckRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
Promise<ResolutionResult & { replayed: boolean }> {
+ if (item.target === 'withdrawal_mirror') return resolveEffectRecovery(engine, item, opts);
const hostId = opts.hostId ?? localHostId();
const key = `${item.id}:${opts.previewHash}`;
const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id);
- let journal = await readJournal(engine, key);
- if (journal && journal.keep !== opts.keep) throw opError('idempotency_conflict', `Preview ${opts.previewHash.slice(0, 12)} of request ${item.request_id} was ${journal.phase === 'done' ? 'resolved' : 'started'} with --keep ${journal.keep}.`,
- `Nothing was changed. ${journal.phase === 'done' ? 'That resolution is final' : `Finish it with the same choice: rerun the apply with --keep ${journal.keep}`}; for a different choice, preview again (${command}) and apply the new hash.`);
+ let journal = await startedJournal(engine, key, item, opts, command);
if (journal?.phase === 'done' && journal.result) return { ...journal.result, replayed: true };
- const binding = ownerBinding(await getWorktreeBinding(engine, item.source_id, hostId), item.source_id, hostId);
- const lock = await acquireWorktree(binding, opts.lockWaitMs ?? 10_000, undefined, engine, { yieldLanes: true });
- if (!lock) throw opError('writer_lock_unavailable', `Source ${item.source_id}'s worktree lock is held by another writer, so the recovery of request ${item.request_id} was not resolved.`,
- `Nothing was changed. Rerun the same apply in a few seconds; if it stays busy, inspect the holder with gbrain sources writer status --source ${item.source_id} --json.`, { fix: statusFix(item.source_id) });
+ const { binding, lock } = await lockOwner(engine, item, hostId, opts.lockWaitMs);
try {
let row = await getWriteRequestById(engine, item.id);
if (!journal) {
@@ -375,32 +513,31 @@ Promise<ResolutionResult & { replayed: boolean }> {
const current = await readItem(engine, row!, binding);
if (current.item.digest !== item.digest) throw previewChangedError(opts.previewHash, command);
if (!current.item.choices[opts.keep]) throw catalogueError('recovery_choice_refused', `--keep ${opts.keep} is not available for request ${item.request_id}: `
- + (opts.keep === 'prior' ? 'the recovery record does not hold the prior bytes, or a blocked file is not a regular file.' : 'a blocked file is not a regular file.'),
+ + (opts.keep === 'prior' ? 'the recovery record does not hold the prior bytes, or a blocked file is not a regular file.'
+ : opts.keep === 'withdrawn' ? 'only a withdrawal-mirror effect recovery has withdrawn bytes to write.' : 'a blocked file is not a regular file.'),
`Nothing was changed. The preview lists the available choices; run it again (${command}) and apply one of those.`);
const dir = await privateBackupDir(engine, item.request_id, item.digest.slice(0, 16));
- writeArtifacts(dir, current.item, current.records, current.disks);
+ writeArtifacts(dir, current.item.files, priorReferences(current.records), current.disks);
await faultPoint('stuck_recovery:backed_up', { requestId: item.request_id, sourceId: item.source_id });
journal = { id: item.id, request_id: item.request_id, source_id: item.source_id, slug: item.slug, preview_hash: opts.previewHash, keep: opts.keep, phase: 'backed_up',
backup_dir: dir, original: { state: row!.state, blocked_reason: row!.blocked_reason ?? null, prior_hashes: item.prior_hashes,
- disk_hashes: item.files.map(file => file.disk.deleted ? null : file.disk.sha256) } };
+ disk_hashes: item.files.map(file => diskHash(file.disk)) } };
await writeJournal(engine, key, journal);
}
if (journal.phase === 'backed_up' && sameIdentity(row, item)) {
const records = recoveryFiles(row!.recovery!);
- const unexpected = records.map((record, index) => ({ record, index })).filter(({ index }) => item.files[index].matches === 'neither');
+ const unexpected = records.map((record, index) => ({ record, index })).filter(({ index }) => item.files[index]!.matches === 'neither');
for (const { record, index } of unexpected) {
- const hash = diskView(record.path).view;
- const now = hash.deleted ? null : hash.sha256;
+ const now = diskHash(diskView(record.path).view);
const allowed = opts.keep === 'prior' ? [journal.original.disk_hashes[index], item.prior_hashes[index]] : [journal.original.disk_hashes[index]];
- if (!allowed.includes(now)) throw opError('unexpected_file_bytes', `A canonical file of request ${item.request_id} changed again after the preview, so the resolution stopped before touching it.`,
- `Nothing more was changed; the bytes from the preview are backed up under ${journal.backup_dir}. Preview again (${command}), show the user the new diff and apply the new hash.`, { fix: statusFix(item.source_id) });
+ if (!allowed.includes(now)) throw changedAgain(item, journal.backup_dir, command);
}
if (opts.keep === 'prior') {
await upgradeRecoveryStaging(engine, 'persistence_requests', item.id, item.worktree_id, 'restore');
const staged = recoveryFiles((await getWriteRequestById(engine, item.id))!.recovery!);
await withFilesystemPublication([...new Set(staged.map(record => record.root))], async () => {
for (const { index } of unexpected) {
- const record = staged[index];
+ const record = staged[index]!;
cleanupRecoveryStaging(record);
publishPersistenceFile({ path: record.path, root: record.root, content: priorBytes(record) }, record.staging?.restoration?.path, undefined, record.mode);
}
@@ -428,3 +565,70 @@ Promise<ResolutionResult & { replayed: boolean }> {
return { ...result, replayed: false };
} finally { await lock.release(); }
}
+
+/**
+ * `--keep withdrawn` for a withdrawal-mirror effect recovery: back up the edited bytes, write the recorded
+ * post-withdrawal bytes through the record's publication stage, then finish the effect forward with its own
+ * `recoverEffectPublication` (it materializes the page, clears the record and advances the effect's cursor).
+ */
+async function resolveEffectRecovery(engine: BrainEngine, item: StuckRecovery, opts: { keep: KeepChoice; previewHash: string; hostId?: string; lockWaitMs?: number }):
+Promise<ResolutionResult & { replayed: boolean }> {
+ const hostId = opts.hostId ?? localHostId();
+ const key = `${item.id}:${opts.previewHash}`;
+ const command = stuckRecoveryPreviewCommand([item.source_id], item.request_id || undefined);
+ let journal = await startedJournal(engine, key, item, opts, command);
+ if (journal?.phase === 'done' && journal.result) return { ...journal.result, replayed: true };
+ if (opts.keep !== 'withdrawn') throw catalogueError('recovery_choice_refused', `--keep ${opts.keep} is not available for the withdrawal-mirror effect recovery of request ${item.request_id}: `
+ + 'the withdrawal is committed, and keeping the edited or pre-withdrawal bytes would leave the forgotten fact on disk for the next sync to import again.',
+ `Nothing was changed. The only choice is --keep withdrawn; run the preview again (${command}) and apply its hash with --keep withdrawn after the user agrees.`);
+ const { binding, lock } = await lockOwner(engine, item, hostId, opts.lockWaitMs);
+ try {
+ const read = async () => (await engine.executeRaw<EffectRow>(`${EFFECT_SQL} WHERE e.id=$1`, [item.effect_id]))[0] ?? null;
+ const same = (effect: EffectRow | null) => !!effect?.recovery && digest(effectIdentity(effect.id, effect.recovery)) === digest(item.identity);
+ let effect = await read();
+ if (!journal) {
+ if (!same(effect)) throw previewChangedError(opts.previewHash, command);
+ const current = await readEffectItem(engine, effect!, binding, item.source_id);
+ if (!current || 'code' in current || current.item.digest !== item.digest) throw previewChangedError(opts.previewHash, command);
+ if (!current.item.choices.withdrawn) throw catalogueError('recovery_choice_refused', `--keep withdrawn is not available for request ${item.request_id}: its file is not a regular file.`,
+ `Nothing was changed. Put a regular file back at ${current.item.files[0]!.path} (the backup and the preview diff name the bytes), then preview again (${command}).`);
+ const dir = await privateBackupDir(engine, item.request_id || item.id, item.digest.slice(0, 16));
+ writeArtifacts(dir, current.item.files, [{ label: 'withdrawn', bytes: current.reference }], [current.disk]);
+ await faultPoint('stuck_recovery:backed_up', { requestId: item.request_id, sourceId: item.source_id });
+ journal = { id: item.id, request_id: item.request_id, source_id: item.source_id, slug: item.slug, preview_hash: opts.previewHash, keep: opts.keep, phase: 'backed_up',
+ backup_dir: dir, original: { state: effect!.state, blocked_reason: effect!.error_code, prior_hashes: item.prior_hashes, disk_hashes: [diskHash(current.item.files[0]!.disk)] } };
+ await writeJournal(engine, key, journal);
+ }
+ if (journal.phase === 'backed_up' && same(effect)) {
+ const now = diskHash(diskView(effect!.recovery!.path).view);
+ if (![journal.original.disk_hashes[0], effect!.recovery!.afterHash].includes(now)) throw changedAgain(item, journal.backup_dir, command);
+ await upgradeRecoveryStaging(engine, 'persistence_effects', item.effect_id!, item.worktree_id, 'forward');
+ const record = (await read())!.recovery!;
+ await withFilesystemPublication([record.root], async () => {
+ cleanupRecoveryStaging(record);
+ publishPersistenceFile({ path: record.path, root: record.root, content: Buffer.from(record.after, 'base64') }, record.staging?.publication?.path);
+ if (record.mode !== null && existsSync(record.path)) chmodSync(record.path, record.mode);
+ });
+ await faultPoint('stuck_recovery:written', { requestId: item.request_id, sourceId: item.source_id });
+ journal = { ...journal, phase: 'written' };
+ await writeJournal(engine, key, journal);
+ effect = await read();
+ }
+ const ours = same(effect);
+ if (ours) {
+ await claimAndRecoverEffect(engine, item.effect_id!, hostId);
+ await trueUpRequests(engine, [effect!.request_ref]).catch(() => { /* idempotent; the request's next settlement retries it */ });
+ }
+ await faultPoint('stuck_recovery:recovered', { requestId: item.request_id, sourceId: item.source_id });
+ const finished = await read();
+ const blocked = same(finished);
+ const result: ResolutionResult = { outcome: blocked ? 'still_blocked' : 'resolved', keep: opts.keep, request_state: finished?.state ?? 'committed',
+ blocked_reason: blocked ? finished!.error_code : null, finished_by: ours ? 'this_run' : 'another_pass', backup_dir: journal.backup_dir,
+ next: blocked ? `The effect recovery is still blocked (${finished!.error_code ?? 'recovering'}); rerun the same apply, or inspect it with gbrain sources writer status --source ${item.source_id} --json.`
+ : `The withdrawn bytes are back in ${item.files[0]!.relative} and the withdrawal mirror finished it; the edited bytes are backed up under ${journal.backup_dir} (0.disk, with a diff against 0.withdrawn). `
+ + `Writes queued on source ${item.source_id} resume on the resident writer's next pass. Commit the file before the next sync (an uncommitted change is held as worktree_dirty). `
+ + 'If the edit held other changes, make them again from the backup, leaving the forgotten fact out.' };
+ if (!blocked) await writeJournal(engine, key, { ...journal, phase: 'done', result });
+ return { ...result, replayed: false };
+ } finally { await lock.release(); }
+}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 39825a76cf..834d3fe4b8 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -106,7 +106,7 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
/** #6712 PR 2 `file-drift`: only pages whose newest drift conflict is at or after this concrete instant (ISO; `--since`, parsed by `since.ts`). */
since?: string;
/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
- keep?: 'prior' | 'disk'; requestId?: string;
+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string;
/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */
olderThan?: string; includeFailures?: boolean; force?: boolean;
/** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */
@@ -304,7 +304,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
opts: { 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; since?: string;
- keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean;
+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: 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> {
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 62c7e76789..e2fe3feb3e 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -466,7 +466,7 @@ 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; since?: string;
- keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean } = {}): Promise<RepairResult> {
+ keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: 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,
diff --git a/src/core/repair/stuck-recovery.ts b/src/core/repair/stuck-recovery.ts
index 0c7dc1ae30..ef77827724 100644
--- a/src/core/repair/stuck-recovery.ts
+++ b/src/core/repair/stuck-recovery.ts
@@ -1,15 +1,18 @@
/**
- * `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10): the repair-kind adapter for
- * `persistence/recovery-resolve.ts`. Explicit-only, preview-bound and destructive-consent: the preview lists each
- * recovery record blocked on unexpected bytes (prior and disk fingerprints, a private diff, the choices available)
- * and saves the set under its hash; `--apply --expect <hash> --keep prior|disk --yes` resolves exactly that set. There is no
- * default `--keep`, and a terminal request is listed as refused (see recovery-resolve.ts for the per-state semantics).
- * Projection-only: no journal admission; each record finishes through the owner's own `recoverPublication`.
+ * `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4): the repair-kind
+ * adapter for `persistence/recovery-resolve.ts`. Explicit-only, preview-bound and destructive-consent: the preview lists
+ * each recovery record blocked on unexpected bytes (a page write's, a shared-skill bundle's or a withdrawal-mirror
+ * effect's: recorded and disk fingerprints, a private diff, the choices available) and saves the set under its hash;
+ * `--apply --expect <hash> --keep prior|disk|withdrawn --yes` resolves exactly that set. There is no default `--keep`,
+ * a choice some approved record does not offer is refused before anything runs, and a terminal request is listed as
+ * refused (see recovery-resolve.ts for the per-state semantics).
+ * Projection-only: no journal admission; each record finishes through the owner's own recovery.
*/
import { OperationError } from '../ops/contract.ts';
+import { catalogueError } from '../error-catalogue.ts';
import { loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery, type StuckRecovery }
- from '../persistence/recovery-resolve.ts';
+import { KEEP_CHOICES, readResolutions, resolveStuckRecovery, scanStuckRecoveries, stuckRecoveryPreviewCommand, type KeepChoice, type RecoveryFileView, type RefusedRecovery,
+ type StuckRecovery } from '../persistence/recovery-resolve.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
type Selection = { sources: string[]; request_id: string | null };
@@ -17,10 +20,13 @@ type ApprovedRecovery = StuckRecovery & { selection: Selection };
type RecoveryItem = RepairItem & { recovery: StuckRecovery; hash: string; keep: KeepChoice };
const CHOICE_TEXT: Record<KeepChoice, string> = {
- prior: 'discard the edit: write the recorded prior bytes back (unlink the file when the prior was a create); the owner then finishes the recovery by its own rule, '
- + 'so a request with no recorded failure is requeued and its write publishes again, and one with a failure ends with it',
- disk: 'keep the edit and abandon the write: the request ends conflict (source_changed), or with the failure it already recorded, and its recovery record is '
- + 'cleared; the database page keeps the content before the write, so reconcile the page afterwards (a managed sync import is retried by the next sync instead)',
+ prior: 'discard the edit: write the recorded prior bytes back (unlink the file when the prior was a create; every file of a skill bundle); the owner then finishes the recovery '
+ + 'by its own rule, so a request with no recorded failure is requeued and its write publishes again, and one with a failure ends with it',
+ disk: 'keep the edit and abandon the write: every file stays as it is on disk (every file of a skill bundle), the request ends conflict (source_changed), or with the failure it '
+ + 'already recorded, and its recovery record is cleared; the database page keeps the content before the write, so reconcile the page afterwards (a managed sync import is '
+ + 'retried by the next sync instead)',
+ withdrawn: 'finish the withdrawal: write the recorded post-withdrawal bytes over the edited file (the only choice for a withdrawal-mirror effect: keeping the edit would keep the '
+ + 'forgotten fact on disk for the next sync to import again); the effect then finishes forward and the writes behind it resume',
};
function item(recovery: StuckRecovery, index: number, hash: string, keep: KeepChoice): RecoveryItem {
@@ -33,15 +39,27 @@ const hashOf = (scope: RepairScope, selection: Selection, items: StuckRecovery[]
previewHash({ kind: 'stuck-recovery-v1', brain_id: scope.brain_id, selection, items: items.map(found => found.digest) });
function fileLines(file: RecoveryFileView): string[] {
+ const priorLabel = file.withdrawn ? 'before withdrawal' : 'prior';
const prior = file.prior.absent ? 'absent: prior was a create'
- : `sha256 ${file.prior.sha256.slice(0, 16)}… size ${file.prior.size ?? '?'} mode ${file.prior.mode === null ? '?' : file.prior.mode.toString(8)}${file.prior.stored ? '' : ' (bytes not stored in the record)'}`;
+ : `sha256 ${file.prior.sha256.slice(0, 16)}… size ${file.prior.size ?? '?'} mode ${file.prior.mode === null ? '?' : file.prior.mode.toString(8)}${file.prior.stored || file.withdrawn ? '' : ' (bytes not stored in the record)'}`;
const disk = file.disk.deleted ? 'deleted on disk' : file.disk.kind !== 'file' ? `${file.disk.kind} (not a regular file; resolve it by hand)`
: `sha256 ${file.disk.sha256!.slice(0, 16)}… size ${file.disk.size} mode ${file.disk.mode.toString(8)}`;
- return [` file ${file.relative}`, ` prior: ${prior}`, ` disk: ${disk}`,
- ` recovery sees: ${file.matches === 'neither' ? 'neither the prior nor the published bytes (blocked)' : `the ${file.matches} bytes`}`,
+ const seen = file.matches === 'neither' ? `neither the ${file.withdrawn ? 'pre-withdrawal nor the withdrawn' : 'prior nor the published'} bytes (blocked)` : `the ${file.matches} bytes`;
+ return [` file ${file.relative}`, ` ${priorLabel}: ${prior}`,
+ ...(file.withdrawn ? [` withdrawn: sha256 ${file.withdrawn.sha256.slice(0, 16)}… size ${file.withdrawn.size}`] : []),
+ ` disk: ${disk}`, ` recovery sees: ${seen}`,
...(file.diff_path ? [` diff: ${file.diff_path}`, ` reproduce: ${file.diff_command}`] : [])];
}
+function headerLines(found: StuckRecovery): string[] {
+ if (found.target === 'withdrawal_mirror') return [` effect ${found.effect_id} (withdrawal mirror of request ${found.request_id}, ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; page revision ${found.page_revision ?? 'none'})`,
+ ' the withdrawal is committed: --keep withdrawn is the only choice (keeping the edit would keep the forgotten fact on disk)'];
+ const what = found.target === 'skill_bundle' ? `skill bundle ${found.files.length} file(s)` : `page revision ${found.page_revision ?? 'none'}`;
+ return [` request ${found.request_id} (${found.operation} ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; ${what})`,
+ ` ${found.recorded_error ? `recorded failure ${found.recorded_error}: either choice ends the request with it` : 'no recorded failure: --keep prior requeues the write, --keep disk abandons it'}`
+ + (found.target === 'skill_bundle' ? '; either choice applies to every file of the bundle' : '')];
+}
+
export const stuckRecoveryRepair: RepairHandler = {
kind: 'stuck-recovery',
publication: 'projection',
@@ -57,15 +75,15 @@ export const stuckRecoveryRepair: RepairHandler = {
const apply = (keep: KeepChoice) => `${command} --keep ${keep} --apply --expect ${hash} --yes`;
return { items: scan.items.map((found, index) => item(found, index, hash, 'prior')), preview_hash: hash, residuals: scan.residuals,
listing: scan.items.map(found => ({ item: `${found.source_id}:${found.slug}`, class: 'unexpected_file_bytes',
- detail: `request ${found.request_id}, ${found.files.filter(file => file.matches === 'neither').length} of ${found.files.length} file(s) match neither recorded version` })),
+ detail: `${found.target === 'withdrawal_mirror' ? `withdrawal-mirror effect ${found.effect_id} of request` : 'request'} ${found.request_id}, ${found.files.filter(file => file.matches === 'neither').length} of ${found.files.length} file(s) match neither recorded version` })),
details: { recoveries: scan.items, heads: scan.heads, refused: scan.refused,
- choices: (['prior', 'disk'] as const).filter(keep => scan.items.length && scan.items.every(found => found.choices[keep]))
+ choices: KEEP_CHOICES.filter(keep => scan.items.length && scan.items.every(found => found.choices[keep]))
.map(keep => ({ keep, what: CHOICE_TEXT[keep], apply_command: apply(keep) })) } };
}
if (!opts.expect || !opts.keep) {
throw new OperationError('invalid_params', 'gbrain repair stuck-recovery --apply needs the preview hash and the version to keep.',
- `Preview first: ${command} — show the user the diff it prints, then run the choice they pick: ${command} --keep prior --apply --expect <preview-hash> --yes, `
- + `or ${command} --keep disk --apply --expect <preview-hash> --yes`, 'docs/guides/repair.md#stuck-recovery');
+ `Preview first: ${command} — show the user the diff it prints, then run the choice they pick from the ones it lists: ${command} --keep prior --apply --expect <preview-hash> --yes, `
+ + `${command} --keep disk --apply --expect <preview-hash> --yes, or (a withdrawal-mirror effect) ${command} --keep withdrawn --apply --expect <preview-hash> --yes`, 'docs/guides/repair.md#stuck-recovery');
}
const { expect, keep } = opts;
let approved: ApprovedRecovery[];
@@ -79,6 +97,9 @@ export const stuckRecoveryRepair: RepairHandler = {
approved = done.map(entry => ({ id: entry.id, request_id: entry.request_id, source_id: entry.source_id, slug: entry.slug, selection } as ApprovedRecovery));
}
if (approved.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(selection))) throw previewChangedError(expect, command);
+ const unavailable = approved.filter(entry => entry.choices && !entry.choices[keep]);
+ if (unavailable.length) throw catalogueError('recovery_choice_refused', `--keep ${keep} is not available for ${unavailable.map(entry => `${entry.source_id}:${entry.slug} (${entry.target === 'withdrawal_mirror' ? `withdrawal-mirror effect ${entry.effect_id}` : `request ${entry.request_id}`})`).join(', ')}.`,
+ `Nothing was changed. The preview lists the choices every record offers; run it again (${command}) and apply one of those, or narrow it to one record with --request-id.`);
const started = new Set((await readResolutions(engine, expect)).map(entry => entry.id));
const fresh = approved.filter(entry => !started.has(entry.id));
if (fresh.length) {
@@ -95,7 +116,8 @@ export const stuckRecoveryRepair: RepairHandler = {
const result = await resolveStuckRecovery(ctx.engine, recovery, { keep, previewHash: hash });
return { applied: result.outcome === 'resolved' && !result.replayed, outcome: result.replayed ? 'replayed' : result.outcome,
...(result.blocked_reason ? { reason: result.blocked_reason } : {}),
- detail: { request_id: recovery.request_id, keep, request_state: result.request_state, finished_by: result.finished_by, backup_dir: result.backup_dir, next: result.next } };
+ detail: { request_id: recovery.request_id, ...(recovery.effect_id ? { effect_id: recovery.effect_id } : {}), keep, request_state: result.request_state,
+ finished_by: result.finished_by, backup_dir: result.backup_dir, next: result.next } };
},
render(details) {
const recoveries = (details.recoveries ?? []) as StuckRecovery[];
@@ -104,14 +126,16 @@ export const stuckRecoveryRepair: RepairHandler = {
const lines: string[] = [];
for (const head of heads) if (head.queued_request_id) lines.push(` source ${head.source_id}: queued write ${head.queued_request_id} is blocked by ${head.blocked_by ?? 'nothing known'}`);
for (const found of recoveries) {
- lines.push(` request ${found.request_id} (${found.operation} ${found.source_id}:${found.slug}, ${found.state}${found.blocked_reason ? `, ${found.blocked_reason}` : ''}; page revision ${found.page_revision ?? 'none'})`);
- lines.push(` ${found.recorded_error ? `recorded failure ${found.recorded_error}: either choice ends the request with it` : 'no recorded failure: --keep prior requeues the write, --keep disk abandons it'}`);
+ lines.push(...headerLines(found));
for (const file of found.files) lines.push(...fileLines(file));
}
- for (const refused of (details.refused ?? []) as RefusedRecovery[]) lines.push(` refused ${refused.effect_id ? `effect ${refused.effect_id} of ` : ''}${refused.request_id} (${refused.source_id}:${refused.slug}, ${refused.state}${refused.blocked_reason ? `, ${refused.blocked_reason}` : ''}) ${refused.code}: ${refused.reason}`);
- if (recoveries.length && !choices.length) lines.push(' no choice is available for every listed record: resolve the files listed above by hand, then rerun the preview');
+ for (const refused of (details.refused ?? []) as RefusedRecovery[]) {
+ lines.push(` refused ${refused.effect_id ? `effect ${refused.effect_id} of ` : ''}${refused.request_id} (${refused.source_id}:${refused.slug}, ${refused.state}${refused.blocked_reason ? `, ${refused.blocked_reason}` : ''}) ${refused.code}: ${refused.reason}`);
+ if (refused.fix?.user_message) lines.push(` ask the user: ${refused.fix.user_message}`);
+ }
+ if (recoveries.length && !choices.length) lines.push(' no choice is available for every listed record: narrow the preview with --request-id, or resolve the files listed above by hand, then rerun the preview');
for (const choice of choices) lines.push(` --keep ${choice.keep}: ${choice.what}.`, ` apply (after the user picks it): ${choice.apply_command}`);
- if (choices.length) lines.push(' either choice first backs up the disk and prior bytes beside the diff above');
+ if (choices.length) lines.push(' every choice first backs up the disk and recorded bytes beside the diff above');
return lines;
},
};
diff --git a/test/repair-stuck-recovery.test.ts b/test/repair-stuck-recovery.test.ts
index 3e8219df21..3f101d1c77 100644
--- a/test/repair-stuck-recovery.test.ts
+++ b/test/repair-stuck-recovery.test.ts
@@ -304,18 +304,25 @@ describe('gbrain repair stuck-recovery', () => {
expect(error.suggestion).toContain('--keep disk');
}));
- test('a v2 shared-skill bundle record is refused with recovery_bundle_unsupported', () => run(async () => {
+ test('a v2 shared-skill bundle record is previewed with its files (GBRA-130 C-4); one this binary cannot read is refused with recovery_bundle_unsupported', () => run(async () => {
const s = await stuck({ prior: PRIOR, after: AFTER, disk: EDITED });
const [row] = await engine.executeRaw<{ recovery: any }>('SELECT recovery FROM persistence_requests WHERE id=$1::uuid', [s.id]);
- const bundle = { version: 2, target: 'skill_bundle', root: s.root, ownerEpoch: row.recovery.ownerEpoch, attempt: row.recovery.attempt, files: [row.recovery] };
- // Fixture only: the protocol trigger admits a bundle row solely through the shared-skill writer, so it is bypassed for this one update.
- await engine.transaction(async tx => {
+ const bundle = (files: unknown[]) => ({ version: 2, target: 'skill_bundle', root: s.root, ownerEpoch: row.recovery.ownerEpoch, attempt: row.recovery.attempt, files });
+ // Fixture only: the protocol trigger admits a bundle row solely through the shared-skill writer, so it is bypassed for these updates.
+ const setRecovery = (record: unknown) => engine.transaction(async tx => {
await tx.executeRaw('SET LOCAL session_replication_role = replica');
- await tx.executeRaw("UPDATE persistence_requests SET recovery=$2::text::jsonb,target_kind='skill_bundle',protocol_version=2 WHERE id=$1::uuid", [s.id, JSON.stringify(bundle)]);
+ await tx.executeRaw("UPDATE persistence_requests SET recovery=$2::text::jsonb,target_kind='skill_bundle',protocol_version=2 WHERE id=$1::uuid", [s.id, JSON.stringify(record)]);
});
- const error = await refusal(() => repair(s.sourceId));
+ await setRecovery(bundle([row.recovery]));
+ const preview = await repair(s.sourceId);
+ expect((preview.details as any).recoveries.map((found: any) => [found.target, found.request_id, found.files.map((file: any) => file.matches)]))
+ .toEqual([['skill_bundle', s.requestId, ['neither']]]);
+ await setRecovery(bundle([]));
+ expect((await repair(s.sourceId)).details).toMatchObject({ recoveries: [], refused: [{ code: 'recovery_bundle_unsupported', request_id: s.requestId, fix: { ask_user: true } }] });
+ const error = await refusal(() => repair(s.sourceId, { requestId: s.requestId }));
expect(error.code).toBe('recovery_bundle_unsupported');
expect(error.toJSON()).toMatchObject({ docs: 'docs/guides/repair.md#recovery-bundle-unsupported' });
+ expect(error.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'repair', 'stuck-recovery', '--source', s.sourceId, '--request-id', s.requestId] });
expect(readFileSync(s.path, 'utf8')).toBe(EDITED);
}));