Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): cancel a stuck writer transfer; content receipts follow the root (GBRA-130 C-5, C-7)

garrytan207eb517c976
diff --git a/src/commands/doctor/sync-outcome.ts b/src/commands/doctor/sync-outcome.ts
index 90e486f2d6..8e9e936684 100644
--- a/src/commands/doctor/sync-outcome.ts
+++ b/src/commands/doctor/sync-outcome.ts
@@ -9,12 +9,13 @@ import type { Action } from '../../core/agent-output.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { readLastSyncAttempt, type SyncAttemptState } from '../../core/sync-attempt.ts';
import { classifyManagedSyncOrphans } from '../../core/persistence/managed-sync-orphans.ts';
+import { isOwnedContentSchemaMissing, staleOwnedContent } from '../../core/shared-skills/content-freshness.ts';
import { agentFix, doctorVerify } from './check-fix.ts';
export interface SyncOutcomeEntry {
source_id: string;
- code: 'sync_first_run_in_progress' | 'sync_no_successful_sync';
- reason: 'first_sync_running' | SyncAttemptState;
+ code: 'sync_first_run_in_progress' | 'sync_no_successful_sync' | 'content_receipt_stale';
+ reason: 'first_sync_running' | 'receipt_root_moved' | SyncAttemptState;
last_attempt_at: string | null;
result: string | null;
held: number;
@@ -38,6 +39,8 @@ export function firstSyncRunning(sourceId: string, display: string, snap: { hold
}
export async function noSuccessfulSync(engine: BrainEngine, sourceId: string, display: string, managed: boolean): Promise<{ issue: string; entry: SyncOutcomeEntry }> {
+ const stale = managed ? (await staleOwnedContent(engine, [sourceId]).catch(error => { if (isOwnedContentSchemaMissing(error)) return []; throw error; }))[0] : undefined;
+ if (stale) return contentReceiptStale(sourceId, display);
const attempt = await readLastSyncAttempt(engine, sourceId, managed);
const retry: Action = { argv: ['gbrain', 'sync', '--source', sourceId, ...(managed ? ['--no-pull'] : [])], consent: [], actor: 'agent', requires_exclusive: false,
verify: VERIFY, docs: DOCS, why: `No successful sync of ${sourceId} is recorded; this runs one and stamps last_sync_at when it succeeds.` };
@@ -63,6 +66,22 @@ export async function noSuccessfulSync(engine: BrainEngine, sourceId: string, di
};
}
+/**
+ * C-7 (#6892): a gbrain-owned content source never syncs, and doctor exempts it only while its content receipt names
+ * the source's root. A receipt left on an old root (a transfer or relocation, or a set-path still to run) is
+ * `content_receipt_stale`, fixed by the preview of `gbrain repair content-receipt-root`, never by a sync that refuses.
+ */
+function contentReceiptStale(sourceId: string, display: string): { issue: string; entry: SyncOutcomeEntry } {
+ const fix = agentFix(['gbrain', 'repair', 'content-receipt-root', '--source', sourceId],
+ `The content receipt of ${sourceId} names another root than the source and its owner binding (a writer transfer or relocation moved it). `
+ + 'The preview checks the owner\'s tree against the recorded manifest and prints the apply command with its hash, or names what to fix first; writes nothing.',
+ 'sync_freshness', { docs: 'docs/guides/repair.md#content-receipt-root' });
+ return {
+ issue: `Source ${display}: no successful sync recorded; it is a gbrain-owned content directory whose content receipt names an old root, so sync does not apply and doctor cannot exempt it; run \`${fix.argv!.join(' ')}\``,
+ entry: { source_id: sourceId, code: 'content_receipt_stale', reason: 'receipt_root_moved', last_attempt_at: null, result: null, held: 0, job_id: null, fix },
+ };
+}
+
/**
* #6831: sync_freshness's verdict for each Google or GitHub connector source whose last CONNECTOR_STOPPED_RUNS or more
* runs ended on an error. Such a source imports nothing, but its last_sync_at can still look recent, so freshness alone
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 175f229cba..4b453aed63 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -26,6 +26,7 @@ export const WRITER_HELP = `Usage:
gbrain sources writer deactivate [--admin-intent writer_deactivate --expected-state <admin_state>] [--dry-run] [--json]
gbrain sources writer transfer prepare <source> [--self-transfer [--confirm-relocated-root]] [administration options] [--dry-run] [--json]
gbrain sources writer transfer accept <source> --path <worktree-root> --expected-epoch <n> --manifest <sha256> [--self-transfer [--confirm-relocated-root]] [administration options] [--dry-run] [--json]
+ gbrain sources writer transfer cancel <source> --expected-epoch <n> [administration options] [--dry-run] [--json]
gbrain sources writer lock [--json]
gbrain sources writer unlock [--json]
@@ -46,12 +47,15 @@ git-durability records whether this owner commits (and pushes) page writes throu
its Git effect; --enable runs a read-only push probe first and re-queues the Git
effects skipped while it was off, --pat-file wires a repo-scoped push credential
(same keys as sources harden) and retries this worktree's parked pushes.
-Non-dry-run changes require --admin-intent <writer_claim|writer_activate|writer_deactivate|writer_transfer_prepare|writer_transfer_accept|writer_git_durability>
+Non-dry-run changes require --admin-intent <writer_claim|writer_activate|writer_deactivate|writer_transfer_prepare|writer_transfer_accept|writer_transfer_cancel|writer_git_durability>
matching the action and --expected-state <admin_state from reviewed status>.
These checks also apply to interactive terminals; --yes is not a substitute.
Explicit noninteractive administration is supported. Stale state is rejected.
Use --brain <id> to select a database. Prepare drains the current owner and records
an exact manifest; accept requires that epoch and matching bytes on the successor.
+Cancel, on the owner host, returns a prepared transfer nobody accepted to active at
+the same epoch and clears its manifest (pages and files untouched); an accept with
+that epoch then refuses. --dry-run shows whether the transfer is cancellable.
Before activation, upgrade and stop older writers on every host, claim every
filesystem source, and inspect/release remaining legacy locks. A claim alone
fences legacy sync, sources push and lint --fix for that checkout; claim output
@@ -91,7 +95,7 @@ git-durability --pat-file retries every parked push of the worktree; requests re
on their own are listed in parked_pushes.refused, the result is status partial, and it exits 1.
lock sets an opt-in, brain-level writer admin lock (config key persistence.writer_admin_lock)
and unlock clears it; both are local-only, idempotent and print the resulting state.
-While locked, writer claim, activate and transfer (prepare and accept) are refused with
+While locked, writer claim, activate and transfer (prepare, accept and cancel) are refused with
writer_admin_locked for every caller; ordinary writes continue. lock refuses while a transfer
is prepared and not yet accepted. There is no --force: the escape hatch is the local unlock
(operator workflow: unlock, administer, lock). The lock guards against routine or accidental
@@ -189,9 +193,9 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
else if (verb === 'unlock') operation = 'writer_unlock';
else if (verb === 'transfer') {
const phase = positional.shift();
- if (phase !== 'prepare' && phase !== 'accept') throw invalid(group, 'Transfer requires prepare or accept.',
- 'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed.');
- operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';
+ if (phase !== 'prepare' && phase !== 'accept' && phase !== 'cancel') throw invalid(group, 'Transfer requires prepare or accept (or cancel, which ends a prepared transfer).',
+ 'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed; gbrain sources writer transfer cancel <source> --expected-epoch <n> on the owner host ends a transfer nobody will accept.');
+ operation = phase === 'prepare' ? 'writer_transfer_prepare' : phase === 'accept' ? 'writer_transfer_accept' : 'writer_transfer_cancel';
} else throw invalid(group, 'Writer administration requires status, failures, movement, retry-effects, git-durability, claim, activate, deactivate, transfer, lock, or unlock.',
`Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);
const source = positional.shift();
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 56524e685b..904099b549 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -416,7 +416,7 @@ export const CODES = {
not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },
overlapping_path: { class: 'caller', summary: "Sources cannot claim overlapping canonical directories." },
owner_unavailable: { class: 'retryable', summary: "The source's canonical owner cannot run this write or maintenance step right now; `reason` says which condition.",
- why: "A managed source publishes only through the host that owns its checkout. `host_mismatch`: another host id owns it (two GBRAIN_HOME identity files on one machine look the same; both ids are printed, and a retry on this host cannot help). `transfer_in_progress`: the worktree is draining for a writer transfer; `clone_in_progress`: a topology clone is recovering it; both clear by themselves. `binding_missing`, `incarnation_changed`, `local_path_missing` and `coordination_path_missing` name an incomplete or outdated registration. `not_sent` / `outcome_unknown`: the local owner's IPC lane did not take the write, or lost its acknowledgment. `detail: unbound_source`: on Postgres the source has a checkout but no canonical owner, a configuration state rather than a transient one (not retryable); in classic mode the write path is the file, a commit and `gbrain sync`.",
+ why: "A managed source publishes only through the host that owns its checkout. `host_mismatch`: another host id owns it (two GBRAIN_HOME identity files on one machine look the same; both ids are printed, and a retry on this host cannot help). `transfer_in_progress`: the worktree is draining for a writer transfer, which ends when the successor accepts it or the owner host runs `gbrain sources writer transfer cancel`; a drain prepared over 30 minutes ago asks the user which (`ask_user`) instead of waiting. `clone_in_progress`: a topology clone is recovering it and clears by itself. `binding_missing`, `incarnation_changed`, `local_path_missing` and `coordination_path_missing` name an incomplete or outdated registration. `not_sent` / `outcome_unknown`: the local owner's IPC lane did not take the write, or lost its acknowledgment. `detail: unbound_source`: on Postgres the source has a checkout but no canonical owner, a configuration state rather than a transient one (not retryable); in classic mode the write path is the file, a commit and `gbrain sync`.",
reasons: ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'binding_missing', 'incarnation_changed', 'coordination_path_missing', 'local_path_missing', 'not_sent', 'outcome_unknown'],
docs: 'docs/guides/troubleshooting.md#owner-unavailable',
suggestion: 'Read gbrain sources writer status --source <id> --json on the brain host. A transfer or clone in progress: wait and retry. host_mismatch: run the step on the owner host, or give the worker and the shell one GBRAIN_HOME; never copy or regenerate host.json. Nothing claims or transfers ownership to run maintenance.' },
@@ -593,6 +593,11 @@ export const CODES = {
reasons: ['candidate_in_flight', 'busy_set_unreadable'],
suggestion: 'Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull.' },
// wave 18b #4960: doctor sync_freshness separates sync outcome from freshness for a source with no successful sync.
+ content_receipt_stale: { class: 'unavailable', summary: "A gbrain-owned content source's shared-skills content receipt names another root than the source and its owner binding, so doctor sync_freshness cannot exempt it and sync does not apply.",
+ why: "A writer transfer or relocation an older release ran (or a sources set-path still to run after a transfer accept) moved the canonical root but left the receipt (config shared_skills.content.v1.<source>.<incarnation>) on the old one. Current accepts and set-paths rebind it in their own transaction.",
+ reasons: ['receipt_root_moved'], docs: 'docs/guides/repair.md#content-receipt-root',
+ suggestion: 'Preview gbrain repair content-receipt-root --source <id> on the owner host and apply it with the hash it prints, or do what it names first (sources set-path, or a self-transfer).',
+ fix: { argv: ['gbrain', 'repair', 'content-receipt-root', '--source', '{source_id}'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the receipt rebind and prints the apply command; writes nothing.' } },
sync_first_run_in_progress: { class: 'retryable', summary: "A source's first sync is running (it holds a live sync lock inside the staleness ceiling) and no successful sync is recorded yet, so doctor sync_freshness warns instead of reading it as fresh.",
why: "A sync stamps last_sync_at only when it succeeds; a running sync is not a fresh source, and starting a second one beside it only contends for the lock. Over the staleness ceiling the lock reads as wedged (fail) instead.",
docs: 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync', suggestion: 'Wait for the running sync, then run gbrain doctor --only sync_freshness --json again.' },
diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.ts
index 60cee8baec..f8ab4c0f8d 100644
--- a/src/core/persistence/admin-contract.ts
+++ b/src/core/persistence/admin-contract.ts
@@ -16,7 +16,7 @@ export const PERSISTENCE_ADMIN_OPERATIONS = [
* added there: the owner advertises it in `administration_extensions`, which older clients ignore, and a client calls
* one only when the owner lists it.
*/
-export const PERSISTENCE_ADMIN_EXTENSIONS = ['writer_failures'] as const;
+export const PERSISTENCE_ADMIN_EXTENSIONS = ['writer_failures', 'writer_transfer_cancel'] as const;
export type PersistenceAdminExtension = typeof PERSISTENCE_ADMIN_EXTENSIONS[number];
export type PersistenceAdminOperation = typeof PERSISTENCE_ADMIN_OPERATIONS[number] | PersistenceAdminExtension;
export function isPersistenceAdminOperation(value: unknown): value is PersistenceAdminOperation {
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 241a75f998..49325d1484 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -21,18 +21,18 @@ import { listWriterVersions } from './writer-versions.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
-const invalid = (message: string, suggestion: string, fix?: Action) =>
+export const invalid = (message: string, suggestion: string, fix?: Action) =>
opError('invalid_params', message, suggestion, fix ? { fix } : {});
const sourcesListFix = (why: string) => readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'] });
const writerListFix = readFix('Lists the local writer registrations and their ids, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] });
const LIST_EXAMPLES: Record<string, string> = { source_ids: 'default,notes', scopes: 'read,write', allowed_operations: 'search,get_page', slug_prefixes: 'people/,companies/' };
const cliFlag = (key: string) => `--${key.replaceAll('_', '-')}`;
-function source(value: unknown): string {
+export function source(value: unknown): string {
if (typeof value !== 'string' || !isValidSourceId(value)) throw invalid('An explicit active source ID is required.', 'Name the source explicitly with its id; gbrain sources list --json shows the active sources.',
sourcesListFix('Lists the active source ids, read-only.'));
return value;
}
-function path(value: unknown): string {
+export function path(value: unknown): string {
if (typeof value !== 'string' || !isAbsolute(value) || value.includes('\0')) throw invalid('path must be an absolute directory path on this host.',
'Pass --path with an absolute directory on this host, e.g. --path /srv/brain/notes; a relative path or one containing a NUL byte is refused.');
return value;
@@ -46,18 +46,11 @@ function strings(value: unknown, key: string): string[] {
`Pass ${cliFlag(key)} as a comma-separated list with no empty entries, e.g. ${cliFlag(key)} ${LIST_EXAMPLES[key] ?? 'a,b'}.`);
return [...new Set(value)];
}
-function bool(params: Record<string, unknown>, key: string): void {
+export function bool(params: Record<string, unknown>, key: string): void {
if (params[key] !== undefined && typeof params[key] !== 'boolean') throw invalid(`${key} must be a boolean.`,
`Send ${key} as a JSON boolean (true or false); on the CLI it is the bare flag ${cliFlag(key)}, which takes no value.`);
}
-/** #5914: `--confirm-relocated-root` only qualifies a self-transfer; alone it is a usage error, never a silent no-op. */
-function transferOptions(params: Record<string, unknown>): { selfTransfer: boolean; relocated: boolean } {
- bool(params, 'confirm_relocated_root');
- if (params.confirm_relocated_root === true && params.self_transfer !== true) throw invalid('confirm_relocated_root requires self_transfer.',
- 'Pass --confirm-relocated-root together with --self-transfer: it waives only the directory identity comparison of a self-transfer that repairs a checkout recreated at its recorded path.');
- return { selfTransfer: params.self_transfer === true, relocated: params.confirm_relocated_root === true };
-}
-function keys(params: Record<string, unknown>, allowed: string[]) {
+export function keys(params: Record<string, unknown>, allowed: string[]) {
const unknown = Object.keys(params).filter(key => !allowed.includes(key));
if (unknown.length) throw invalid(`Unsupported administration parameters: ${unknown.join(', ')}.`,
`Remove ${unknown.join(', ')}; this operation accepts ${allowed.length ? allowed.join(', ') : 'no parameters'}. A caller on another gbrain release sends the parameters of its own release: run one release on both sides.`);
@@ -122,9 +115,6 @@ function writerFailuresQuery(sourceId: string, params: Record<string, unknown>):
...(p.category ? { category: p.category } : {}) };
}
-const transferStatusFix = (sourceId: string) =>
- readFix(`Shows source ${sourceId}'s owner binding and prepared transfer, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
-
export async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,
params: Record<string, unknown>, config?: GBrainConfig, embeddingRetryPolicy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {
if (operation === 'writer_reconcile_preview') return (await import('./reconcile.ts')).runReconcilePreview(engine, params);
@@ -153,7 +143,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
return { ...await setWriterAdminLock(engine, operation === 'writer_lock') };
}
// Early refusal before any native lock or preview; the checks inside each transaction stay authoritative.
- if (['writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept'].includes(operation)) await assertWriterAdminUnlocked(engine);
+ if (['writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept', 'writer_transfer_cancel'].includes(operation)) await assertWriterAdminUnlocked(engine);
if (operation === 'writer_sync') return (await import('./sync-administration.ts')).runAuthenticatedSyncSlice(engine, params);
if (operation === 'writer_refresh') {
keys(params, ['source_id', 'dry_run', 'resume', 'abandon', 'wait_drain_ms', 'fetch_timeout_ms']);
@@ -245,7 +235,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const adminState = await writerAdminState(engine);
const diagnostics = await writerDiagnostics(engine);
const bindings = await engine.executeRaw(`SELECT b.source_id,b.source_incarnation,b.worktree_id,b.relative_path,b.topology_generation::text AS topology_generation,
- w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,w.manifest->>'digest' AS manifest_digest,h.local_path,h.git_durability,
+ w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,w.manifest->>'digest' AS manifest_digest,w.manifest->>'prepared_at' AS prepared_at,h.local_path,h.git_durability,
CASE h.git_durability WHEN 'enabled' THEN 'on' WHEN 'disabled' THEN 'off' ELSE 'unknown' END AS git_durability_state FROM persistence_source_bindings b
JOIN persistence_worktrees w ON w.id=b.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid
@@ -336,51 +326,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
return { ...await deactivatePersistence(engine, { expectedState, requestId: params.request_id === undefined ? undefined
: uuid(params.request_id, 'A valid deactivation request UUID is required.', 'Pass --request-id as a UUID, or omit it and gbrain generates one.') }) };
}
- if (operation === 'writer_transfer_prepare') {
- keys(params, ['source_id', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
- const sourceId = source(params.source_id);
- bool(params, 'self_transfer');
- const transfer = transferOptions(params);
- if (params.dry_run) {
- const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
- if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
- throw opError('permission_denied', 'Only the current owner can prepare a transfer.',
- `This host is not source ${sourceId}'s current owner. Run the transfer prepare on the owner host that writer status names; a transfer is a deliberate topology change the operator reviews.`,
- { fix: readFix(`Shows which host owns source ${sourceId}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
- }
- const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
- return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count }, ...(transfer.relocated ? { relocated: true } : {}) };
- }
- const expectedState = await requireWriterAdminIntent(engine, operation, params);
- const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, transfer);
- // #6099: a Git-scoped manifest covers tracked files only; untracked files Git does not ignore are reported as a count.
- const untracked = prepared.manifest.untracked_count ?? 0;
- return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,
- manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count, ...(prepared.manifest.scope ? { scope: prepared.manifest.scope } : {}) },
- ...(untracked ? { untracked_files: untracked, warning: `${untracked} untracked file(s) in the checkout that Git does not ignore are not part of the transfer manifest and are not carried to the successor; commit them, or add them to .gitignore, before the successor clones.` } : {}) };
- }
- if (operation === 'writer_transfer_accept') {
- keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
- bool(params, 'self_transfer');
- const transfer = transferOptions(params);
- const sourceId = source(params.source_id), root = path(params.path);
- if (typeof params.expected_epoch !== 'string' || !/^[1-9]\d{0,18}$/.test(params.expected_epoch)
- || BigInt(params.expected_epoch) > 9_223_372_036_854_775_807n) throw invalid('expected_epoch must be the prepared positive owner epoch.',
- `Pass --expected-epoch with the owner_epoch that gbrain sources writer transfer prepare ${sourceId} printed (a positive integer).`, transferStatusFix(sourceId));
- if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.',
- `Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));
- if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
- if (params.dry_run) {
- const current = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
- const [prepared] = current ? await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [current.worktree_id]) : [];
- const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });
- return { dry_run: true, action: operation, source_id: sourceId, current, manifest_matches: candidate.digest === params.manifest, expected_epoch: params.expected_epoch,
- ...(candidate.scope ? { manifest_scope: candidate.scope } : {}), ...(candidate.untracked_count ? { untracked_files: candidate.untracked_count } : {}) };
- }
- const expectedState = await requireWriterAdminIntent(engine, operation, params);
- await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, undefined, expectedState, transfer);
- return { transferred: true, binding: await getWorktreeBinding(engine, sourceId) };
- }
+ if (operation === 'writer_transfer_prepare' || operation === 'writer_transfer_accept' || operation === 'writer_transfer_cancel') return (await import('./transfer-administration.ts')).runWriterTransferAdministration(engine, operation, params);
if (operation === 'local_writer_list') {
keys(params, ['limit', 'before']);
const limit = params.limit ?? 100;
diff --git a/src/core/persistence/owner-refusal.ts b/src/core/persistence/owner-refusal.ts
index 52f8141778..3c4c727ad4 100644
--- a/src/core/persistence/owner-refusal.ts
+++ b/src/core/persistence/owner-refusal.ts
@@ -18,7 +18,13 @@
* coordination_path_missing this host's registration has no coordination directory
*
* The two in-progress reasons are a `wait` (the fix's actor is `provider`;
- * the `why` names the delay); the rest are a host administrator's decision
+ * the `why` names the delay), except a transfer whose recorded preparation
+ * (`prepared_at`) is older than TRANSFER_STALE_MINUTES: a prepared transfer
+ * never ends on its own, so that refusal asks the user (`ask_user`) to accept
+ * it on the successor or cancel it on the owner host, with both argv and the
+ * cancel's `--dry-run` preview; a drain with no recorded time (an older
+ * release prepared it) keeps the wait, whose `why` names the cancel. The rest
+ * are a host administrator's decision
* (`tell_user_to_run`). `host_mismatch` is `retryable: false`: retrying on
* the same host cannot change the answer. Nothing here claims or transfers
* ownership; the fix is always the read-only writer status, and the local
@@ -39,6 +45,15 @@ export type OwnerUnavailableReason = typeof OWNER_UNAVAILABLE_REASONS[number];
/** Seconds a caller waits before retrying while a transfer or clone is in progress. */
export const OWNER_WAIT_SECONDS = 30;
+/** Minutes after its recorded preparation a still-draining transfer stops reading as in progress and asks the user to accept or cancel it. */
+export const TRANSFER_STALE_MINUTES = 30;
+
+/** Whole minutes since the binding's transfer was prepared, or null when no preparation time is recorded. */
+function drainingMinutes(binding: WorktreeBinding | null): number | null {
+ const at = binding?.prepared_at ? Date.parse(binding.prepared_at) : NaN;
+ return Number.isFinite(at) ? Math.floor((Date.now() - at) / 60_000) : null;
+}
+
/** A binding this host may publish through: active, owned here, with both registered paths. */
export type ActiveOwnerBinding = WorktreeBinding & { state: 'active'; local_path: string; coordination_path: string };
@@ -115,10 +130,24 @@ export function ownerRefusal(input: OwnerRefusalInput): OwnerRefusal {
fix: admin(`Shows the owner host of source ${sourceId}; run ${work} there, or align GBRAIN_HOME so the worker and the shell share one host identity. Do not copy or regenerate host.json: a new identity orphans the ownership recorded for the old one.`,
`gbrain could not run ${work} for source ${sourceId} because a different host identity owns its checkout. Run it on the owner host (writer status names it), or make both environments use the same GBRAIN_HOME.`) };
}
- case 'transfer_in_progress':
- return { reason, retryable: true, message: `Source ${sourceId}'s worktree is draining for a writer transfer, so ${work} waits.`,
+ case 'transfer_in_progress': {
+ const minutes = drainingMinutes(binding);
+ const epoch = String(binding?.owner_epoch ?? '<owner_epoch>');
+ const cancel = ['gbrain', 'sources', 'writer', 'transfer', 'cancel', sourceId, '--expected-epoch', epoch];
+ if (minutes === null || minutes < TRANSFER_STALE_MINUTES) return { reason, retryable: true, message: `Source ${sourceId}'s worktree is draining for a writer transfer, so ${work} waits.`,
why: `A writer transfer of source ${sourceId} is prepared and its worktree is in state draining; until the transfer is accepted or cancelled no host may publish to it. ${never}`,
- fix: wait(`Source ${sourceId}'s worktree is draining for a writer transfer (gbrain sources writer transfer prepare was run); the status read shows its state.`) };
+ fix: wait(`Source ${sourceId}'s worktree is draining for a writer transfer (gbrain sources writer transfer prepare was run); the status read shows its state. `
+ + `If no successor will accept it, the owner host ends it with ${cancel.join(' ')} (preview with --dry-run).`) };
+ const accept = `gbrain sources writer transfer accept ${sourceId} --path <successor root> --expected-epoch ${epoch} --manifest <manifest digest printed by prepare> --admin-intent writer_transfer_accept --expected-state <admin_state>`;
+ const apply = [...cancel, '--admin-intent', 'writer_transfer_cancel', '--expected-state', '<admin_state>'];
+ return { reason, retryable: false, message: `Source ${sourceId}'s worktree has been draining for a writer transfer for ${minutes} minutes, so ${work} did not run.`,
+ why: `A writer transfer of source ${sourceId} was prepared ${minutes} minutes ago (over ${TRANSFER_STALE_MINUTES}) and never accepted; a prepared transfer does not end on its own, and until it is accepted or cancelled no host may publish to it. ${never}`,
+ fix: { ask_user: true, argv: apply, preview_argv: [...cancel, '--dry-run', '--json'], consent: [], actor: 'host_admin', requires_exclusive: false, verify,
+ inputs: [{ name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host` }],
+ why: `Cancels the prepared transfer on the owner host: the worktree returns to active at epoch ${epoch} and the prepared manifest is cleared; pages and files are untouched. Run the --dry-run preview first.`,
+ user_message: `A writer transfer of source ${sourceId} was prepared ${minutes} minutes ago and never accepted, so ${work} is paused. Either finish it on the successor host (${accept}) `
+ + `or cancel it on this owner host (${apply.join(' ')}). Which do you want?` } };
+ }
case 'clone_in_progress':
return { reason, retryable: true, message: `Source ${sourceId}'s worktree is being cloned or recloned, so ${work} waits.`,
why: `A topology clone of source ${sourceId}'s checkout is in progress and its worktree is in state recovering; it becomes active when the clone finishes. ${never}`,
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index f7b8faf5e1..39a95ab342 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -24,6 +24,7 @@ import { assertWriterAdminState } from './admin-intent.ts';
import { readGraduationRow } from './graduation-schema.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';
+import type { ContentReceiptRebind } from '../shared-skills/receipt-root.ts';
const writerStatusFix = (sourceId: string): Action => readFix(
`Shows source ${sourceId}'s owner host, epoch, worktree state, admin_state and any publication still recovering, read-only.`,
@@ -42,6 +43,8 @@ export interface WorktreeBinding {
coordination_path: string | null;
/** #5182 per-host Git-durability opt-in: null until an operator records one. */
git_durability: GitDurabilitySetting;
+ /** C-5: when the prepared transfer was recorded (manifest `prepared_at`); null when none is, or an older release prepared it. */
+ prepared_at?: string | null;
}
export type GitDurabilitySetting = 'enabled' | 'disabled' | null;
export function containsPath(root: string, path: string): boolean {
@@ -71,7 +74,7 @@ export async function persistenceEnabledForHealth(engine: BrainEngine): Promise<
export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
const [row] = await engine.executeRaw<WorktreeBinding>(`SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path,
s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,
- h.local_path,h.coordination_path,h.git_durability FROM persistence_source_bindings s
+ h.local_path,h.coordination_path,h.git_durability,w.manifest->>'prepared_at' AS prepared_at FROM persistence_source_bindings s
JOIN persistence_worktrees w ON w.id=s.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid
WHERE s.source_id=$1`, [sourceId, hostId]);
@@ -334,13 +337,53 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
if (!opts.selfTransfer) assertPhysicalRoot(binding.local_path!, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });
if (hashed instanceof Error) throw hashed;
const manifest: StoredWorktreeManifest = { ...hashed, ...(recovery ? { self_transfer: recovery } : {}) };
- if (!opts.dryRun) await tx.executeRaw(`UPDATE persistence_worktrees SET state='draining',manifest=$2::text::jsonb WHERE id=$1::uuid`, [binding.worktree_id, JSON.stringify(manifest)]);
+ if (!opts.dryRun) await tx.executeRaw(`UPDATE persistence_worktrees SET state='draining',manifest=$2::text::jsonb||jsonb_build_object('prepared_at',now()) WHERE id=$1::uuid`,
+ [binding.worktree_id, JSON.stringify(manifest)]);
return { worktree_id: binding.worktree_id, owner_epoch: String(owner.owner_epoch), manifest };
});
} finally { await lock.release(); }
}
+/**
+ * C-5: on the owner host, return a prepared transfer nobody accepted to `active` and clear its prepared manifest,
+ * under the native coordination lock and the worktree row's FOR UPDATE. The epoch is kept, so an accept bound to it
+ * meets an active worktree and refuses `writer_transfer_conflict`; the owner may prepare again.
+ */
+export async function cancelWriterTransfer(engine: BrainEngine, sourceId: string, expectedEpoch: string, hostId = localHostId(), expectedAdminState?: string,
+ opts: { dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; state: string; prepared_at: string | null; cancellable: boolean }> {
+ const binding = await getWorktreeBinding(engine, sourceId, hostId);
+ const notOwner = () => opError('permission_denied', 'Only the current owner can cancel this transfer.',
+ `This host does not own source ${sourceId}'s checkout, so nothing was cancelled. Cancel runs in a terminal on the owner host that writer status names; a successor that has not accepted has nothing to cancel.`,
+ { fix: writerStatusFix(sourceId) });
+ if (!binding || binding.owner_host_id !== hostId) throw notOwner();
+ const conflict = (state: string, epoch: string) => opError('writer_transfer_conflict', 'No transfer is prepared at that epoch.',
+ `Source ${sourceId}'s worktree is ${state} at epoch ${epoch}, not draining at epoch ${expectedEpoch}, so nothing was cancelled. Read writer status and cancel with the epoch of the current preparation, if one is still prepared.`,
+ { fix: writerStatusFix(sourceId) });
+ if (opts.dryRun) {
+ const cancellable = binding.state === 'draining' && String(binding.owner_epoch) === expectedEpoch;
+ return { worktree_id: binding.worktree_id, owner_epoch: String(binding.owner_epoch), state: binding.state, prepared_at: binding.prepared_at ?? null, cancellable };
+ }
+ if (!binding.coordination_path) throw opError('recovery_required', 'The recorded coordination path is missing.',
+ `Source ${sourceId}'s host binding has no coordination lock path, so the transfer was not cancelled. Inspect writer status and show it to the user; repairing the binding is a deliberate topology change (docs/architecture/topologies.md).`,
+ { fix: writerStatusFix(sourceId) });
+ const lock = await acquireNativeLock(binding.coordination_path, { timeoutMs: 5000 });
+ if (!lock) throw opError('write_pending', 'The worktree is busy; retry the cancel.',
+ `Another gbrain process holds source ${sourceId}'s coordination lock, so the transfer was not cancelled. Run the cancel again once that process has finished.`,
+ { fix: writerStatusFix(sourceId) });
+ try {
+ return await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
+ await assertWriterAdminState(tx, expectedAdminState);
+ await assertWriterAdminUnlocked(tx);
+ const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string; state: string }>('SELECT owner_host_id,owner_epoch::text AS owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);
+ if (!owner || owner.owner_host_id !== hostId) throw notOwner();
+ if (owner.state !== 'draining' || String(owner.owner_epoch) !== expectedEpoch) throw conflict(owner.state, String(owner.owner_epoch));
+ await tx.executeRaw(`UPDATE persistence_worktrees SET state='active',manifest=NULL WHERE id=$1::uuid`, [binding.worktree_id]);
+ return { worktree_id: binding.worktree_id, owner_epoch: String(owner.owner_epoch), state: 'active', prepared_at: binding.prepared_at ?? null, cancellable: true };
+ });
+ } finally { await lock.release(); }
+}
export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = localHostId(), expectedAdminState?: string,
- opts: WriterTransferOptions = {}): Promise<void> {
+ opts: WriterTransferOptions = {}): Promise<{ content_receipts: ContentReceiptRebind[] }> {
const root = realpathSync(resolve(path));
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) throw opError('not_found', 'Source has no worktree owner.',
@@ -366,7 +409,7 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
const [prepared] = await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]);
const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });
if (candidate.digest !== expectedManifest) throw successorManifestMismatch(sourceId, root, expectedManifest, prepared?.manifest ?? null, candidate);
- await engine.transaction(async tx => {
+ return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await assertWriterAdminState(tx, expectedAdminState);
await assertWriterAdminUnlocked(tx);
@@ -388,11 +431,13 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
{ fix: writerStatusFix(sourceId) });
if (opts.selfTransfer) repairPhysicalRoot(root, owner.manifest.self_transfer!, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination }, opts.dryRun);
else if (!opts.dryRun) await preparePhysicalRootTransfer(tx, root, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination, expectedEpoch });
- if (opts.dryRun) return;
+ if (opts.dryRun) return { content_receipts: [] };
await tx.executeRaw(`INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path)
VALUES($1::uuid,$2::uuid,$3,$4) ON CONFLICT(worktree_id,host_id) DO UPDATE SET local_path=EXCLUDED.local_path,coordination_path=EXCLUDED.coordination_path`, [binding.worktree_id, hostId, root, coordination]);
+ const contentReceipts = await (await import('../shared-skills/receipt-root.ts')).rebindContentReceipts(tx, [binding.worktree_id], hostId);
await tx.executeRaw(`UPDATE persistence_worktrees SET owner_host_id=$2::uuid,owner_epoch=owner_epoch+1,state='active',heartbeat_at=now() WHERE id=$1::uuid`, [binding.worktree_id, hostId]);
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
+ return { content_receipts: contentReceipts };
});
} finally { await lock.release(); }
}
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 354fa5514e..9b8cbb7a21 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -28,6 +28,7 @@ import { claimPhysicalRoot } from './physical-root.ts';
import { inspectRelocatedPhysicalRoot, relocatePhysicalRoot } from './physical-root-record.ts';
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
+import { rebindContentReceipts } from '../shared-skills/receipt-root.ts';
export interface SourceLifecycleInput {
operation:'add'|'claim'|'archive'|'restore'|'remove'|'purge'|'rebind'|'reclone';
@@ -278,6 +279,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
await tx.executeRaw('DELETE FROM sources WHERE id=$1 AND incarnation=$2::uuid',[input.sourceId,incarnation]);
await tx.executeRaw('DELETE FROM persistence_source_bindings WHERE source_id=$1 AND source_incarnation=$2::uuid',[input.sourceId,incarnation]);
}
+ const contentReceipts=input.operation==='rebind'?await rebindContentReceipts(tx,worktrees,localHostId(),relocated?undefined:[input.sourceId]):[];
await advanceTopology(tx,worktrees);
for(const id of worktrees){
const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[id,localHostId()]);
@@ -288,7 +290,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
// stale installations cannot write after a source moved or disappeared.
await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));
return {operation:input.operation,source_id:input.sourceId,source_incarnation:incarnation,invalidated_requests:invalidated,
- ...(missingCheckout?{retired_without_checkout:missingCheckout}:{}),
+ ...(missingCheckout?{retired_without_checkout:missingCheckout}:{}),...(contentReceipts.length?{content_receipts:contentReceipts}:{}),
...(root?{local_path:root.source}:{}),...(['remove','purge'].includes(input.operation)?{storage_retained:true,local_path:ownedSourcePath??null,pages_deleted:pagesDeleted}:{}),
...(input.operation==='add'?{name:input.name??source?.name??input.sourceId,config:redactSourceConfig({...source?.config,...input.config}),id:input.sourceId}: {})};
},principalAttribution({kind:'local_cli',id:principal}));
diff --git a/src/core/persistence/transfer-administration.ts b/src/core/persistence/transfer-administration.ts
new file mode 100644
index 0000000000..5f9ad8b29b
--- /dev/null
+++ b/src/core/persistence/transfer-administration.ts
@@ -0,0 +1,89 @@
+/**
+ * Writer transfer administration (`gbrain sources writer transfer prepare|accept|cancel`), dispatched by
+ * `runPersistenceAdministration`. Prepare drains the owner and records the manifest; accept moves ownership to the
+ * successor; cancel (C-5) returns a prepared transfer nobody accepted to active on the owner host. Every non-dry-run
+ * change requires its action-specific --admin-intent and the reviewed --expected-state.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { acceptWriterTransfer, cancelWriterTransfer, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from './ownership.ts';
+import { existingLocalHostId } from './identity.ts';
+import { requireWriterAdminIntent } from './admin-intent.ts';
+import { bool, invalid, keys, path, source } from './administration.ts';
+
+/** #5914: `--confirm-relocated-root` only qualifies a self-transfer; alone it is a usage error, never a silent no-op. */
+function transferOptions(params: Record<string, unknown>): { selfTransfer: boolean; relocated: boolean } {
+ bool(params, 'confirm_relocated_root');
+ if (params.confirm_relocated_root === true && params.self_transfer !== true) throw invalid('confirm_relocated_root requires self_transfer.',
+ 'Pass --confirm-relocated-root together with --self-transfer: it waives only the directory identity comparison of a self-transfer that repairs a checkout recreated at its recorded path.');
+ return { selfTransfer: params.self_transfer === true, relocated: params.confirm_relocated_root === true };
+}
+
+const transferStatusFix = (sourceId: string) =>
+ readFix(`Shows source ${sourceId}'s owner binding and prepared transfer, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
+
+/** The prepared positive owner epoch a transfer accept or cancel names. */
+function expectedEpoch(params: Record<string, unknown>, sourceId: string): string {
+ if (typeof params.expected_epoch !== 'string' || !/^[1-9]\d{0,18}$/.test(params.expected_epoch)
+ || BigInt(params.expected_epoch) > 9_223_372_036_854_775_807n) throw invalid('expected_epoch must be the prepared positive owner epoch.',
+ `Pass --expected-epoch with the owner_epoch that gbrain sources writer transfer prepare ${sourceId} printed (a positive integer).`, transferStatusFix(sourceId));
+ return params.expected_epoch;
+}
+
+export async function runWriterTransferAdministration(engine: BrainEngine, operation: 'writer_transfer_prepare' | 'writer_transfer_accept' | 'writer_transfer_cancel',
+ params: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (operation === 'writer_transfer_cancel') {
+ keys(params, ['source_id', 'expected_epoch', 'dry_run', 'admin_intent', 'expected_state']);
+ const sourceId = source(params.source_id), epoch = expectedEpoch(params, sourceId);
+ if (params.dry_run) {
+ const preview = await cancelWriterTransfer(engine, sourceId, epoch, existingLocalHostId()!, undefined, { dryRun: true });
+ return { dry_run: true, action: operation, source_id: sourceId, ...preview,
+ ...(preview.cancellable ? { apply_command: `gbrain sources writer transfer cancel ${sourceId} --expected-epoch ${epoch} --admin-intent writer_transfer_cancel --expected-state <admin_state>` } : {}) };
+ }
+ const expectedState = await requireWriterAdminIntent(engine, operation, params);
+ const cancelled = await cancelWriterTransfer(engine, sourceId, epoch, undefined, expectedState);
+ return { cancelled: true, source_id: sourceId, worktree_id: cancelled.worktree_id, owner_epoch: cancelled.owner_epoch, binding: await getWorktreeBinding(engine, sourceId) };
+ }
+ if (operation === 'writer_transfer_prepare') {
+ keys(params, ['source_id', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
+ const sourceId = source(params.source_id);
+ bool(params, 'self_transfer');
+ const transfer = transferOptions(params);
+ if (params.dry_run) {
+ const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
+ if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
+ throw opError('permission_denied', 'Only the current owner can prepare a transfer.',
+ `This host is not source ${sourceId}'s current owner. Run the transfer prepare on the owner host that writer status names; a transfer is a deliberate topology change the operator reviews.`,
+ { fix: readFix(`Shows which host owns source ${sourceId}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
+ }
+ const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
+ return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count }, ...(transfer.relocated ? { relocated: true } : {}) };
+ }
+ const expectedState = await requireWriterAdminIntent(engine, operation, params);
+ const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, transfer);
+ // #6099: a Git-scoped manifest covers tracked files only; untracked files Git does not ignore are reported as a count.
+ const untracked = prepared.manifest.untracked_count ?? 0;
+ return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,
+ manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count, ...(prepared.manifest.scope ? { scope: prepared.manifest.scope } : {}) },
+ ...(untracked ? { untracked_files: untracked, warning: `${untracked} untracked file(s) in the checkout that Git does not ignore are not part of the transfer manifest and are not carried to the successor; commit them, or add them to .gitignore, before the successor clones.` } : {}) };
+ }
+ keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
+ bool(params, 'self_transfer');
+ const transfer = transferOptions(params);
+ const sourceId = source(params.source_id), root = path(params.path);
+ const epoch = expectedEpoch(params, sourceId);
+ if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.',
+ `Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));
+ if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, epoch, params.manifest, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
+ if (params.dry_run) {
+ const current = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
+ const [prepared] = current ? await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [current.worktree_id]) : [];
+ const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });
+ return { dry_run: true, action: operation, source_id: sourceId, current, manifest_matches: candidate.digest === params.manifest, expected_epoch: epoch,
+ ...(candidate.scope ? { manifest_scope: candidate.scope } : {}), ...(candidate.untracked_count ? { untracked_files: candidate.untracked_count } : {}) };
+ }
+ const expectedState = await requireWriterAdminIntent(engine, operation, params);
+ const accepted = await acceptWriterTransfer(engine, sourceId, root, epoch, params.manifest, undefined, expectedState, transfer);
+ return { transferred: true, binding: await getWorktreeBinding(engine, sourceId), ...(accepted.content_receipts.length ? { content_receipts: accepted.content_receipts } : {}) };
+}
diff --git a/src/core/repair/content-receipt-root.ts b/src/core/repair/content-receipt-root.ts
new file mode 100644
index 0000000000..4ab165b8c6
--- /dev/null
+++ b/src/core/repair/content-receipt-root.ts
@@ -0,0 +1,122 @@
+/**
+ * `gbrain repair content-receipt-root [--source <id>]` (C-7, #6892): rebind a gbrain-owned content source's
+ * shared-skills content receipt that still names an old root after a writer transfer or relocation an older release
+ * ran (newer accepts and set-paths rebind it themselves, `shared-skills/receipt-root.ts`). Explicit-only and
+ * preview-bound: the preview classifies every stale receipt and hashes the result; `--apply --expect <hash>`
+ * recomputes it and refuses `preview_changed` unless it is unchanged.
+ *
+ * A receipt is rebound (class `rebind`) only on the owner host, when the owner binding's root (joined with the
+ * source's relative_path) exists, is the source's local_path, and the owner's tree still hashes to the worktree
+ * manifest the last transfer or rebind verified. Otherwise it is refused and listed with what to do first:
+ * `not_owner_host`, `root_missing` (writer status), `source_path_mismatch` (`gbrain sources set-path`), or
+ * `tree_mismatch` (a self-transfer on the owner host re-verifies the tree and rebinds the receipt in its accept).
+ * The apply rewrites only the receipt's `root` and `root_identity`, keeps the previous value under
+ * `<receipt key>.backup`, and skips a receipt that changed since the preview.
+ */
+import { createHash } from 'node:crypto';
+import { resolve } from 'node:path';
+import type { Action } from '../agent-output.ts';
+import { OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { localHostId } from '../persistence/identity.ts';
+import { previewChangedError, previewHash } from '../persistence/preview-approval.ts';
+import { storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from '../persistence/worktree-manifest.ts';
+import { staleOwnedContent } from '../shared-skills/content-freshness.ts';
+import { ownedContentReceipt, rootIdentity } from '../shared-skills/receipt-root.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+type Verdict = { source_id: string; class: 'rebind' | 'not_owner_host' | 'root_missing' | 'source_path_mismatch' | 'tree_mismatch'; detail: string; fix?: Action;
+ key: string; raw: string; next?: { root: string; root_identity: { device: number; inode: number } } };
+type ReceiptItem = RepairItem & { key: string; raw: string; next: NonNullable<Verdict['next']> };
+
+const previewCommand = (scope: RepairScope) => `gbrain repair content-receipt-root${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
+const statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s owner host, binding root and worktree state, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+
+function selfTransferFix(sourceId: string): Action {
+ const intent = (phase: string) => ['--admin-intent', `writer_transfer_${phase}`, '--expected-state', '<admin_state>'];
+ const inputs = [{ name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host (read it again before the accept)` }];
+ return { argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, '--self-transfer', ...intent('prepare')], inputs, consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: `Records the manifest of source ${sourceId}'s current tree on the owner host; the self-transfer accept then re-verifies the tree and rebinds the content receipt in the same transaction.`,
+ then: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', sourceId, '--path', '<owner root>', '--expected-epoch', '<owner_epoch>', '--manifest', '<manifest digest printed by prepare>', '--self-transfer', ...intent('accept')],
+ inputs: [...inputs, { name: 'owner root', how: 'the binding root writer status prints' }, { name: 'owner_epoch', how: 'the owner_epoch prepare printed' }],
+ consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Accepts the self-transfer: ownership stays on this host and the content receipt follows the verified root.' } };
+}
+
+async function verdicts(engine: Parameters<RepairHandler['plan']>[0], scope: RepairScope): Promise<Verdict[]> {
+ const out: Verdict[] = [];
+ for (const stale of await staleOwnedContent(engine, scope.source_ids)) {
+ const [row] = await engine.executeRaw<{ incarnation: string; brain_id: string; key: string; value: string; owner_host_id: string; manifest: StoredWorktreeManifest | null; worktree_root: string; relative_path: string }>(
+ `SELECT s.incarnation::text AS incarnation,p.brain_id,c.key,c.value,w.owner_host_id::text AS owner_host_id,w.manifest,h.local_path AS worktree_root,b.relative_path
+ FROM sources s JOIN persistence_brain p ON p.singleton=1
+ JOIN config c ON c.key='shared_skills.content.v1.'||s.id||'.'||s.incarnation::text
+ JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
+ JOIN persistence_worktrees w ON w.id=b.worktree_id
+ JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id
+ WHERE s.id=$1`, [stale.sourceId]);
+ if (!row || !ownedContentReceipt(row.value, row.brain_id, stale.sourceId, row.incarnation)) continue;
+ const base = { source_id: stale.sourceId, key: row.key, raw: row.value };
+ const was = `the receipt names ${stale.receiptRoot ?? 'no root'}`;
+ if (row.owner_host_id !== localHostId()) { out.push({ ...base, class: 'not_owner_host', detail: `${was}; run this repair on the owner host, which can read its root`, fix: statusFix(stale.sourceId) }); continue; }
+ const next = rootIdentity(resolve(row.worktree_root, row.relative_path));
+ if (!next) { out.push({ ...base, class: 'root_missing', detail: `${was}; the owner binding's root ${resolve(row.worktree_root, row.relative_path)} cannot be read`, fix: statusFix(stale.sourceId) }); continue; }
+ if (rootIdentity(stale.localPath)?.root !== next.root) {
+ out.push({ ...base, class: 'source_path_mismatch', detail: `${was}; the source's local_path is ${stale.localPath} but its owner binding is at ${next.root}; move the source there first`,
+ fix: { argv: ['gbrain', 'sources', 'set-path', stale.sourceId, next.root], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: `Moves source ${stale.sourceId}'s local_path to its owner binding's root after verifying the bytes; the rebind also rebinds the content receipt.` } });
+ continue;
+ }
+ const recorded = row.manifest?.digest ?? null;
+ const actual = worktreeManifest(row.worktree_root, { scope: storedManifestScope(row.manifest) }).digest;
+ if (recorded !== actual) {
+ out.push({ ...base, class: 'tree_mismatch', fix: selfTransferFix(stale.sourceId),
+ detail: `${was}; the owner's tree at ${row.worktree_root} hashes to ${actual} but the recorded worktree manifest is ${recorded ?? 'missing'}, so it is not proven to be the transferred content` });
+ continue;
+ }
+ out.push({ ...base, class: 'rebind', next, detail: `${was}; rebind it to ${next.root} (device ${next.root_identity.device}, inode ${next.root_identity.inode}), whose tree matches manifest ${actual}` });
+ }
+ return out;
+}
+
+export const contentReceiptRootRepair: RepairHandler = {
+ kind: 'content-receipt-root',
+ publication: 'projection',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = previewCommand(scope);
+ const found = await verdicts(engine, scope);
+ const hash = previewHash({ kind: 'content-receipt-root-v1', brain_id: scope.brain_id, selection: scope.source_ids,
+ verdicts: found.map(v => [v.source_id, v.class, createHash('sha256').update(v.raw).digest('hex'), v.next ?? null]) });
+ if (opts?.apply && !opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair content-receipt-root --apply rebinds only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`, 'docs/guides/repair.md#content-receipt-root');
+ }
+ if (opts?.apply && opts.expect !== hash) throw previewChangedError(opts.expect!, command);
+ const items: ReceiptItem[] = found.filter(v => v.class === 'rebind').map((v, index) => ({ cursor: { phase: 0, id: index + 1 }, source_id: v.source_id, slug: v.source_id, chars: 0,
+ action: 'rebind_receipt', change: { from: v.raw, to: JSON.stringify(v.next) }, key: v.key, raw: v.raw, next: v.next! }));
+ const refused = found.filter(v => v.class !== 'rebind');
+ const residuals: Record<string, number> = {};
+ for (const v of refused) residuals[v.class] = (residuals[v.class] ?? 0) + 1;
+ return { items: items.filter(item => afterCursor(item.cursor, after)), preview_hash: hash, residuals,
+ listing: found.map(v => ({ item: v.source_id, class: v.class, detail: v.detail })),
+ details: { refused: refused.map(v => ({ source_id: v.source_id, class: v.class, detail: v.detail, fix: v.fix })) } };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { key, raw, next, source_id } = entry as ReceiptItem;
+ return ctx.engine.transaction(async tx => {
+ const [row] = await tx.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1 FOR UPDATE', [key]);
+ if (row?.value !== raw) return { applied: false, outcome: 'kept', reason: 'changed_since_preview' };
+ const now = rootIdentity(next.root);
+ if (now?.root_identity.device !== next.root_identity.device || now.root_identity.inode !== next.root_identity.inode) return { applied: false, outcome: 'kept', reason: 'root_changed_since_preview' };
+ const backup = `${key}.backup`;
+ await tx.executeRaw('INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value',
+ [backup, JSON.stringify({ previous: raw, replaced_at: new Date().toISOString(), source_id })]);
+ await tx.executeRaw('UPDATE config SET value=$2 WHERE key=$1', [key, JSON.stringify({ ...JSON.parse(raw), ...next })]);
+ return { applied: true, outcome: 'rebound', detail: { from: (JSON.parse(raw) as { root?: unknown }).root ?? null, to: next.root, backup_key: backup } };
+ });
+ },
+ render(details) {
+ const refused = (details.refused ?? []) as Array<{ source_id: string; class: string; detail: string; fix?: Action }>;
+ return refused.map(row => `refused ${row.source_id} (${row.class}): ${row.detail}${row.fix?.argv ? `; next: ${row.fix.argv.join(' ')}` : ''}`);
+ },
+};
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 39825a76cf..920e87ecc8 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 62c7e76789..95425cd633 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -46,6 +46,7 @@ import { takeSupersessionRepair } from './take-supersession.ts';
import { acceptedTakesRepair } from './accepted-takes.ts';
import { orphanBindingsRepair } from './orphan-bindings.ts';
import { managedSyncOrphansRepair } from './managed-sync-orphans.ts';
+import { contentReceiptRootRepair } from './content-receipt-root.ts';
import { embeddingEffectsRepair } from './embedding-effects.ts';
import { googleFileModesRepair } from './google-file-modes.ts';
import { staleAtomsRepair } from './stale-atoms.ts';
@@ -292,6 +293,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Bookkeeping only (op_checkpoints); no journal admission. The preview prints a hash; --apply --expect <hash> retires exactly that set. '
+ 'A cursor with a live pending request, or one the live writer can still resume, is kept and counted.',
},
+ 'content-receipt-root': {
+ handler: contentReceiptRootRepair, embeds: 'none', checks: ['sync_freshness'], explicit_only: true, preview_bound: true,
+ summary: 'Rebind a gbrain-owned content source\'s shared-skills content receipt that still names an old root after a writer transfer or relocation (#6892), '
+ + 'so doctor sync_freshness exempts the source again. Owner host only; rebinds only when the owner\'s tree still hashes to the recorded worktree manifest, '
+ + 'and otherwise lists why (source_path_mismatch: run sources set-path; tree_mismatch: a self-transfer re-verifies). The receipt row only; the previous '
+ + 'value is kept under <key>.backup. Preview-bound: --apply --expect <hash> rebinds exactly the previewed set.',
+ },
'frontmatter-keys': {
handler: frontmatterKeysRepair, embeds: 'none', checks: ['stale_frontmatter_keys'], explicit_only: true, preview_bound: true,
summary: 'Strip the parser\'s reserved keys (type, title, tags, slug) that older imports stored inside pages.frontmatter (#6454). Since this release '
diff --git a/src/core/shared-skills/content-freshness.ts b/src/core/shared-skills/content-freshness.ts
index aa02568827..fe0228514b 100644
--- a/src/core/shared-skills/content-freshness.ts
+++ b/src/core/shared-skills/content-freshness.ts
@@ -21,11 +21,22 @@ export interface OwnedContentFreshness {
recovering: number;
}
-export async function ownedContentFreshness(engine: BrainEngine, sourceIds?: string[]): Promise<OwnedContentFreshness[]> {
- const rows = await engine.executeRaw<{
- id: string; incarnation: string; local_path: string; config: unknown; last_commit: string | null;
- brain_id: string; receipt: string; owner_root: string; relative_path: string; pending: number; recovering: number;
- }>(`SELECT s.id,s.incarnation,s.local_path,s.config,s.last_commit,p.brain_id,c.value AS receipt,
+/** C-7: a gbrain-owned content source whose complete receipt names another root than the source and its owner binding. */
+export interface StaleOwnedContent {
+ sourceId: string;
+ receiptRoot: string | null;
+ /** The owner host's binding root joined with the source's relative_path. */
+ ownerRoot: string | null;
+ localPath: string;
+}
+
+interface OwnedContentRow {
+ id: string; incarnation: string; local_path: string; config: unknown; last_commit: string | null;
+ brain_id: string; receipt: string; owner_root: string; relative_path: string; pending: number; recovering: number;
+}
+
+async function ownedContentRows(engine: BrainEngine, sourceIds?: string[]): Promise<OwnedContentRow[]> {
+ return engine.executeRaw<OwnedContentRow>(`SELECT s.id,s.incarnation,s.local_path,s.config,s.last_commit,p.brain_id,c.value AS receipt,
h.local_path AS owner_root,b.relative_path,
((SELECT COUNT(*) FROM persistence_requests r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation
AND r.state IN ('queued','running') AND r.recovery IS NULL)
@@ -42,20 +53,46 @@ export async function ownedContentFreshness(engine: BrainEngine, sourceIds?: str
JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id
WHERE NOT s.archived AND s.local_path IS NOT NULL AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))
AND NOT EXISTS (SELECT 1 FROM source_ingestion_receipts r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.profile='company-brain')`, [sourceIds ?? null, await graduationVerifyInheritsPersistence(engine)]);
+}
+
+/** The row's complete, ready, owned receipt of a plain content source (no connector, clone or company brain), else null. */
+function completeOwnedReceipt(row: OwnedContentRow, sourceIds?: string[]): Record<string, unknown> | null {
+ if (sourceIds && !sourceIds.includes(row.id)) return null;
+ if (!row.config || typeof row.config !== 'object' || Array.isArray(row.config) || row.last_commit !== null) return null;
+ const config = row.config as Record<string, unknown>;
+ if (config.kind != null || config.remote_url != null || config.managed_clone === true || config.company_brain != null) return null;
+ let receipt: Record<string, unknown>;
+ try { receipt = JSON.parse(row.receipt); } catch { return null; }
+ return receipt && receipt.version === 1 && receipt.brain_id === row.brain_id && receipt.source_id === row.id
+ && receipt.source_incarnation === row.incarnation && receipt.owned_root === true && receipt.stage === 'complete'
+ && receipt.status === 'ready' && ['content_directory', 'git'].includes(String(receipt.repository_kind)) ? receipt : null;
+}
+
+const ownerRootOf = (row: OwnedContentRow) => typeof row.owner_root === 'string' && typeof row.relative_path === 'string' ? resolve(row.owner_root, row.relative_path) : null;
+
+/** The receipt, the source's local_path and the owner binding name one absolute root. */
+function rootsAgree(row: OwnedContentRow, receipt: Record<string, unknown>): boolean {
+ return receipt.root === row.local_path && typeof row.local_path === 'string' && isAbsolute(row.local_path) && ownerRootOf(row) === row.local_path;
+}
+
+export async function ownedContentFreshness(engine: BrainEngine, sourceIds?: string[]): Promise<OwnedContentFreshness[]> {
const result: OwnedContentFreshness[] = [];
- for (const row of rows) {
- if (sourceIds && !sourceIds.includes(row.id)) continue;
- if (!row.config || typeof row.config !== 'object' || Array.isArray(row.config) || row.last_commit !== null) continue;
- const config = row.config as Record<string, unknown>;
- if (config.kind != null || config.remote_url != null || config.managed_clone === true || config.company_brain != null) continue;
- let receipt: Record<string, unknown>;
- try { receipt = JSON.parse(row.receipt); } catch { continue; }
- if (!receipt || receipt.version !== 1 || receipt.brain_id !== row.brain_id || receipt.source_id !== row.id
- || receipt.source_incarnation !== row.incarnation || receipt.owned_root !== true || receipt.stage !== 'complete'
- || receipt.status !== 'ready' || !['content_directory', 'git'].includes(String(receipt.repository_kind)) || receipt.root !== row.local_path
- || typeof row.local_path !== 'string' || !isAbsolute(row.local_path) || typeof row.owner_root !== 'string'
- || typeof row.relative_path !== 'string' || resolve(row.owner_root, row.relative_path) !== row.local_path) continue;
- result.push({ sourceId: row.id, pending: Number(row.pending), recovering: Number(row.recovering) });
+ for (const row of await ownedContentRows(engine, sourceIds)) {
+ const receipt = completeOwnedReceipt(row, sourceIds);
+ if (receipt && rootsAgree(row, receipt)) result.push({ sourceId: row.id, pending: Number(row.pending), recovering: Number(row.recovering) });
+ }
+ return result;
+}
+
+/**
+ * C-7: owned content sources whose complete receipt, local_path and owner binding disagree on the root (a transfer or
+ * relocation an older release ran, or a set-path still to run). Doctor names `gbrain repair content-receipt-root` for them.
+ */
+export async function staleOwnedContent(engine: BrainEngine, sourceIds?: string[]): Promise<StaleOwnedContent[]> {
+ const result: StaleOwnedContent[] = [];
+ for (const row of await ownedContentRows(engine, sourceIds)) {
+ const receipt = completeOwnedReceipt(row, sourceIds);
+ if (receipt && !rootsAgree(row, receipt)) result.push({ sourceId: row.id, receiptRoot: typeof receipt.root === 'string' ? receipt.root : null, ownerRoot: ownerRootOf(row), localPath: row.local_path });
}
return result;
}
diff --git a/src/core/shared-skills/receipt-root.ts b/src/core/shared-skills/receipt-root.ts
new file mode 100644
index 0000000000..a4e3755735
--- /dev/null
+++ b/src/core/shared-skills/receipt-root.ts
@@ -0,0 +1,58 @@
+/**
+ * C-7 (#6892): keep the shared-skills content receipt (`shared_skills.content.v1.<source>.<incarnation>`) on the
+ * canonical root when a topology change moves it. A writer transfer accept and a `sources set-path` rebind call
+ * `rebindContentReceipts` inside their own transaction, so the receipt commits and rolls back with the move.
+ * Only an owned receipt of this brain and the source's current incarnation is rewritten: its `root` becomes the
+ * realpath of the host binding's root joined with the source's `relative_path` (nested sources included) and its
+ * `root_identity` that directory's device and inode. A root that cannot be read leaves the receipt as it is.
+ */
+import { realpathSync, statSync } from 'node:fs';
+import { resolve } from 'node:path';
+import type { SqlEngine } from '../persistence/model.ts';
+
+export interface ContentReceiptRebind { source_id: string; source_incarnation: string; from: string | null; to: string }
+
+/** The receipt's parsed JSON when it is an owned receipt of this brain and source incarnation, else null. */
+export function ownedContentReceipt(raw: string | null | undefined, brainId: string, sourceId: string, incarnation: string): Record<string, unknown> | null {
+ let receipt: unknown;
+ try { receipt = JSON.parse(raw ?? ''); } catch { return null; }
+ if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)) return null;
+ const r = receipt as Record<string, unknown>;
+ return r.version === 1 && r.brain_id === brainId && r.source_id === sourceId && r.source_incarnation === incarnation && r.owned_root === true ? r : null;
+}
+
+/** The directory's realpath with its device and inode, or null when it cannot be read. */
+export function rootIdentity(path: string): { root: string; root_identity: { device: number; inode: number } } | null {
+ try {
+ const root = realpathSync(path);
+ const stat = statSync(root);
+ return stat.isDirectory() ? { root, root_identity: { device: stat.dev, inode: stat.ino } } : null;
+ } catch { return null; }
+}
+
+/**
+ * Rebinds the owned content receipts of the sources bound to `worktreeIds` (only `sourceIds` when given) to their
+ * root under `hostId`'s binding; returns what moved. Runs on the caller's transaction.
+ */
+export async function rebindContentReceipts(tx: SqlEngine, worktreeIds: string[], hostId: string, sourceIds?: string[]): Promise<ContentReceiptRebind[]> {
+ const rows = await tx.executeRaw<{ source_id: string; incarnation: string; relative_path: string; local_path: string; brain_id: string; key: string; value: string }>(
+ `SELECT b.source_id,b.source_incarnation::text AS incarnation,b.relative_path,h.local_path,p.brain_id,c.key,c.value
+ FROM persistence_source_bindings b
+ JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation AND NOT s.archived
+ JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$2::uuid
+ JOIN persistence_brain p ON p.singleton=1
+ JOIN config c ON c.key='shared_skills.content.v1.'||b.source_id||'.'||b.source_incarnation::text
+ WHERE b.worktree_id=ANY($1::uuid[]) AND ($3::text[] IS NULL OR b.source_id=ANY($3::text[])) ORDER BY b.source_id`,
+ [worktreeIds, hostId, sourceIds ?? null]);
+ const moved: ContentReceiptRebind[] = [];
+ for (const row of rows) {
+ const receipt = ownedContentReceipt(row.value, row.brain_id, row.source_id, row.incarnation);
+ const next = receipt && rootIdentity(resolve(row.local_path, row.relative_path));
+ if (!receipt || !next) continue;
+ const identity = receipt.root_identity as { device?: number; inode?: number } | undefined;
+ if (receipt.root === next.root && identity?.device === next.root_identity.device && identity?.inode === next.root_identity.inode) continue;
+ await tx.executeRaw('UPDATE config SET value=$2 WHERE key=$1 AND value=$3', [row.key, JSON.stringify({ ...receipt, ...next }), row.value]);
+ moved.push({ source_id: row.source_id, source_incarnation: row.incarnation, from: typeof receipt.root === 'string' ? receipt.root : null, to: next.root });
+ }
+ return moved;
+}
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index cdf6030c35..e99ee5969d 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -195,7 +195,7 @@ for (const backend of testBackends()) {
const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
- frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
+ frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables' };
diff --git a/test/helpers/fail-transaction.ts b/test/helpers/fail-transaction.ts
new file mode 100644
index 0000000000..708fe5c15e
--- /dev/null
+++ b/test/helpers/fail-transaction.ts
@@ -0,0 +1,17 @@
+import type { BrainEngine } from '../../src/core/engine.ts';
+
+/**
+ * Wraps the engine's transactions so the first statement matching `pattern` throws `error()` (a run-scoped failure injected
+ * mid-transaction, so the transaction rolls back); every other statement runs on the real transaction. Returns the restore.
+ */
+export function failTransactionAt(engine: BrainEngine, pattern: RegExp, error: () => unknown): () => void {
+ const original = engine.transaction;
+ (engine as unknown as { transaction: BrainEngine['transaction'] }).transaction = ((fn: (tx: BrainEngine) => Promise<unknown>) => original.call(engine, (tx: BrainEngine) => fn(new Proxy(tx, {
+ get(target, prop) {
+ if (prop === 'executeRaw') return async (sql: string, params?: unknown[]) => { if (pattern.test(sql)) throw error(); return target.executeRaw(sql, params); };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ })))) as BrainEngine['transaction'];
+ return () => { delete (engine as unknown as { transaction?: unknown }).transaction; };
+}
diff --git a/test/pathological/c5-writer-transfer-cancel.test.ts b/test/pathological/c5-writer-transfer-cancel.test.ts
new file mode 100644
index 0000000000..a7de1931f1
--- /dev/null
+++ b/test/pathological/c5-writer-transfer-cancel.test.ts
@@ -0,0 +1,154 @@
+/**
+ * GBRA-130 C-5: a writer transfer that was prepared and never accepted.
+ *
+ * Protects: `gbrain sources writer transfer prepare` drains the worktree;
+ * until now the only exit was `accept` on a successor, so a lost successor (or
+ * a change of mind) left maintenance, fence repair, managed repair roots and
+ * lifecycle changes refusing `owner_unavailable/transfer_in_progress` with
+ * "wait 30 s" forever. `gbrain sources writer transfer cancel <source>
+ * --expected-epoch <n>` (admin-intent bound, owner host, native lock, FOR
+ * UPDATE) returns the worktree to active and clears the prepared manifest; a
+ * racing accept with the old epoch then refuses `writer_transfer_conflict`;
+ * past TRANSFER_STALE_MINUTES the refusal's fix turns from wait into ask_user
+ * naming accept and cancel with exact argv.
+ * Fails when: cancel is missing or changes anything but the worktree state and
+ * manifest, a stale drain still reads `wait`, or an accept lands after cancel.
+ * Why new: no test covered an abandoned transfer; test/owner-refusal.test.ts
+ * pins only the fresh-drain `wait`.
+ * Seams: none (the run case wraps the engine's transaction to inject a
+ * run-scoped error at the cancel's state write).
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { cliRenderContext, toAgentError } from '../../src/core/agent-output.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';
+import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { maintenancePreflight } from '../../src/core/persistence/prepared-maintenance.ts';
+import { TRANSFER_STALE_MINUTES } from '../../src/core/persistence/owner-refusal.ts';
+import { parsePersistenceAdminArgs } from '../../src/commands/persistence-admin.ts';
+import { failTransactionAt } from '../helpers/fail-transaction.ts';
+import { reviewedWriterIntent } from '../helpers/writer-admin-intent.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SOURCE = 'default';
+const SLUGS = ['notes/alice-example', 'notes/acme-example'];
+
+async function seed({ engine }: { engine: BrainEngine }) {
+ for (const slug of SLUGS) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `body of ${slug}` }, { sourceId: SOURCE });
+}
+
+async function topology(engine: BrainEngine, sql: string, params: unknown[]) {
+ await engine.transaction(async tx => { await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)"); await tx.executeRaw(sql, params); });
+}
+
+async function prepare(engine: BrainEngine): Promise<{ owner_epoch: string; manifest: { digest: string } }> {
+ return await runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: SOURCE, ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }) as never;
+}
+
+async function worktree(engine: BrainEngine) {
+ const binding = (await getWorktreeBinding(engine, SOURCE))!;
+ const [row] = await engine.executeRaw<{ state: string; owner_epoch: string; owner_host_id: string; manifest: unknown }>(
+ 'SELECT state,owner_epoch::text AS owner_epoch,owner_host_id::text AS owner_host_id,manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]);
+ return { binding, row: row! };
+}
+
+async function refusal(engine: BrainEngine): Promise<OperationError> {
+ try { await maintenancePreflight(engine, SOURCE); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('maintenancePreflight did not refuse');
+}
+
+const cancelArgv = (epoch: string) => ['gbrain', 'sources', 'writer', 'transfer', 'cancel', SOURCE, '--expected-epoch', epoch, '--admin-intent', 'writer_transfer_cancel', '--expected-state', '<admin_state>'];
+const render = (error: OperationError) => toAgentError(error, { transport: 'cli', command: 'chronicle', render: cliRenderContext() });
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`C-5 writer transfer cancel (${backend})`, () => {
+ test('C-5 wedge: a drain older than the threshold asks the user to accept or cancel instead of waiting forever', () => managedBrain(async ({ engine }) => {
+ const prepared = await prepare(engine);
+ expect(render(await refusal(engine))).toMatchObject({ code: 'owner_unavailable', reason: 'transfer_in_progress', fix: { next: 'wait' } });
+ const { binding } = await worktree(engine);
+ await topology(engine, `UPDATE persistence_worktrees SET manifest=manifest||jsonb_build_object('prepared_at',to_jsonb(now()-make_interval(mins=>$2::int)))
+ WHERE id=$1::uuid`, [binding.worktree_id, TRANSFER_STALE_MINUTES + 1]);
+ const stale = render(await refusal(engine));
+ expect({ reason: stale.reason, next: stale.fix?.next, argv: stale.fix?.argv }).toEqual({ reason: 'transfer_in_progress', next: 'ask_user', argv: cancelArgv(prepared.owner_epoch) });
+ expect(stale.fix?.preview_argv).toEqual(['gbrain', 'sources', 'writer', 'transfer', 'cancel', SOURCE, '--expected-epoch', prepared.owner_epoch, '--dry-run', '--json']);
+ expect(stale.fix?.user_message).toContain(`gbrain sources writer transfer accept ${SOURCE}`);
+ expect(stale.fix?.user_message).toContain(`gbrain sources writer transfer cancel ${SOURCE} --expected-epoch ${prepared.owner_epoch}`);
+ // A drain an older release prepared records no time: its age is unknown, so it keeps the wait, whose why names the cancel.
+ await topology(engine, "UPDATE persistence_worktrees SET manifest=manifest-'prepared_at' WHERE id=$1::uuid", [binding.worktree_id]);
+ const unknown = render(await refusal(engine));
+ expect({ next: unknown.fix?.next, names_cancel: unknown.fix?.why.includes(`gbrain sources writer transfer cancel ${SOURCE} --expected-epoch ${prepared.owner_epoch}`) })
+ .toEqual({ next: 'wait', names_cancel: true });
+ }, { setup: seed, databaseUrl }), 120_000);
+
+ test('C-5 item: cancel returns a stuck drain to active, maintenance runs again, and nothing else changes', () => managedBrain(async ({ engine }) => {
+ const prepared = await prepare(engine);
+ const failure = await refusal(engine);
+ expectItemFailure({ key: SOURCE, code: failure.reason, fix: failure.fix }, { key: SOURCE, code: 'transfer_in_progress', fix: /gbrain sources writer status --source default/ });
+ const before = await snapshotItems(engine, SOURCE);
+ const drained = await worktree(engine);
+ const preview = await runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: prepared.owner_epoch, dry_run: true });
+ expect(preview).toMatchObject({ dry_run: true, action: 'writer_transfer_cancel', source_id: SOURCE, cancellable: true, state: 'draining', owner_epoch: prepared.owner_epoch });
+ expect((await worktree(engine)).row).toEqual(drained.row);
+ const result = await expectUnitNotAborted(async () => runPersistenceAdministration(engine, 'writer_transfer_cancel',
+ { source_id: SOURCE, expected_epoch: prepared.owner_epoch, ...await reviewedWriterIntent(engine, 'writer_transfer_cancel') }));
+ expect(result).toMatchObject({ cancelled: true, source_id: SOURCE, owner_epoch: prepared.owner_epoch });
+ const after = await worktree(engine);
+ expect(after.row).toEqual({ state: 'active', owner_epoch: drained.row.owner_epoch, owner_host_id: drained.row.owner_host_id, manifest: null });
+ expect({ ...after.binding, state: drained.binding.state, prepared_at: drained.binding.prepared_at }).toEqual({ ...drained.binding, prepared_at: drained.binding.prepared_at });
+ expect(await maintenancePreflight(engine, SOURCE)).toMatchObject({ binding: { worktree_id: drained.binding.worktree_id } });
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));
+ // Recovery: the owner can prepare the transfer again at the same epoch.
+ const again = await prepare(engine);
+ expect(again.owner_epoch).toBe(prepared.owner_epoch);
+ expect((await worktree(engine)).row.state).toBe('draining');
+ }, { setup: seed, databaseUrl }), 120_000);
+
+ test('C-5 race: an accept with the cancelled epoch refuses writer_transfer_conflict and changes nothing', () => managedBrain(async ({ engine, root }) => {
+ const prepared = await prepare(engine);
+ await runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: prepared.owner_epoch, ...await reviewedWriterIntent(engine, 'writer_transfer_cancel') });
+ const settled = await worktree(engine);
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_accept', { source_id: SOURCE, path: root, expected_epoch: prepared.owner_epoch,
+ manifest: prepared.manifest.digest, ...await reviewedWriterIntent(engine, 'writer_transfer_accept') })).rejects.toMatchObject({ code: 'writer_transfer_conflict' });
+ expect(await worktree(engine)).toEqual(settled);
+ }, { setup: seed, databaseUrl }), 120_000);
+
+ test('C-5 refusals: cancel needs a drain at the stated epoch on the owner host and changes nothing otherwise', () => managedBrain(async ({ engine }) => {
+ const intent = async () => reviewedWriterIntent(engine, 'writer_transfer_cancel');
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: '1', ...await intent() }))
+ .rejects.toMatchObject({ code: 'writer_transfer_conflict', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', SOURCE, '--json'] } });
+ const prepared = await prepare(engine);
+ const drained = await worktree(engine);
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: String(Number(prepared.owner_epoch) + 1), ...await intent() }))
+ .rejects.toMatchObject({ code: 'writer_transfer_conflict' });
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: prepared.owner_epoch }))
+ .rejects.toMatchObject({ code: 'writer_admin_intent_required' });
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: 'one', ...await intent() }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ await topology(engine, 'UPDATE persistence_worktrees SET owner_host_id=gen_random_uuid() WHERE id=$1::uuid', [drained.binding.worktree_id]);
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: prepared.owner_epoch, ...await intent() }))
+ .rejects.toMatchObject({ code: 'permission_denied' });
+ await topology(engine, 'UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [drained.binding.worktree_id, drained.row.owner_host_id]);
+ expect(await worktree(engine)).toEqual(drained);
+ }, { setup: seed, databaseUrl }), 120_000);
+
+ for (const { name, error } of runScopedErrors().filter(entry => entry.name !== 'owner_unavailable')) {
+ test(`C-5 run: a run-scoped error (${name}) at the cancel's state write stops it and the drain stays as it was`, () => managedBrain(async ({ engine }) => {
+ const prepared = await prepare(engine);
+ const drained = await worktree(engine);
+ const injected = error();
+ const restore = failTransactionAt(engine, /SET state='active'/, () => injected);
+ try {
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_cancel', { source_id: SOURCE, expected_epoch: prepared.owner_epoch,
+ ...await reviewedWriterIntent(engine, 'writer_transfer_cancel') })).rejects.toBe(injected);
+ } finally { restore(); }
+ expect(await worktree(engine)).toEqual(drained);
+ }, { setup: seed, databaseUrl }), 120_000);
+ }
+
+ test('C-5 CLI: transfer cancel parses to writer_transfer_cancel with its epoch', () => {
+ expect(parsePersistenceAdminArgs('writer', ['transfer', 'cancel', SOURCE, '--expected-epoch', '3', '--admin-intent', 'writer_transfer_cancel', '--expected-state', 'a'.repeat(64)]))
+ .toMatchObject({ operation: 'writer_transfer_cancel', params: { source_id: SOURCE, expected_epoch: '3', admin_intent: 'writer_transfer_cancel' } });
+ });
+ });
+}
diff --git a/test/pathological/c7-content-receipt-root.test.ts b/test/pathological/c7-content-receipt-root.test.ts
new file mode 100644
index 0000000000..ac692d5700
--- /dev/null
+++ b/test/pathological/c7-content-receipt-root.test.ts
@@ -0,0 +1,212 @@
+/**
+ * GBRA-130 C-7: the shared-skills content receipt after a writer transfer or relocation.
+ *
+ * Protects: a gbrain-owned content-directory source keeps a content receipt
+ * (config `shared_skills.content.v1.<source>.<incarnation>`) naming its root and
+ * the root's device/inode. A cross-host transfer (or `sources set-path`) moved the
+ * checkout but left the receipt on the old root, so doctor `sync_freshness`
+ * failed forever and prescribed `gbrain sync --no-pull`, which refuses
+ * `sync_not_applicable`. Now accept and set-path rebind every owned receipt of
+ * the moved sources (nested ones by relative_path) in their own transaction, so
+ * a failed accept rolls the receipt back with it; a receipt that is already
+ * stale gets doctor's typed `content_receipt_stale` with the explicit,
+ * preview-bound `gbrain repair content-receipt-root`, which rebinds only when
+ * the owner's tree still hashes to the recorded worktree manifest and otherwise
+ * refuses naming the mismatch and its exit.
+ * Fails when: accept or set-path leaves a receipt on the old root, a failed
+ * accept keeps a rebound receipt, doctor points at sync again, or the repair
+ * rebinds without the tree evidence or touches anything but the receipt.
+ * Why new: nothing covered the receipt across a topology change (#6892).
+ * Seams: none (the run cases wrap the engine's transaction to inject a
+ * run-scoped error mid-transaction).
+ */
+import { describe, expect, test } from 'bun:test';
+import { cpSync, mkdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { noSuccessfulSync } from '../../src/commands/doctor/sync-outcome.ts';
+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';
+import { claimWorktree, getWorktreeBinding, worktreeManifest } from '../../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+import { resolveRepairScope, runRepair } from '../../src/core/repair/core.ts';
+import { ownedContentFreshness } from '../../src/core/shared-skills/content-freshness.ts';
+import { contentSetupKey } from '../../src/core/shared-skills/setup.ts';
+import { failTransactionAt } from '../helpers/fail-transaction.ts';
+import { reviewedWriterIntent } from '../helpers/writer-admin-intent.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, renderFix, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SLUGS = ['notes/alice-example', 'notes/acme-example'];
+const OLD_ROOT = '/srv/old-host-example/content';
+
+async function seed({ engine, root }: { engine: BrainEngine; root: string }, nested: boolean) {
+ for (const slug of SLUGS) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `body of ${slug}` }, { sourceId: 'default' });
+ writeFileSync(join(root, 'notes.md'), '# notes\n');
+ mkdirSync(join(root, 'sub'));
+ writeFileSync(join(root, 'sub', 'nested.md'), '# nested\n');
+ if (!nested) return;
+ await claimWorktree(engine, 'default', root);
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('nested','nested',$1)", [join(root, 'sub')]);
+ await claimWorktree(engine, 'nested', join(root, 'sub'));
+}
+
+/** A complete, ready, owned content receipt for a source, naming `root` with the device/inode of `identityOf` (default: root itself). */
+async function writeReceipt(engine: BrainEngine, sourceId: string, root: string, identity?: { device: number; inode: number }) {
+ const [{ brain_id }] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const stat = identity ? null : statSync(root);
+ await engine.setConfig(contentSetupKey(sourceId, incarnation), JSON.stringify({ version: 1, brain_id, source_id: sourceId, source_incarnation: incarnation, root,
+ repository_kind: 'content_directory', backup: 'not_verified', status: 'ready', stage: 'complete', pending_actions: [], owned_root: true,
+ root_identity: identity ?? { device: stat!.dev, inode: stat!.ino } }));
+ return contentSetupKey(sourceId, incarnation);
+}
+
+async function receipt(engine: BrainEngine, sourceId: string) {
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const raw = await engine.getConfig(contentSetupKey(sourceId, incarnation));
+ return raw ? JSON.parse(raw) as { root: string; root_identity: { device: number; inode: number } } : null;
+}
+
+const identityOf = (path: string) => { const stat = statSync(path); return { device: stat.dev, inode: stat.ino }; };
+const fresh = async (engine: BrainEngine) => (await ownedContentFreshness(engine)).map(row => row.sourceId).sort();
+
+async function topology(engine: BrainEngine, sql: string, params: unknown[]) {
+ await engine.transaction(async tx => { await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)"); await tx.executeRaw(sql, params); });
+}
+
+/** Copies the canonical content (not the ownership markers) to a successor directory. */
+function successorOf(root: string, name: string): string {
+ const next = join(root, '..', name);
+ mkdirSync(join(next, 'sub'), { recursive: true });
+ cpSync(join(root, 'notes.md'), join(next, 'notes.md'));
+ cpSync(join(root, 'sub', 'nested.md'), join(next, 'sub', 'nested.md'));
+ return realpathSync(next);
+}
+
+async function prepare(engine: BrainEngine) {
+ return await runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'default', ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }) as { owner_epoch: string; manifest: { digest: string } };
+}
+
+async function accept(engine: BrainEngine, path: string, prepared: { owner_epoch: string; manifest: { digest: string } }, extra: Record<string, unknown> = {}) {
+ return runPersistenceAdministration(engine, 'writer_transfer_accept', { source_id: 'default', path, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest,
+ ...extra, ...await reviewedWriterIntent(engine, 'writer_transfer_accept') });
+}
+
+const ctxOf = (engine: BrainEngine) => ({ engine, sourceId: 'default', remote: false as const, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }) as never;
+
+async function repairKind(engine: BrainEngine, opts: { apply: boolean; expect?: string }) {
+ const { contentReceiptRootRepair } = await import('../../src/core/repair/content-receipt-root.ts');
+ const { repairSpec } = await import('../../src/core/repair/registry.ts');
+ return runRepair(ctxOf(engine), contentReceiptRootRepair, await resolveRepairScope(engine, 'default'),
+ { ...opts, explicit: true, spec: repairSpec('content-receipt-root' as never), sourceFlag: 'default' });
+}
+
+const refusedFix = (result: { details?: Record<string, unknown> }) => renderFix((result.details?.refused as Array<{ fix?: unknown }> | undefined)?.[0]?.fix);
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`C-7 content receipt follows the canonical root (${backend})`, () => {
+ test('C-7 accept: a transfer rebinds every owned receipt on the worktree, nested included; set-path then makes the sources fresh', () => managedBrain(async ({ engine, root }) => {
+ await writeReceipt(engine, 'default', root);
+ await writeReceipt(engine, 'nested', join(root, 'sub'));
+ expect(await fresh(engine)).toEqual(['default', 'nested']);
+ const before = await snapshotItems(engine, 'default');
+ const prepared = await prepare(engine);
+ const successor = successorOf(root, 'successor');
+ await expectUnitNotAborted(() => accept(engine, successor, prepared));
+ expect({ default: await receipt(engine, 'default'), nested: await receipt(engine, 'nested') }).toMatchObject({
+ default: { root: successor, root_identity: identityOf(successor) }, nested: { root: join(successor, 'sub'), root_identity: identityOf(join(successor, 'sub')) } });
+ // Until set-path moves sources.local_path the receipt and the source disagree: doctor names the repair, whose preview names set-path.
+ const never = await noSuccessfulSync(engine, 'default', "'default'", true);
+ expectItemFailure({ key: never.entry.source_id, code: never.entry.code, fix: never.entry.fix }, { key: 'default', code: 'content_receipt_stale', fix: /^gbrain repair content-receipt-root --source default$/ });
+ const preview = await repairKind(engine, { apply: false });
+ expect(preview.listing).toEqual([expect.objectContaining({ item: 'default', class: 'source_path_mismatch' })]);
+ expect(refusedFix(preview)).toBe(`gbrain sources set-path default ${successor}`);
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ }, { setup: brain => seed(brain, true), databaseUrl }), 180_000);
+
+ test('C-7 accept then set-path: a transferred content source is fresh again with no manual receipt edit', () => managedBrain(async ({ engine, root }) => {
+ await writeReceipt(engine, 'default', root);
+ const before = await snapshotItems(engine, 'default');
+ const prepared = await prepare(engine);
+ const successor = successorOf(root, 'successor');
+ const accepted = await accept(engine, successor, prepared);
+ expect(accepted.content_receipts).toEqual([expect.objectContaining({ source_id: 'default', from: root, to: successor })]);
+ await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'default', path: successor });
+ expect(await fresh(engine)).toEqual(['default']);
+ expect((await repairKind(engine, { apply: false })).listing).toEqual([]);
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ }, { setup: brain => seed(brain, false), databaseUrl }), 180_000);
+
+ test('C-7 set-path: relocating a source on its host rebinds its receipt in the same lifecycle change', () => managedBrain(async ({ engine, root }) => {
+ await writeReceipt(engine, 'default', root);
+ const before = await snapshotItems(engine, 'default');
+ const moved = successorOf(root, 'moved');
+ await expectUnitNotAborted(() => runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'default', path: moved }));
+ expect(await receipt(engine, 'default')).toMatchObject({ root: moved, root_identity: identityOf(moved) });
+ expect(await fresh(engine)).toEqual(['default']);
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ }, { setup: brain => seed(brain, false), databaseUrl }), 180_000);
+
+ for (const { name, error } of runScopedErrors().filter(entry => entry.name !== 'owner_unavailable')) {
+ test(`C-7 run: a run-scoped error (${name}) after the receipt rebind rolls the accept back, receipt included`, () => managedBrain(async ({ engine, root }) => {
+ await writeReceipt(engine, 'default', root);
+ const was = await receipt(engine, 'default');
+ const prepared = await prepare(engine);
+ const successor = successorOf(root, 'successor');
+ const injected = error();
+ const restore = failTransactionAt(engine, /SET owner_host_id=/, () => injected);
+ try { await expect(accept(engine, successor, prepared)).rejects.toBe(injected); } finally { restore(); }
+ expect(await receipt(engine, 'default')).toEqual(was);
+ expect((await getWorktreeBinding(engine, 'default'))!).toMatchObject({ state: 'draining', local_path: realpathSync(root) });
+ }, { setup: brain => seed(brain, false), databaseUrl }), 180_000);
+ }
+
+ test('C-7 stale: doctor names the repair; the preview rebinds when the tree hash matches; the apply clears it and nothing else changes', () => managedBrain(async ({ engine, root }) => {
+ const key = await writeReceipt(engine, 'default', OLD_ROOT, { device: 1, inode: 2 });
+ const { worktree_id } = (await getWorktreeBinding(engine, 'default'))!;
+ await topology(engine, 'UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [worktree_id, JSON.stringify(worktreeManifest(root))]);
+ expect(await fresh(engine)).toEqual([]);
+ const never = await noSuccessfulSync(engine, 'default', "'default'", true);
+ expectItemFailure({ key: never.entry.source_id, code: never.entry.code, fix: never.entry.fix }, { key: 'default', code: 'content_receipt_stale', fix: /^gbrain repair content-receipt-root --source default$/ });
+ const before = await snapshotItems(engine, 'default');
+ const configBefore = await engine.executeRaw<{ key: string; value: string }>("SELECT key,value FROM config WHERE key<>$1 ORDER BY key", [key]);
+ const preview = await repairKind(engine, { apply: false });
+ expect(preview.listing).toEqual([expect.objectContaining({ item: 'default', class: 'rebind' })]);
+ expect(preview.apply_command).toContain(`--expect ${preview.preview_hash}`);
+ expect(await receipt(engine, 'default')).toMatchObject({ root: OLD_ROOT });
+ await expect(repairKind(engine, { apply: true, expect: 'f'.repeat(64) })).rejects.toMatchObject({ code: 'preview_changed' });
+ const injected = runScopedErrors()[0]!.error();
+ const restore = failTransactionAt(engine, /UPDATE config SET value/, () => injected);
+ try { await expect(repairKind(engine, { apply: true, expect: preview.preview_hash })).rejects.toBe(injected); } finally { restore(); }
+ expect(await receipt(engine, 'default')).toMatchObject({ root: OLD_ROOT });
+ const applied = await expectUnitNotAborted(() => repairKind(engine, { apply: true, expect: preview.preview_hash }));
+ expect({ applied: applied.applied, failed: applied.failed }).toEqual({ applied: 1, failed: [] });
+ expect(await receipt(engine, 'default')).toMatchObject({ root: realpathSync(root), root_identity: identityOf(root) });
+ expect(await fresh(engine)).toEqual(['default']);
+ const backup = JSON.parse((await engine.getConfig(`${key}.backup`))!);
+ expect(JSON.parse(backup.previous)).toMatchObject({ root: OLD_ROOT, root_identity: { device: 1, inode: 2 } });
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ expect(await engine.executeRaw<{ key: string; value: string }>("SELECT key,value FROM config WHERE key<>$1 AND key<>$2 ORDER BY key", [key, `${key}.backup`])).toEqual(configBefore);
+ expect((await repairKind(engine, { apply: false })).listing).toEqual([]);
+ }, { setup: brain => seed(brain, false), databaseUrl }), 180_000);
+
+ test('C-7 recovery: a tree that no longer matches its manifest is refused naming both digests; a self-transfer re-verifies and rebinds it', () => managedBrain(async ({ engine, root }) => {
+ await writeReceipt(engine, 'default', OLD_ROOT, { device: 1, inode: 2 });
+ const { worktree_id } = (await getWorktreeBinding(engine, 'default'))!;
+ const recorded = worktreeManifest(root);
+ await topology(engine, 'UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [worktree_id, JSON.stringify(recorded)]);
+ writeFileSync(join(root, 'later.md'), '# written after the manifest\n');
+ const preview = await repairKind(engine, { apply: false });
+ expect(preview.listing).toEqual([expect.objectContaining({ item: 'default', class: 'tree_mismatch' })]);
+ expect(preview.listing![0]!.detail).toContain(recorded.digest);
+ expect(preview.listing![0]!.detail).toContain(worktreeManifest(root).digest);
+ expect(refusedFix(preview)).toStartWith('gbrain sources writer transfer prepare default --self-transfer');
+ expect(await receipt(engine, 'default')).toMatchObject({ root: OLD_ROOT });
+ const prepared = await runPersistenceAdministration(engine, 'writer_transfer_prepare',
+ { source_id: 'default', self_transfer: true, ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }) as { owner_epoch: string; manifest: { digest: string } };
+ await accept(engine, realpathSync(root), prepared, { self_transfer: true });
+ expect(await receipt(engine, 'default')).toMatchObject({ root: realpathSync(root), root_identity: identityOf(root) });
+ expect(await fresh(engine)).toEqual(['default']);
+ }, { setup: brain => seed(brain, false), databaseUrl }), 180_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6b437b9f9d..5a9b7142f1 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -235,6 +235,8 @@ test/pathological/a49-unmanaged-purge-tombstones.test.ts
test/pathological/a50-unmanaged-expired-sources.test.ts
test/pathological/a9-repair-core.test.ts
test/pathological/b6-triage-verdict-surrogate.test.ts
+test/pathological/c5-writer-transfer-cancel.test.ts
+test/pathological/c7-content-receipt-root.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 9e94276321..f1c5479a7c 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
diff --git a/test/writer-failures-cli-6650.test.ts b/test/writer-failures-cli-6650.test.ts
index d9f045a024..b208b61b1e 100644
--- a/test/writer-failures-cli-6650.test.ts
+++ b/test/writer-failures-cli-6650.test.ts
@@ -126,15 +126,16 @@ describe('capability handshake across releases', () => {
'company_brain_resume', 'writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',
'trust_read', 'trust_preview', 'trust_apply'];
- test('a new owner keeps the frozen list and advertises writer_failures as an extension', async () => {
+ test('a new owner keeps the frozen list and advertises writer_failures and writer_transfer_cancel as extensions', async () => {
expect([...PERSISTENCE_ADMIN_OPERATIONS as readonly string[]].sort()).toEqual([...FROZEN].sort());
const path = socketPath();
const binding = await startPersistenceIpcServer(path, { brainId: BRAIN, dispatch: async () => ({}), administer: async () => ({}) });
bindings.push(binding!);
const capability = await requestPersistenceCapabilities(path);
expect((capability.administration ?? []).every(op => FROZEN.includes(op))).toBe(true);
- expect(capability.administration_extensions).toEqual(['writer_failures']);
+ expect(capability.administration_extensions).toEqual(['writer_failures', 'writer_transfer_cancel']);
expect(ownerAdministers(capability, 'writer_failures')).toBe(true);
+ expect(ownerAdministers(capability, 'writer_transfer_cancel')).toBe(true);
expect(ownerAdministers(capability, 'writer_status')).toBe(true);
});