Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): owner_unavailable reasons matrix and fence repair during a sync (#6278 PR 2)
garrytan7127370ec2a0
diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex bbc795fbc1..e9bdf36044 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -555,6 +555,7 @@ const ROWS: Row[] = [protocol_version: e.protocolVersion === 1 ? 1 : undefined,write_request: j.write_request, write_error: e.writeError,...(e.fence ? { fence: e.fence } : {}), ...(e.fenceIssues?.length ? { fence_issues: e.fenceIssues } : {}),+ ...(e.retryable !== undefined ? { retryable: e.retryable } : {}),};},},diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 11f5189066..78a03a8d41 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -252,7 +252,11 @@ export const CODES = {no_brain: { class: 'caller', summary: "No brain is configured on this machine.", suggestion: 'Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options).' },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 brain's persistence owner is not reachable right now." },+ 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.",+ 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.' },page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },@@ -336,7 +340,10 @@ export const CODES = {state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },storage_error: { class: 'server', summary: "Reading or writing durable storage failed." },sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },- sync_in_progress: { class: 'retryable', summary: "A sync is running on this source." },+ sync_in_progress: { class: 'retryable', summary: "A sync is running on this source, or a write in flight or the sync's frozen manifest still names the file a repair would write.",+ why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",+ 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.' },sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported, so the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull --retry-failed.' },take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },diff --git a/src/core/fence-repair/hold-fix.ts b/src/core/fence-repair/hold-fix.tsindex e77afed557..77e9d47819 100644--- a/src/core/fence-repair/hold-fix.ts+++ b/src/core/fence-repair/hold-fix.ts@@ -78,7 +78,8 @@ export interface FenceHoldStatus {}const PAID: readonly FenceReason[] = ['budget_exhausted', 'llm_disabled', 'no_pricing', 'no_measured_model'];-const OWNER: readonly FenceReason[] = ['owner_unavailable', 'owner_cli_required'];+const OWNER: readonly FenceReason[] = ['owner_unavailable', 'owner_cli_required', 'host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'incarnation_changed',+ 'local_path_missing', 'coordination_path_missing'];type HoldMeta = Pick<GitHoldRecord['meta'], 'reason' | 'line' | 'fence' | 'fence_repair'>;diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 06302277c7..80de5ad061 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -93,7 +93,13 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {ledger_unavailable: entry(run(true), 'The spend ledger could not be read, so no model call was made. The next repair run retries.'),owner_unavailable: entry(run(true, null), 'Fence repairs run on the brain\'s owner host. Run `gbrain repair fences` there.', { actor: 'host_admin' }),owner_cli_required: entry(run(false, null), 'This repair must be applied from the owner host CLI. Run `gbrain repair fences --apply` there.', { actor: 'host_admin' }),- sync_in_progress: entry(run(true, null), 'A sync of this source is still running; the repair waits for it and retries on the next run.'),+ host_mismatch: entry(run(false, null), 'Another host id owns this source\'s checkout (the hold names both ids), so this host never repairs it. Run `gbrain repair fences --source <source>` on the owner host that `gbrain sources writer status --source <source> --json` names, or give the worker and the shell one GBRAIN_HOME so they share one host identity; never copy or regenerate host.json.', { actor: 'host_admin' }),+ transfer_in_progress: entry(run(true, null), 'A writer transfer of this source is prepared (its worktree is draining), so no host may write it yet. Nothing to do: the next run repairs it once the transfer is accepted or cancelled (`gbrain sources writer status --source <source> --json` shows the state).', { actor: 'host_admin' }),+ clone_in_progress: entry(run(true, null), 'A topology clone of this source\'s checkout is in progress (its worktree is recovering). Nothing to do: the next run repairs it once the clone finishes (`gbrain sources writer status --source <source> --json` shows the state).', { actor: 'host_admin' }),+ incarnation_changed: entry(run(false, null), 'This source\'s checkout binding is from an earlier incarnation of the source (it was removed and re-added, or restored), so no host may write it. On the brain host, review `gbrain sources writer status --source <source> --json` and re-bind the checkout; the next run after that repairs the file.', { actor: 'host_admin' }),+ local_path_missing: entry(run(false, null), 'This host owns the source\'s checkout but has no path registered for it. On the brain host, review `gbrain sources writer status --source <source> --json` and register the checkout again; the next run after that repairs the file.', { actor: 'host_admin' }),+ coordination_path_missing: entry(run(false, null), 'This host\'s registration for the source has no coordination directory. On the brain host, review `gbrain sources writer status --source <source> --json` and repair the registration; the next run after that repairs the file.', { actor: 'host_admin' }),+ sync_in_progress: entry(run(true, null), 'A sync of this source or a write in flight still names this file (a path still ahead in the sync\'s frozen manifest counts; a held path does not); the repair of every other file goes on, and this one is retried on the next run.'),time_budget: entry(run(true, null), 'The repair run reached its time budget; the next run resumes where it stopped.'),changed_since_read: entry(run(true, null), 'The file changed after the repair read it, so nothing was written. The next repair run reads it again.'),changed_since_preview: entry(run(false, null), 'The page changed after the preview, so it was not applied. Preview again with `gbrain repair fences` and apply the new plan.'),diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.tsindex 4cbecee84e..1393ddf0d7 100644--- a/src/core/fence-repair/repair-io.ts+++ b/src/core/fence-repair/repair-io.ts@@ -3,11 +3,13 @@* candidate's current bytes, and the four write-back paths.** Sources. On a managed brain a source with a canonical checkout is repaired- * only on its active owner host (`owner_unavailable` elsewhere), and never- * while its managed sync cursor is unfinished or a queued or running write- * names the candidate (`sync_in_progress`, E9). A legacy (unmanaged) source- * writes its recorded checkout. A read-only mirror is repaired in the- * database only.+ * only on its active owner host (`owner_unavailable` elsewhere, with the+ * condition as its reason: persistence/owner-refusal.ts), and a candidate a+ * write in flight or an unfinished sync's frozen manifest still names is+ * `sync_in_progress` (persistence/repair-busy.ts); every other candidate is+ * repaired while the sync runs (#6278). A legacy (unmanaged) source writes+ * its recorded checkout. A read-only mirror is repaired in the database+ * only.** Write-back (spec section 12 step 7):* - managed: `managed_file_repair` writes the exact repaired bytes bound to@@ -36,6 +38,8 @@ import { resolveSlugForPath } from '../sync.ts';import { sha256 } from '../persistence/digest.ts';import { localHostId } from '../persistence/identity.ts';import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';+import { checkOwner, ownerRefusal, type OwnerRefusal } from '../persistence/owner-refusal.ts';+import { loadRepairBusySet, type RepairBusySet } from '../persistence/repair-busy.ts';import { sourceMirrorReadOnly } from '../persistence/mirror-read-only.ts';import { isSourceDbOnlySlug } from '../persistence/source-storage.ts';import { confinedRepairTarget, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';@@ -57,12 +61,10 @@ export interface FenceSource {mirror: boolean;/** The checkout this host reads and (unless a mirror) writes; null when the source has none here. */root: string | null;- /** Managed brain: another host owns this source's checkout, or its owner is not active. */- ownerElsewhere: boolean;- /** Managed brain: a managed sync of this source has not finished (E9). */- syncUnfinished: boolean;- /** Paths and slugs a queued, running or recovering write of this source names. */- busy: { paths: Set<string>; slugs: Set<string> };+ /** Managed brain: why this host may not write the source's checkout (another owner, a transfer or clone in progress, an incomplete registration); null when it may. */+ owner: OwnerRefusal | null;+ /** Managed brain: the paths and slugs in-flight writes and unfinished sync manifests name (every candidate while `unknown`). */+ busy: RepairBusySet;activePack?: Awaited<ReturnType<typeof repairScreenConfig>>['activePack'];}@@ -70,33 +72,34 @@ function inGit(root: string): boolean {try { execFileSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], { stdio: 'ignore' }); return true; } catch { return false; }}-/** This host's view of one source for fence repair; null when the source is gone or archived. */-export async function loadFenceSource(engine: BrainEngine, sourceId: string): Promise<FenceSource | null> {+/**+ * This host's view of one source for fence repair; null when the source is gone or archived. `remote` (default+ * true, the fail-closed reading of an unknown caller) keeps local paths out of the owner refusal's text.+ */+export async function loadFenceSource(engine: BrainEngine, sourceId: string, opts: { remote?: boolean } = {}): Promise<FenceSource | null> {const [row] = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>('SELECT id, incarnation::text AS incarnation, local_path FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);if (!row) return null;const managed = await managedPersistenceEnabled(engine);const mirror = await sourceMirrorReadOnly(engine, sourceId);let root: string | null = null;- let ownerElsewhere = false;+ let owner: OwnerRefusal | null = null;if (managed) {const binding = await getWorktreeBinding(engine, sourceId);+ // A source with no binding at all has no checkout anywhere: it is repaired in the database (db mode), not refused.if (binding) {- if (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) ownerElsewhere = true;- else root = join(binding.local_path, binding.relative_path);+ const hostId = localHostId();+ const checked = checkOwner(binding, row.incarnation, hostId);+ if (checked.reason) owner = ownerRefusal({ sourceId, reason: checked.reason, binding, incarnation: row.incarnation, hostId, remote: opts.remote !== false, work: 'fence repair' });+ else root = join(checked.binding.local_path, checked.binding.relative_path);}} else {const local = row.local_path ?? (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);root = local && existsSync(local) ? local : null;}- const [cursor] = managed ? await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync'- AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [sourceId]) : [{ n: 0 }];- const pending = await engine.executeRaw<{ slug: string; path: string | null; source_path: string | null }>(`SELECT slug, intent->>'path' AS path, intent->>'sourcePath' AS source_path- FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]).catch(() => []);+ const busy: RepairBusySet = managed ? await loadRepairBusySet(engine, sourceId, row.incarnation) : { paths: new Set(), slugs: new Set(), unknown: null };const config = await repairScreenConfig(engine, sourceId);- return { id: row.id, incarnation: row.incarnation, managed, mirror, root, ownerElsewhere, syncUnfinished: Number(cursor?.n ?? 0) > 0,- busy: { paths: new Set(pending.flatMap(p => [p.path, p.source_path].filter((v): v is string => !!v))), slugs: new Set(pending.map(p => p.slug)) },- ...(config.activePack ? { activePack: config.activePack } : {}) };+ return { id: row.id, incarnation: row.incarnation, managed, mirror, root, owner, busy, ...(config.activePack ? { activePack: config.activePack } : {}) };}/** One candidate's current bytes: a working-tree file, or a stored page. */@@ -249,6 +252,7 @@ export async function writeFenceRepair(ctx: OperationContext, src: FenceSource,if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'source_changed'].includes(error.code)) {return { ok: false, reason: 'changed_since_read', message: `${target.path} changed while it was being repaired; the next run reads it again.` };}+ if (error instanceof OperationError && error.code === 'sync_in_progress') return { ok: false, reason: 'sync_in_progress', message: error.message };throw error;}}diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsindex 82b7f9de3c..2f02e9a148 100644--- a/src/core/fence-repair/types.ts+++ b/src/core/fence-repair/types.ts@@ -50,6 +50,8 @@ export type FenceReason =// Repair runs.| 'llm_unavailable' | 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_truncated' | 'llm_declined' | 'llm_disabled' | 'no_measured_model'| 'budget_exhausted' | 'no_pricing' | 'ledger_unavailable' | 'owner_unavailable' | 'owner_cli_required'+ // Owner conditions (#6278; the `owner_unavailable` reasons the owner-refusal matrix names).+ | 'host_mismatch' | 'transfer_in_progress' | 'clone_in_progress' | 'incarnation_changed' | 'local_path_missing' | 'coordination_path_missing'| 'sync_in_progress' | 'time_budget' | 'changed_since_read' | 'changed_since_preview'// Validator gates.| 'still_invalid' | 'claim_changed' | 'row_number_changed' | 'visibility_loosened'diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 2ae6b49ec5..5cae0fbec2 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -81,6 +81,8 @@ export class OperationError extends Error {public why?: string;/** Agent contract v1: the one next step. Rendered (`next`, `command`) only at serialization. */public fix?: Action;+ /** Site-level override of the code's class-derived `retryable` (#6278: `owner_unavailable` / `host_mismatch` is never worth a retry). */+ public retryable?: boolean;/** Agent contract v1: advice that rides the error (rendered into the envelope's `notices`). */public notices?: Notice[];/** #6188 (D16, D18): a fence refusal's location and its blocking issues; location and class only, never a cell value. */@@ -159,6 +161,8 @@ export interface OpErrorOpts {fix?: Action;docs?: string;detail?: string;+ /** Overrides the class-derived `retryable` on the envelope for this site. */+ retryable?: boolean;/*** The frozen v1 `error` wire value when this site historically threw a* different code (A1 frozen pairs). `error` keeps this value; `code` is the@@ -179,6 +183,7 @@ export function opError(code: RegistryCode, message: string, suggestion: string,if (opts.why !== undefined) e.why = opts.why;if (opts.fix !== undefined) e.fix = opts.fix;if (opts.detail !== undefined) e.detail = opts.detail;+ if (opts.retryable !== undefined) e.retryable = opts.retryable;e.contractVersion = 1;return e;}diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 6439205fae..25591dbe1f 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -55,6 +55,8 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';+import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';+import { loadRepairBusySet, repairBusy, repairBusyError } from './repair-busy.ts';import { submitPageMutation } from './page-mutations.ts';import { clearGitHold, recordSyncImportProvenance } from './sync-holds.ts';import { screenSyncImport } from './sync-prepare.ts';@@ -212,21 +214,26 @@ function assertTrustedRepairCaller(ctx: Pick<OperationContext, 'remote'>): void}}-/** The active local owner's canonical root of a source, or a refusal naming writer status. */-export async function managedRepairRoot(engine: BrainEngine, sourceId: string, kind: FileRepairKind = 'frontmatter'): Promise<{ root: string; ownerEpoch: string }> {+/**+ * The active local owner's canonical root of a source, or an `owner_unavailable` refusal whose reason names the+ * condition (owner-refusal.ts). `remote` (default true) keeps the local identity path out of the text.+ */+export async function managedRepairRoot(engine: BrainEngine, sourceId: string, kind: FileRepairKind = 'frontmatter', opts: { remote?: boolean } = {}): Promise<{ root: string; ownerEpoch: string; incarnation: string }> {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);const binding = await getWorktreeBinding(engine, sourceId);- if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {- throw opError('owner_unavailable', 'A managed file repair must run on the active canonical owner of its source.',- `This host is not the active owner of source ${sourceId}, so nothing was written. Run gbrain repair ${kind} on the owner host that writer status names, or wait until its owner is active.`,- { fix: ownerStatusFix(sourceId) });- }- return { root: join(binding.local_path, binding.relative_path), ownerEpoch: String(binding.owner_epoch) };+ const hostId = localHostId();+ const owner = checkOwner(binding, source?.incarnation ?? '', hostId);+ if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source?.incarnation ?? '', hostId, remote: opts.remote !== false, work: `the ${kind} repair` });+ return { root: join(owner.binding.local_path, owner.binding.relative_path), ownerEpoch: String(owner.binding.owner_epoch), incarnation: owner.binding.source_incarnation };}/*** Admits and waits for one `managed_file_repair` write. Refuses before* admission when the caller is not the trusted local CLI, the path is not a- * confined regular file, or the file no longer has the previewed bytes.+ * confined regular file, the file no longer has the previewed bytes, or a+ * write in flight or an unfinished sync's frozen manifest names the path or+ * page (`sync_in_progress`, #6278: the plan's busy check is repeated here+ * because a sync can start while a repair waits on its model call).*/export interface ManagedFileRepairInput {sourceId: string; requestId: string; slug: string; path: string; sourcePath: string; content: string;@@ -239,9 +246,13 @@ export async function submitManagedFileRepair(ctx: OperationContext, input: ManaassertTrustedRepairCaller(ctx);const kind: FileRepairKind = input.fenceRepair !== undefined ? 'fences' : 'frontmatter';checkedFenceRepair(input, input.sourceId);- const { root, ownerEpoch } = await managedRepairRoot(ctx.engine, input.sourceId, kind);+ const { root, ownerEpoch, incarnation } = await managedRepairRoot(ctx.engine, input.sourceId, kind, { remote: false });const target = confinedRepairTarget(root, input.path, input.sourceId, kind);if (fileSha256(target) !== input.beforeHash) throw changedSincePreview(input.sourceId, input.path, 'the file bytes differ from the previewed hash', kind);+ const busy = await loadRepairBusySet(ctx.engine, input.sourceId, incarnation);+ if (repairBusy(busy, { path: input.path, sourcePath: input.sourcePath, slug: input.slug }) || (input.renameFrom && repairBusy(busy, { sourcePath: input.renameFrom.sourcePath, slug: input.renameFrom.slug }))) {+ throw repairBusyError(busy, input.sourceId, input.path);+ }const { sourceId, requestId, expected_revision, ...rest } = input;const params: Record<string, unknown> = { ...rest, kind: 'managed_file_repair', ownerEpoch, source_id: sourceId, request_id: requestId,...(expected_revision ? { expected_revision } : {}) };diff --git a/src/core/persistence/owner-refusal.ts b/src/core/persistence/owner-refusal.tsnew file mode 100644index 0000000000..52f8141778--- /dev/null+++ b/src/core/persistence/owner-refusal.ts@@ -0,0 +1,144 @@+/**+ * #6278: why a source's canonical owner is unavailable to this process, one+ * reason per condition. `maintenancePreflight` (chronicle, fact-fence+ * adoption, every maintenance submitter), `gbrain repair fences` and the+ * managed file repair admission all refuse with the code `owner_unavailable`+ * (the sync drain branches on that code), and this matrix gives each reason+ * its message, `why`, actor, next step and read-only verify, so the same+ * condition reads the same everywhere.+ *+ * Reasons, in the order they are checked:+ * binding_missing the source has no canonical worktree binding+ * incarnation_changed the binding belongs to an earlier incarnation of the source+ * host_mismatch another host id owns the checkout (a host-id split on one+ * machine looks exactly like this; both ids are printed)+ * transfer_in_progress the worktree is `draining` (a writer transfer is prepared)+ * clone_in_progress the worktree is `recovering` (a topology clone or reclone)+ * local_path_missing this host has no registered checkout path for the worktree+ * 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+ * (`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+ * identity file path is printed to local callers only (it carries a home+ * directory). The owner's own identity path is never known here, so it is+ * never printed.+ */+import { join } from 'node:path';+import type { Action } from '../agent-output.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { persistenceHome } from './identity.ts';+import type { WorktreeBinding } from './ownership.ts';++export const OWNER_UNAVAILABLE_REASONS = ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'binding_missing', 'incarnation_changed',+ 'coordination_path_missing', 'local_path_missing'] as const;+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;++/** 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 };++/** The first condition that makes the binding unusable by host `hostId` for source incarnation `incarnation`, or the usable binding. */+export function checkOwner(binding: WorktreeBinding | null, incarnation: string, hostId: string): { reason: OwnerUnavailableReason } | { reason: null; binding: ActiveOwnerBinding } {+ if (!binding) return { reason: 'binding_missing' };+ if (String(binding.source_incarnation) !== String(incarnation)) return { reason: 'incarnation_changed' };+ if (binding.owner_host_id !== hostId) return { reason: 'host_mismatch' };+ if (binding.state === 'draining') return { reason: 'transfer_in_progress' };+ if (binding.state === 'recovering') return { reason: 'clone_in_progress' };+ if (!binding.local_path) return { reason: 'local_path_missing' };+ if (!binding.coordination_path) return { reason: 'coordination_path_missing' };+ return { reason: null, binding: binding as ActiveOwnerBinding };+}++/** The reason alone; null when the binding is usable. */+export function ownerUnavailableReason(binding: WorktreeBinding | null, incarnation: string, hostId: string): OwnerUnavailableReason | null {+ return checkOwner(binding, incarnation, hostId).reason;+}++export interface OwnerRefusalInput {+ sourceId: string;+ reason: OwnerUnavailableReason;+ binding: WorktreeBinding | null;+ /** The source's current incarnation. */+ incarnation: string;+ /** This process's host id (`localHostId()`). */+ hostId: string;+ /** `OperationContext.remote`: a remote caller never sees a local path. */+ remote: boolean;+ /** What was refused, in the message: "maintenance", "fence repair", "the file repair". */+ work: string;+}++export interface OwnerRefusal {+ reason: OwnerUnavailableReason;+ message: string;+ why: string;+ fix: Action;+ retryable: boolean;+}++const short = (id: string | null | undefined) => (id ?? 'unknown').slice(0, 8);++function writerStatus(sourceId: string): string[] {+ return ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'];+}++/** The matrix row for one refusal: message, why, fix (with its read-only verify) and whether a retry can help. */+export function ownerRefusal(input: OwnerRefusalInput): OwnerRefusal {+ const { sourceId, reason, binding, work } = input;+ const status = writerStatus(sourceId);+ const verify = { argv: status };+ const admin = (why: string, user: string): Action => ({ argv: status, consent: [], actor: 'host_admin', requires_exclusive: false, why, user_message: user, verify });+ const wait = (why: string): Action => ({ argv: status, consent: [], actor: 'provider', requires_exclusive: false,+ why: `${why} Wait ${OWNER_WAIT_SECONDS} seconds, run this status read, and retry the same request once the worktree state is active.`, verify });+ const never = `Nothing was written and no model work ran; ${work} never claims or transfers ownership to run.`;+ switch (reason) {+ case 'binding_missing':+ return { reason, retryable: false, message: `Source ${sourceId} has no canonical owner, so ${work} did not run.`,+ why: `No worktree binding records a canonical checkout for source ${sourceId}. ${never}`,+ fix: admin('Shows whether the source has a canonical binding and which host owns it; claiming one is the host administrator\'s decision.',+ `gbrain could not run ${work} for source ${sourceId}: no host owns its checkout. Review writer status on the brain host and decide whether to claim it.`) };+ case 'incarnation_changed':+ return { reason, retryable: false, message: `Source ${sourceId}'s canonical binding belongs to an earlier incarnation of the source, so ${work} did not run.`,+ why: `The binding records incarnation ${short(binding?.source_incarnation)} but the source is now incarnation ${short(input.incarnation)} (it was removed and re-added, or restored), so the checkout it names is not this source's. ${never}`,+ fix: admin('Shows the binding\'s incarnation beside the source\'s; re-binding the checkout is the host administrator\'s decision.',+ `gbrain could not run ${work} for source ${sourceId}: its checkout binding is from before the source was re-created. Review writer status on the brain host.`) };+ case 'host_mismatch': {+ const local = input.remote ? '' : ` (this process read its identity from ${join(persistenceHome(), 'host.json')})`;+ return { reason, retryable: false, message: `Source ${sourceId} is owned by host ${short(binding?.owner_host_id)}, not this host (${short(input.hostId)}), so ${work} did not run.`,+ why: `The canonical checkout of source ${sourceId} belongs to host id ${short(binding?.owner_host_id)}; this process runs as host id ${short(input.hostId)}${local}. `+ + `If both run on one machine, the two environments read different GBRAIN_HOME identity files (a launchd or cron worker with another GBRAIN_HOME or user than the shell), and retrying from this one cannot change the answer. ${never}`,+ 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.`,+ 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.`) };+ 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}`,+ fix: wait(`Source ${sourceId}'s worktree is recovering while a topology clone runs; the status read shows when it is active again.`) };+ case 'local_path_missing':+ return { reason, retryable: false, message: `This host has no registered checkout path for source ${sourceId}, so ${work} did not run.`,+ why: `Host ${short(input.hostId)} owns source ${sourceId}'s worktree but has no local path registered for it (the host binding row is missing or empty). ${never}`,+ fix: admin('Shows the host bindings of the worktree; registering the checkout path again is the host administrator\'s decision.',+ `gbrain could not run ${work} for source ${sourceId}: this host owns the checkout but has no path registered for it. Review writer status on the brain host.`) };+ case 'coordination_path_missing':+ return { reason, retryable: false, message: `This host's registration for source ${sourceId} has no coordination directory, so ${work} did not run.`,+ why: `Host ${short(input.hostId)} owns source ${sourceId}'s worktree and has a checkout path, but no coordination path (the directory the physical-root stamp and locks live in); the registration predates it or was edited. ${never}`,+ fix: admin('Shows the host binding with its coordination path; repairing the registration is the host administrator\'s decision.',+ `gbrain could not run ${work} for source ${sourceId}: this host's checkout registration is incomplete. Review writer status on the brain host.`) };+ }+}++/** The `owner_unavailable` error for one refusal (message, why, reason, fix and the site's retryable). */+export function ownerUnavailableError(input: OwnerRefusalInput): OperationError {+ const row = ownerRefusal(input);+ return opError('owner_unavailable', row.message, `${row.why} Read writer status with the command in fix${row.retryable ? ', wait, and retry' : ' and act on what it shows'}.`,+ { reason: row.reason, why: row.why, fix: row.fix, retryable: row.retryable });+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 843df8bfe3..bcf91f63d1 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -13,6 +13,7 @@ import { normalizeClaimWhitespace, parseFactsFence } from '../facts-fence.ts';import { submissionAuthority, authorizeStoredRequest, authorizeWrite } from './authority.ts';import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';+import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';import { admitWrite, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';import { preparePageMutation, prepareFileTarget } from './page-prepare.ts';@@ -99,19 +100,16 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: stringconst writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');const configuredRoot = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);if (writeThrough && (root || configuredRoot || binding)) {- if (!binding || binding.source_incarnation !== source.incarnation || binding.owner_host_id !== localHostId() ||- binding.state !== 'active' || !binding.local_path || !binding.coordination_path) {- throw opError('owner_unavailable', 'The maintenance source needs an active canonical owner before model work.',- `Source '${sourceId}' has no active canonical owner on this host, so no model work ran. Inspect the owner with the command in fix and run maintenance on the host it names; do not claim or transfer ownership just to run maintenance.`,- { fix: ownerStatusFix(sourceId) });- }- if (root && realpathSync(root) !== realpathSync(join(binding.local_path, binding.relative_path))) {+ const hostId = localHostId();+ const owner = checkOwner(binding, source.incarnation, hostId);+ if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source.incarnation, hostId, remote: false, work: 'maintenance' });+ if (root && realpathSync(root) !== realpathSync(join(owner.binding.local_path, owner.binding.relative_path))) {throw opError('source_changed', 'The maintenance directory is not the canonical source root.',`Run maintenance for '${sourceId}' against its registered canonical root (the command in fix shows it), or without a directory argument; nothing was submitted.`,{ fix: ownerStatusFix(sourceId) });}await nativeLockCapability();- assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });+ assertPhysicalRoot(owner.binding.local_path, { worktreeId: owner.binding.worktree_id, coordinationPath: owner.binding.coordination_path });}if (!writeThrough) writer.databaseOnlyReason = 'disabled_by_config';else if (!binding) writer.databaseOnlyReason = 'no_repo_configured';diff --git a/src/core/persistence/repair-busy.ts b/src/core/persistence/repair-busy.tsnew file mode 100644index 0000000000..ca52285886--- /dev/null+++ b/src/core/persistence/repair-busy.ts@@ -0,0 +1,94 @@+/**+ * #6278: which paths and slugs of a managed source a repair must not write+ * right now, so `gbrain repair fences` (and the managed file repair+ * admission under it and under `gbrain repair frontmatter`) runs during a+ * sync for every other candidate instead of skipping the whole source while+ * a managed sync cursor is unfinished.+ *+ * Busy (`sync_in_progress` for that candidate):+ * - every request of the source that is queued, running or recovering, or+ * terminal with an open recovery: its slug, path, origin path and both+ * endpoints of a rename;+ * - every entry at or after the index of each unfinished managed sync+ * cursor of the source's current incarnation, read from the run's frozen+ * manifest: the sync admits those entries later with the raw hash it+ * reads then, and a repair that changed the bytes in between would make+ * the entry refuse on it (`source_changed`); a held path is left out,+ * because the sync does not retry a held entry until its bytes change,+ * and a repair that changes them is exactly what makes the next sync+ * re-screen it.+ *+ * The read fails closed: a query that throws, or an unfinished cursor whose+ * manifest cannot be read, makes every candidate busy (`unknown` names why).+ * Callers check once when they plan and again at coordinated admission of+ * the write, because a new sync can freeze a candidate while a repair waits+ * on its model call.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { GIT_HOLD_OP } from './sync-holds.ts';++export interface RepairBusySet {+ paths: Set<string>;+ slugs: Set<string>;+ /** Set when the busy set could not be read; then every candidate is busy. */+ unknown: string | null;+}++interface PendingRow { slug: string | null; path: string | null; source_path: string | null; rename_slug: string | null; rename_source_path: string | null }+interface CursorRow { run_id: string | null; index: string | number | null }+interface ManifestEntry { path?: string; sourcePath?: string; slug?: string; renameFrom?: { sourcePath?: string; slug?: string } }++const BUSY_UNINFORMED = (why: string) => `the busy set could not be read (${why}), so every candidate of the source is treated as in flight`;++/** The busy set of one source incarnation; never throws. */+export async function loadRepairBusySet(engine: BrainEngine, sourceId: string, incarnation: string): Promise<RepairBusySet> {+ const paths = new Set<string>(), slugs = new Set<string>();+ const add = (path: string | null | undefined, slug?: string | null) => { if (path) paths.add(path); if (slug) slugs.add(slug); };+ try {+ const pending = await engine.executeRaw<PendingRow>(`SELECT slug, intent->>'path' AS path, intent->>'sourcePath' AS source_path,+ intent->'renameFrom'->>'slug' AS rename_slug, intent->'renameFrom'->>'sourcePath' AS rename_source_path+ FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL)`, [sourceId]);+ for (const row of pending) { add(row.path, row.slug); add(row.source_path); add(row.rename_source_path, row.rename_slug); }+ const cursors = await engine.executeRaw<CursorRow>(`SELECT completed_keys->0->>'runId' AS run_id, completed_keys->0->>'index' AS index+ FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'+ AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2`, [sourceId, incarnation]);+ if (!cursors.length) return { paths, slugs, unknown: null };+ const held = new Set((await engine.executeRaw<{ path: string }>(`SELECT completed_keys->0->>'path' AS path FROM op_checkpoints+ WHERE op=$1 AND completed_keys->0->>'source_id'=$2 AND completed_keys->0->>'incarnation'=$3`, [GIT_HOLD_OP, sourceId, incarnation])).map(row => row.path));+ for (const cursor of cursors) {+ const [manifest] = cursor.run_id ? await engine.executeRaw<{ entries: ManifestEntry[] | null }>(+ "SELECT completed_keys AS entries FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.run_id]) : [];+ if (!Array.isArray(manifest?.entries)) return { paths, slugs, unknown: BUSY_UNINFORMED(`the manifest of sync run ${cursor.run_id ?? '<unknown>'} is missing`) };+ const from = Math.max(0, Math.trunc(Number(cursor.index ?? 0)) || 0);+ for (const entry of manifest.entries.slice(from)) {+ if (entry.path && held.has(entry.path)) continue;+ add(entry.path, entry.slug); add(entry.sourcePath); add(entry.renameFrom?.sourcePath, entry.renameFrom?.slug);+ }+ }+ return { paths, slugs, unknown: null };+ } catch (error) {+ return { paths, slugs, unknown: BUSY_UNINFORMED(error instanceof Error ? error.message : String(error)) };+ }+}++/** Whether a candidate (by path, origin path or slug) is busy; always true while the set is unknown. */+export function repairBusy(busy: RepairBusySet, candidate: { path?: string | null; sourcePath?: string | null; slug?: string | null }): boolean {+ if (busy.unknown !== null) return true;+ return (!!candidate.path && busy.paths.has(candidate.path)) || (!!candidate.sourcePath && busy.paths.has(candidate.sourcePath)) || (!!candidate.slug && busy.slugs.has(candidate.slug));+}++/** The `sync_in_progress` message for one busy candidate: what names it and when the next run picks it up. */+export function repairBusyMessage(busy: RepairBusySet, sourceId: string, what: string): string {+ if (busy.unknown !== null) return `${what} was not repaired: ${busy.unknown}. The next run reads it again.`;+ return `A running sync of ${sourceId}, or a write still in flight, names ${what}; finish the sync (gbrain sync --source ${sourceId} --no-pull) and the next run repairs it.`;+}++/** The refusal a coordinated repair admission raises when its candidate became busy after the plan read it. */+export function repairBusyError(busy: RepairBusySet, sourceId: string, path: string): OperationError {+ return opError('sync_in_progress', `${path} is named by a sync or write of ${sourceId} that started after this repair was planned, so nothing was written.`,+ `${repairBusyMessage(busy, sourceId, path)} Check the source with the command in fix; the repair is read again on the next run.`,+ { reason: busy.unknown !== null ? 'busy_set_unreadable' : 'candidate_in_flight',+ fix: readFix('Shows the sync cursors and in-flight writes of the source, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 86d3376c09..1f40620f94 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -74,7 +74,9 @@ export interface RepairListing { item: string; class: string; detail?: string }* the run's paid-model allowance (it only lowers the kind's own cap). `deadline` (epoch ms) bounds a discovery scan.*/export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[];- noLlm?: boolean; maxLlmUsd?: number; deadline?: number }+ noLlm?: boolean; maxLlmUsd?: number; deadline?: number;+ /** `ctx.remote !== false` of the run: a remote caller's plan never names a local path (unset reads as remote). */+ remote?: boolean }export interface RepairHandler {kind: RepairKind;@@ -251,7 +253,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst now = opts.now ?? Date.now;const planOpts: RepairPlanOptions = { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous, only: opts.only, skip: opts.skip,...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),- ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}) };+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex bf4cfb362e..109af92834 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -26,8 +26,14 @@** Per-item outcomes: `repaired` (detail: tier, classes, mode, path or slug),* `held` (reason: a FenceReason; the hold records it for the surfaces), or- * `skipped` (owner_unavailable, sync_in_progress, changed_since_read,- * changed_since_preview, claimed_elsewhere, already_clean). When the daily+ * `skipped` (an owner reason: host_mismatch, transfer_in_progress,+ * clone_in_progress, incarnation_changed, local_path_missing,+ * coordination_path_missing, or owner_unavailable; sync_in_progress,+ * changed_since_read, changed_since_preview, claimed_elsewhere,+ * already_clean). A source whose sync is running is not skipped as a whole:+ * only the candidates a write in flight or the sync's frozen manifest still+ * names are `sync_in_progress`, and the busy set is read again at apply and+ * at the write's admission (#6278). When the daily* ledger refuses a call the run stops with `budget_exhausted` (D15). The* result adds `repaired`, `remaining` by reason, `scan` and `verification`;* a run whose every model proposal is rejected reports 0 repaired.@@ -52,6 +58,8 @@ import { fenceRepairLlmEnabled, readFenceRepairCaps } from '../fence-repair/confimport { FENCE_REASONS } from '../fence-repair/reasons.ts';import { FENCE_REPAIR_ACTOR } from '../fence-repair/receipt.ts';import { checkoutFileExists, loadFenceSource, pageSha, readFenceTarget, spliceFileSections, writeFenceRepair, type FenceRepairMode, type FenceSource, type FenceTarget } from '../fence-repair/repair-io.ts';+import type { OwnerRefusal } from '../persistence/owner-refusal.ts';+import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';import { analyzeFences, attemptCandidate, runTier3, tier3Estimate, tier3Memo, type FenceAnalysis } from '../fence-repair/repair-tiers.ts';import type { FenceFix, FenceIssue, FencePage, FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';import { lineDiff } from './frontmatter.ts';@@ -215,6 +223,11 @@ function item(entry: ApprovedFence, index: number, hash: string | null, last: bo...(entry.tier === 'llm' ? { llm_usd: entry.estimate_usd } : {}), entry, hash, last, scan_partial: partial };}+/** The hold reason of an owner refusal: the matrix reason where the fence reason table has it, else the generic `owner_unavailable`. */+function ownerReason(owner: OwnerRefusal): FenceReason {+ return owner.reason in FENCE_REASONS ? owner.reason as FenceReason : 'owner_unavailable';+}+/** The read-only fix that previews one candidate's repair again. */const previewFix = (sourceId: string, path: string | null, slug: string): Action => ({ argv: ['gbrain', 'repair', 'fences', '--source', sourceId, ...(path ? ['--only', path] : ['--slug', slug])],consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews this fence repair again from the bytes as they are now; nothing is written.' });@@ -236,7 +249,7 @@ export const fencesRepair: RepairHandler = {const now = Date.now();const runs = await runFenceCensus(engine, { sourceIds: scope.source_ids, deadline: Math.min(now + SCAN_MS(), opts?.deadline ?? Infinity) });const sources = new Map<string, FenceSource | null>();- for (const id of scope.source_ids) sources.set(id, await loadFenceSource(engine, id));+ for (const id of scope.source_ids) sources.set(id, await loadFenceSource(engine, id, { remote: opts?.remote !== false }));const found = await listFenceCandidates(engine, scope.source_ids);const { extra, unknown } = await extraCandidates(engine, scope, selection, found, sources);let candidates = [...found, ...extra].filter(cand => selected(cand, selection));@@ -261,9 +274,9 @@ export const fencesRepair: RepairHandler = {hold(cand, entry);if (opts?.apply) await recordHeld(engine, src, { path: cand.path, held: isHeld }, { reason: entry.reason, gate: entry.gate, rows: entry.rows, next });};- if (src.ownerElsewhere) { await keep({ item: name, reason: 'owner_unavailable', tier: 'manual', resolution: `Run gbrain repair fences --source ${src.id} on the owner host (gbrain sources writer status --source ${src.id} names it).` }); continue; }- if (src.syncUnfinished || (cand.path && src.busy.paths.has(cand.path)) || src.busy.slugs.has(cand.key)) {- await keep({ item: name, reason: 'sync_in_progress', tier: cand.tier, resolution: `A sync or write of ${src.id} still names this file; finish it (gbrain sync --source ${src.id} --no-pull) and the next run repairs it.` });+ if (src.owner) { await keep({ item: name, reason: ownerReason(src.owner), tier: 'manual', resolution: `${src.owner.message} ${src.owner.why}` }); continue; }+ if (repairBusy(src.busy, { path: cand.path, slug: cand.key })) {+ await keep({ item: name, reason: 'sync_in_progress', tier: cand.tier, resolution: repairBusyMessage(src.busy, src.id, cand.path ?? cand.key) });continue;}const read = await readFenceTarget(engine, src, { key: cand.key, path: cand.path });@@ -405,19 +418,22 @@ async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: Appconst where = { ...(entry.path ? { path: entry.path } : {}), slug: entry.slug, mode: entry.mode, tier: entry.tier };const moved = opts.expect ? 'changed_since_preview' : 'changed_since_read';const skipped = (reason: string, message: string): RepairItemOutcome => ({ applied: false, outcome: 'skipped', reason, detail: { ...where, message } });- const src = await loadFenceSource(engine, entry.source_id);+ const src = await loadFenceSource(engine, entry.source_id, { remote: ctx.remote !== false });if (!src) return skipped(moved, `Source ${entry.source_id} is gone or archived.`);const heldOutcome = async (reason: string, message: string, extra: { gate?: GateLetter; rows?: number[]; next?: string | null; tier?: FenceTier } = {}): Promise<RepairItemOutcome> => {await recordHeld(engine, src, entry, { reason, ...extra });return { applied: false, outcome: 'held', reason, detail: { ...where, tier: extra.tier ?? heldTier(reason), message, ...(extra.gate ? { gate: extra.gate } : {}), ...(extra.rows?.length ? { rows: extra.rows } : {}) } };};- if (src.ownerElsewhere) {- await recordHeld(engine, src, entry, { reason: 'owner_unavailable' });- return skipped('owner_unavailable', `This host is not the active owner of source ${src.id}; run gbrain repair fences there.`);+ if (src.owner) {+ const reason = ownerReason(src.owner);+ await recordHeld(engine, src, entry, { reason });+ const out = skipped(reason, src.owner.message);+ return { ...out, detail: { ...out.detail, why: src.owner.why, fix: src.owner.fix.argv, retryable: src.owner.retryable } };}- if (src.syncUnfinished || (entry.path && src.busy.paths.has(entry.path)) || src.busy.slugs.has(entry.slug)) {+ // Re-checked here and again at the write's admission (file-repair.ts): a sync may have frozen this candidate since the plan.+ if (repairBusy(src.busy, { path: entry.path, slug: entry.slug })) {await recordHeld(engine, src, entry, { reason: 'sync_in_progress' });- return skipped('sync_in_progress', `A sync or write of ${src.id} still names this candidate; the next run repairs it.`);+ return skipped('sync_in_progress', repairBusyMessage(src.busy, src.id, entry.path ?? entry.slug));}const read = await readFenceTarget(engine, src, { key: entry.key, path: entry.path });if (!read.ok) return skipped(moved, `The candidate is ${read.reason === 'gone' ? 'gone' : read.reason}.`);@@ -444,6 +460,10 @@ async function write(ctx: OperationContext, src: FenceSource, target: FenceTarge{ embed: opts.embed });if (!outcome.ok) {if (outcome.reason === 'changed_since_read') return { applied: false, outcome: 'skipped', reason: 'changed_since_read', detail: { path: target.path, slug: target.slug, mode: target.mode, message: outcome.message } };+ if (outcome.reason === 'sync_in_progress') {+ await recordHeld(ctx.engine, src, { path: target.path, held: target.hold !== null }, { reason: 'sync_in_progress' });+ return { applied: false, outcome: 'skipped', reason: 'sync_in_progress', detail: { path: target.path, slug: target.slug, mode: target.mode, message: outcome.message } };+ }return held(outcome.reason, outcome.message, { tier: 'manual' });}return { applied: true, outcome: 'repaired', detail: { tier: r.tier, classes: r.classes.join(', '), slug: target.slug, ...outcome.detail }, ...(r.cost ? { llm_usd: r.cost } : {}) };@@ -483,7 +503,7 @@ async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTargeopts, held);const store = attemptStore(engine);if (written.applied) await store.publish(result.claim);- else if (written.reason === 'changed_since_read') await store.transient(result.claim, 'changed_since_read');+ else if (written.reason === 'changed_since_read' || written.reason === 'sync_in_progress') await store.transient(result.claim, written.reason);else await store.reject(result.claim, { reason: written.reason ?? 'still_invalid' });return { ...written, ...(result.spentUsd ? { llm_usd: result.spentUsd } : {}) };}diff --git a/test/e2e/repair-fences-during-catchup-postgres.test.ts b/test/e2e/repair-fences-during-catchup-postgres.test.tsnew file mode 100644index 0000000000..7c7e288ab4--- /dev/null+++ b/test/e2e/repair-fences-during-catchup-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-fences-during-catchup.test.ts'));diff --git a/test/owner-refusal.test.ts b/test/owner-refusal.test.tsnew file mode 100644index 0000000000..8b10d21fb1--- /dev/null+++ b/test/owner-refusal.test.ts@@ -0,0 +1,195 @@+/**+ * #6278 R1: the `owner_unavailable` reasons matrix. One reason per owner+ * condition, in a fixed order; each with its message, `why`, actor, next+ * step and read-only verify; `host_mismatch` prints both host ids' first 8+ * characters and, for local callers only, the observed `host.json` path, and+ * is never retryable; the in-progress reasons render `next: wait`.+ * `maintenancePreflight` refuses every condition with its own reason and+ * never claims or transfers ownership to get past it; the HTTP envelope of+ * each refusal carries no local path.+ * Fails when: a condition loses its reason, falls back to the generic text,+ * leaks the identity path to a remote caller, or lets an agent retry a host+ * mismatch forever.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { cliRenderContext, deriveNext, toAgentError, type RenderContext } from '../src/core/agent-output.ts';+import { CODES } from '../src/core/error-registry.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { checkOwner, ownerRefusal, ownerUnavailableError, OWNER_UNAVAILABLE_REASONS, OWNER_WAIT_SECONDS, type OwnerUnavailableReason } from '../src/core/persistence/owner-refusal.ts';+import { claimWorktree, getWorktreeBinding, type WorktreeBinding } from '../src/core/persistence/ownership.ts';+import { localHostId, persistenceHome } from '../src/core/persistence/identity.ts';+import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { FENCE_REASONS } from '../src/core/fence-repair/reasons.ts';+import { fenceHoldStatus } from '../src/core/fence-repair/hold-fix.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const OWNER = 'aaaaaaaa-1111-4111-8111-111111111111', LOCAL = 'bbbbbbbb-2222-4222-8222-222222222222';+const INCARNATION = 'cccccccc-3333-4333-8333-333333333333';+const binding = (over: Partial<WorktreeBinding> = {}): WorktreeBinding => ({ worktree_id: randomUUID(), source_id: 'src', source_incarnation: INCARNATION, relative_path: '',+ topology_generation: 1, owner_host_id: LOCAL, owner_epoch: 1, state: 'active', local_path: '/srv/brain', coordination_path: '/srv/brain/.gbrain-coordination', ...over });+const http: RenderContext = { transport: 'http', surface: 'full', isCallable: () => false, preapproved: () => false, principal: 'client-example' };++describe('the matrix', () => {+ test('checks the conditions in one order and names the first that fails', () => {+ const at = (b: WorktreeBinding | null, incarnation = INCARNATION) => checkOwner(b, incarnation, LOCAL).reason;+ expect(at(null)).toBe('binding_missing');+ expect(at(binding({ owner_host_id: OWNER, state: 'draining' }), randomUUID())).toBe('incarnation_changed');+ expect(at(binding({ owner_host_id: OWNER, state: 'draining' }))).toBe('host_mismatch');+ expect(at(binding({ state: 'draining', local_path: null }))).toBe('transfer_in_progress');+ expect(at(binding({ state: 'recovering', local_path: null }))).toBe('clone_in_progress');+ expect(at(binding({ local_path: null, coordination_path: null }))).toBe('local_path_missing');+ expect(at(binding({ coordination_path: null }))).toBe('coordination_path_missing');+ const ok = checkOwner(binding(), INCARNATION, LOCAL);+ expect(ok.reason).toBeNull();+ if (ok.reason === null) expect(ok.binding.local_path).toBe('/srv/brain');+ });++ test('every reason is in the registry vocabulary, has a fence reason the hold routes as owner, and a read-only writer-status verify', () => {+ const registry = CODES.owner_unavailable.reasons!;+ for (const reason of OWNER_UNAVAILABLE_REASONS) {+ expect(registry).toContain(reason);+ const row = ownerRefusal({ sourceId: 'src', reason, binding: binding({ owner_host_id: OWNER }), incarnation: INCARNATION, hostId: LOCAL, remote: true, work: 'maintenance' });+ expect(row.fix.verify?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json']);+ expect(row.fix.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json']);+ expect(row.fix.consent).toEqual([]);+ expect(row.why).toContain('never claims or transfers ownership');+ if (reason !== 'binding_missing') {+ expect(FENCE_REASONS[reason].actor).toBe('host_admin');+ expect(fenceHoldStatus({ reason: 'invalid_fence', fence_repair: { reason, tier: null, at: '2026-10-08T00:00:00Z', next_attempt_after: null } } as never).state).toBe('owner');+ }+ }+ });++ test('in-progress work is a wait with its delay; the rest is a host administrator decision; host_mismatch is never retryable', () => {+ const cli = cliRenderContext();+ const next = (reason: OwnerUnavailableReason) => deriveNext(ownerRefusal({ sourceId: 'src', reason, binding: binding(), incarnation: INCARNATION, hostId: LOCAL, remote: false, work: 'maintenance' }).fix, cli);+ expect(next('transfer_in_progress')).toBe('wait');+ expect(next('clone_in_progress')).toBe('wait');+ expect(ownerRefusal({ sourceId: 'src', reason: 'clone_in_progress', binding: binding(), incarnation: INCARNATION, hostId: LOCAL, remote: false, work: 'maintenance' }).fix.why).toContain(`Wait ${OWNER_WAIT_SECONDS} seconds`);+ for (const reason of ['host_mismatch', 'binding_missing', 'incarnation_changed', 'local_path_missing', 'coordination_path_missing'] as const) expect(next(reason)).toBe('tell_user_to_run');+ const retryable = Object.fromEntries(OWNER_UNAVAILABLE_REASONS.map(reason => [reason,+ ownerRefusal({ sourceId: 'src', reason, binding: binding(), incarnation: INCARNATION, hostId: LOCAL, remote: false, work: 'maintenance' }).retryable]));+ expect(retryable).toEqual({ host_mismatch: false, transfer_in_progress: true, clone_in_progress: true, binding_missing: false, incarnation_changed: false, coordination_path_missing: false, local_path_missing: false });+ });++ test('host_mismatch prints both ids\' first 8 characters, and the observed host.json path to local callers only', async () => {+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbrain-owner-refusal-')) }, async () => {+ const path = join(persistenceHome(), 'host.json');+ const local = ownerUnavailableError({ sourceId: 'src', reason: 'host_mismatch', binding: binding({ owner_host_id: OWNER }), incarnation: INCARNATION, hostId: LOCAL, remote: false, work: 'fence repair' });+ expect(local.message).toContain('aaaaaaaa'); expect(local.message).toContain('bbbbbbbb');+ expect(local.message).not.toContain(OWNER); expect(local.message).not.toContain(LOCAL);+ expect(local.why).toContain(path);+ expect(local.reason).toBe('host_mismatch');+ expect(local.retryable).toBe(false);+ const envelope = toAgentError(local, { transport: 'cli', command: 'repair', render: cliRenderContext() });+ expect(envelope).toMatchObject({ code: 'owner_unavailable', reason: 'host_mismatch', class: 'retryable', retryable: false, fix: { next: 'tell_user_to_run', actor: 'host_admin' } });+ const remote = ownerUnavailableError({ sourceId: 'src', reason: 'host_mismatch', binding: binding({ owner_host_id: OWNER }), incarnation: INCARNATION, hostId: LOCAL, remote: true, work: 'fence repair' });+ const rendered = JSON.stringify(toAgentError(remote, { transport: 'http', op: 'chronicle_day', render: http }));+ expect(rendered).not.toContain(path); expect(rendered).not.toContain(persistenceHome()); expect(rendered).not.toContain('read its identity from');+ expect(rendered).toContain('aaaaaaaa'); expect(rendered).toContain('bbbbbbbb');+ expect(JSON.parse(rendered)).toMatchObject({ reason: 'host_mismatch', retryable: false });+ // The in-progress reasons keep the code's retryable class.+ const wait = toAgentError(ownerUnavailableError({ sourceId: 'src', reason: 'transfer_in_progress', binding: binding({ state: 'draining' }), incarnation: INCARNATION, hostId: LOCAL, remote: false, work: 'maintenance' }),+ { transport: 'cli', command: 'chronicle', render: cliRenderContext() });+ expect(wait).toMatchObject({ reason: 'transfer_in_progress', retryable: true, fix: { next: 'wait' } });+ });+ });+});++describe('maintenancePreflight', () => {+ const backends = testBackends();+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-owner-preflight-'));++ beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({ database_path: join(dataDir, 'pglite') }); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });+ });++ 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 fixture(run: (engine: BrainEngine, sourceId: string, root: string) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-owner-preflight-src-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `owner-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run(engine, sourceId, root);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+ }++ const refusal = async (engine: BrainEngine, sourceId: string): Promise<OperationError> => {+ try { await maintenancePreflight(engine, sourceId); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('preflight did not refuse');+ };++ test('each owner condition refuses owner_unavailable with its own reason, never claims ownership, and the remote envelope carries no local path', () => fixture(async (engine, sourceId) => {+ const before = (await getWorktreeBinding(engine, sourceId))!;+ const worktree = before.worktree_id;+ expect(await maintenancePreflight(engine, sourceId)).toMatchObject({ binding: { worktree_id: worktree } });+ const stranger = randomUUID();+ const seen: Record<string, OperationError> = {};+ await topology(engine, 'UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [worktree, stranger]);+ seen.host_mismatch = await refusal(engine, sourceId);+ await topology(engine, 'UPDATE persistence_worktrees SET owner_host_id=$2::uuid, state=$3 WHERE id=$1::uuid', [worktree, localHostId(), 'draining']);+ seen.transfer_in_progress = await refusal(engine, sourceId);+ await topology(engine, 'UPDATE persistence_worktrees SET state=$2 WHERE id=$1::uuid', [worktree, 'recovering']);+ seen.clone_in_progress = await refusal(engine, sourceId);+ await topology(engine, 'UPDATE persistence_worktrees SET state=$2 WHERE id=$1::uuid', [worktree, 'active']);+ await topology(engine, "UPDATE persistence_host_bindings SET coordination_path='' WHERE worktree_id=$1::uuid", [worktree]);+ seen.coordination_path_missing = await refusal(engine, sourceId);+ await topology(engine, 'DELETE FROM persistence_host_bindings WHERE worktree_id=$1::uuid', [worktree]);+ seen.local_path_missing = await refusal(engine, sourceId);+ await topology(engine, 'INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path) VALUES($1::uuid,$2::uuid,$3,$4)',+ [worktree, localHostId(), before.local_path, before.coordination_path]);+ await topology(engine, 'UPDATE persistence_source_bindings SET source_incarnation=$2::uuid WHERE source_id=$1', [sourceId, randomUUID()]);+ seen.incarnation_changed = await refusal(engine, sourceId);+ await topology(engine, 'DELETE FROM persistence_source_bindings WHERE source_id=$1', [sourceId]);+ seen.binding_missing = await refusal(engine, sourceId);+ for (const [reason, error] of Object.entries(seen)) {+ expect([reason, error.code, error.reason]).toEqual([reason, 'owner_unavailable', reason]);+ expect(error.fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json']);+ expect(error.why).toContain('never claims or transfers ownership');+ const remote = JSON.stringify(toAgentError(error, { transport: 'http', op: 'chronicle_day', render: http }));+ expect(remote).not.toContain(persistenceHome());+ }+ expect(seen.host_mismatch!.message).toContain(stranger.slice(0, 8));+ expect(seen.host_mismatch!.message).toContain(localHostId().slice(0, 8));+ expect(seen.host_mismatch!.why).toContain(join(persistenceHome(), 'host.json'));+ expect(seen.host_mismatch!.retryable).toBe(false);+ expect(seen.transfer_in_progress!.fix?.actor).toBe('provider');+ expect(seen.clone_in_progress!.fix?.actor).toBe('provider');+ // Nothing above claimed or transferred: the worktree still has no source binding and the stranger's host id never became this host's.+ expect(await getWorktreeBinding(engine, sourceId)).toBeNull();+ const [row] = await engine.executeRaw<{ owner_host_id: string; state: string }>('SELECT owner_host_id,state FROM persistence_worktrees WHERE id=$1::uuid', [worktree]);+ expect(row).toMatchObject({ owner_host_id: localHostId(), state: 'active' });+ }), 60_000);+});diff --git a/test/repair-busy.test.ts b/test/repair-busy.test.tsnew file mode 100644index 0000000000..a0f51eceb8--- /dev/null+++ b/test/repair-busy.test.ts@@ -0,0 +1,82 @@+/**+ * #6278 R2: the repair busy set. Busy: queued, running and recovering+ * requests, terminal rows with an open recovery, both endpoints of a rename,+ * and the not-yet-admitted entries of every unfinished managed sync cursor+ * of the current incarnation (read from the frozen manifest, from the+ * cursor's index on); a held path in the manifest is not busy. The read+ * fails closed: a thrown query or a cursor whose manifest is missing makes+ * every candidate busy, never an empty set.+ * Fails when: a rename endpoint, a recovery row or a manifest-ahead path+ * stops counting, a held path starts counting, or a failed read comes back+ * as "nothing busy".+ */+import { describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { loadRepairBusySet, repairBusy, repairBusyError, repairBusyMessage } from '../src/core/persistence/repair-busy.ts';++type Rows = Record<string, unknown>[];+/** An engine whose executeRaw answers by the table the SQL names; `fail` throws for SQL containing it. */+function stub(answers: { pending?: Rows; cursors?: Rows; holds?: Rows; manifests?: Record<string, unknown> }, fail?: string): BrainEngine {+ return { async executeRaw(sql: string, params: unknown[] = []) {+ if (fail && sql.includes(fail)) throw new Error(`boom: ${fail}`);+ if (sql.includes('FROM persistence_requests')) return answers.pending ?? [];+ if (sql.includes("op='managed-sync' ")) return params[1] === INC ? answers.cursors ?? [] : [];+ if (sql.includes("op='managed-sync-manifest'")) { const entries = answers.manifests?.[String(params[0])]; return entries === undefined ? [] : [{ entries }]; }+ if (sql.includes('FROM op_checkpoints') && params[0] === 'sync-hold') return answers.holds ?? [];+ throw new Error(`unexpected SQL: ${sql}`);+ } } as unknown as BrainEngine;+}+const INC = 'inc-1';++describe('loadRepairBusySet', () => {+ test('in-flight requests: slug, path, origin and both rename endpoints; terminal rows with an open recovery count', async () => {+ const busy = await loadRepairBusySet(stub({ pending: [+ { slug: 'people/a', path: 'people/a.md', source_path: 'people/a.md', rename_slug: 'people/old-a', rename_source_path: 'people/old-a.md' },+ { slug: 'people/b', path: null, source_path: null, rename_slug: null, rename_source_path: null }] }), 'src', INC);+ expect(busy.unknown).toBeNull();+ expect([...busy.paths].sort()).toEqual(['people/a.md', 'people/old-a.md']);+ expect([...busy.slugs].sort()).toEqual(['people/a', 'people/b', 'people/old-a']);+ expect(repairBusy(busy, { path: 'people/old-a.md' })).toBe(true);+ expect(repairBusy(busy, { slug: 'people/b' })).toBe(true);+ expect(repairBusy(busy, { path: 'people/c.md', slug: 'people/c' })).toBe(false);+ });++ test('an unfinished cursor adds the manifest entries from its index on, held paths excluded; a finished or other-incarnation cursor adds nothing', async () => {+ const manifest = [+ { path: 'people/done.md', sourcePath: 'people/done.md', action: 'import', slug: 'people/done' },+ { path: 'people/next.md', sourcePath: 'people/next.md', action: 'import', slug: 'people/next' },+ { path: 'people/held.md', sourcePath: 'people/held.md', action: 'import', slug: 'people/held' },+ { path: 'people/moved.md', sourcePath: 'people/moved.md', action: 'import', slug: 'people/moved', renameFrom: { sourcePath: 'people/was.md', slug: 'people/was' } },+ ];+ const busy = await loadRepairBusySet(stub({ cursors: [{ run_id: 'run-1', index: '1' }], manifests: { 'run-1': manifest }, holds: [{ path: 'people/held.md' }] }), 'src', INC);+ expect(busy.unknown).toBeNull();+ expect([...busy.paths].sort()).toEqual(['people/moved.md', 'people/next.md', 'people/was.md']);+ expect([...busy.slugs].sort()).toEqual(['people/moved', 'people/next', 'people/was']);+ expect(repairBusy(busy, { path: 'people/done.md', slug: 'people/done' })).toBe(false);+ expect(repairBusy(busy, { path: 'people/held.md', slug: 'people/held' })).toBe(false);+ expect(repairBusy(busy, { sourcePath: 'people/was.md' })).toBe(true);+ const none = await loadRepairBusySet(stub({ cursors: [], manifests: { 'run-1': manifest } }), 'src', INC);+ expect([none.unknown, none.paths.size, none.slugs.size]).toEqual([null, 0, 0]);+ const other = await loadRepairBusySet(stub({ cursors: [{ run_id: 'run-1', index: '1' }], manifests: { 'run-1': manifest } }), 'src', 'inc-2');+ expect([other.unknown, other.paths.size, other.slugs.size]).toEqual([null, 0, 0]);+ });++ test('fails closed: a thrown query or an unfinished cursor without a readable manifest makes every candidate busy', async () => {+ for (const fail of ['FROM persistence_requests', "op='managed-sync' ", 'sync-hold']) {+ const engine = stub({ cursors: [{ run_id: 'run-1', index: 0 }], manifests: { 'run-1': [] } }, fail === 'sync-hold' ? 'FROM op_checkpoints\n WHERE op=$1' : fail);+ const busy = await loadRepairBusySet(engine, 'src', INC);+ expect(busy.unknown).toContain('could not be read');+ expect(repairBusy(busy, { path: 'anything.md' })).toBe(true);+ expect(repairBusy(busy, {})).toBe(true);+ }+ const missing = await loadRepairBusySet(stub({ cursors: [{ run_id: 'run-gone', index: 0 }], manifests: {} }), 'src', INC);+ expect(missing.unknown).toContain('run-gone');+ expect(repairBusy(missing, { path: 'anything.md' })).toBe(true);+ const malformed = await loadRepairBusySet(stub({ cursors: [{ run_id: 'run-odd', index: 0 }], manifests: { 'run-odd': { not: 'an array' } } }), 'src', INC);+ expect(repairBusy(malformed, { path: 'anything.md' })).toBe(true);+ expect(repairBusyMessage(missing, 'src', 'people/x.md')).toContain('every candidate of the source is treated as in flight');+ expect(repairBusyError(missing, 'src', 'people/x.md')).toMatchObject({ code: 'sync_in_progress', reason: 'busy_set_unreadable' });+ const named = await loadRepairBusySet(stub({ pending: [{ slug: 'people/x', path: 'people/x.md', source_path: null, rename_slug: null, rename_source_path: null }] }), 'src', INC);+ expect(repairBusyError(named, 'src', 'people/x.md')).toMatchObject({ code: 'sync_in_progress', reason: 'candidate_in_flight', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'src', '--json'] } });+ });+});diff --git a/test/repair-fences-during-catchup.test.ts b/test/repair-fences-during-catchup.test.tsnew file mode 100644index 0000000000..ff2a71481a--- /dev/null+++ b/test/repair-fences-during-catchup.test.ts@@ -0,0 +1,209 @@+/**+ * #6278 R2: `gbrain repair fences --apply` during a live managed catch-up.+ *+ * Protects: a source whose sync is running is no longer skipped as a whole.+ * While a sync member is being prepared, the candidate it names and a+ * candidate still ahead in the run's frozen manifest are `sync_in_progress`+ * and nothing is written to them; between two entries of the same run a held+ * candidate (the hold's bytes unchanged, so not in the manifest) and an+ * unsynced working-tree candidate are repaired, while the far-ahead one still+ * waits; the sync then finishes with no `source_changed` refusal and imports+ * the entry it had ahead. A plan approved before a sync started is not+ * applied to a candidate that sync froze in between (`sync_in_progress` at+ * apply), and the entry imports once the sync reaches it.+ * Fails when: the blanket skip comes back (nothing repaired during a sync),+ * a manifest-ahead or in-flight candidate is written (the sync would refuse+ * it on its raw hash), or a held path counts as busy.+ * Seams: installFaultHook (`consumer:preparing`, `sync:mid_checkpoint`) pauses+ * the real sync; __setChatTransportForTests answers the model tier.+ * Postgres arm: test/e2e/repair-fences-during-catchup-postgres.test.ts.+ */+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { installFaultHook, type FaultDetail, type FaultPoint } from '../src/core/persistence/fault-points.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-catchup-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: 'sk-test-not-used',+ GBRAIN_FENCE_REPAIR_SCAN_MS: '60000', GBRAIN_SYNC_BULK: '0' };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const quiet = { info() {}, warn() {}, error() {} };++const CLAIM = 'Sentinelcatchup ships quarterly';+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const NARROW = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';+const SEP = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';+const row = (claim: string) => `| 1 | ${claim} | fact | 0.9 | private | high | 2026-01-01 | | chat | ctx |`;+const md = (title: string, body: string) => `---\ntitle: ${title}\n---\nA synthetic page.\n\n${body}`;+/** Tier 3: rows but no header (held by the sync). */+const noHeader = (claim = CLAIM) => `${FB}\n${row(claim)}\n${FBE}\n`;+/** Tier 1: a missing end marker and an invented kind (admitted by the sync, normalized on import). */+const fixable = (claim: string) => `${FB}\n${FH}\n| 1 | ${claim} | partnership | 0.9 | private | high | 2026-01-01 | | chat | |\n`;+const answer = (claim: string): ChatResult => ({ text: `${NARROW}\n${SEP}\n${row(claim)}`, blocks: [], stopReason: 'end',+ usage: { input_tokens: 500, output_tokens: 120, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-4-7', providerId: 'anthropic' });++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterEach(() => { installFaultHook(undefined); __setChatTransportForTests(null); });+afterAll(async () => {+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); resetGateway(); rmSync(home, { recursive: true, force: true });+});++async function managed(engine: BrainEngine, files: Record<string, string>) {+ const id = `catchup-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };+ for (const [path, content] of Object.entries(files)) write(path, content);+ commit(root, 'fixture');+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, '{}']);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];+ const run = async (opts: { apply?: boolean; expect?: string; only?: string[] } = {}) => {+ const runner = await repairRunner(engine, { apply: opts.apply === true, noEmbed: true, logger: quiet });+ return runner.run('fences', await resolveRepairScope(engine, id), { explicit: true, sourceFlag: id, expect: opts.expect, only: opts.only });+ };+ const failed = async () => engine.executeRaw<{ request_id: string; error_code: string | null; slug: string }>(+ "SELECT request_id::text AS request_id, error_code, slug FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict')", [id]);+ const cursor = async () => (await engine.executeRaw<{ index: string | null; run_id: string | null }>(`SELECT completed_keys->0->>'index' AS index, completed_keys->0->>'runId' AS run_id+ FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [id]))[0] ?? null;+ return { id, root, write, read: (path: string) => readFileSync(join(root, path), 'utf8'), sync, holds, run, failed, cursor };+}++/** A gate the fault hook parks the sync at: `reached` resolves when it is hit, `release()` lets the sync go on. */+function gate() {+ let release!: () => void, reached!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ const hit = new Promise<void>(resolve => { reached = resolve; });+ return { release, reached, hit, released };+}+const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;+const classes = (result: RepairResult, prefix: string) => Object.fromEntries((result.listing ?? []).map(entry => [entry.item.slice(prefix.length + 1), entry.class]));++async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6' } as never);+ for (const engine of engines) {+ try { await run(engine); } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }+ }+ });+}++test('during a live catch-up: the admitted and the far-ahead candidates wait, the held and the working-tree candidates repair, and the sync finishes clean', () => each(async engine => {+ const s = await managed(engine, { 'people/held.md': md('Held', noHeader()), 'notes/plain.md': md('Plain', 'Nothing here.\n') });+ expect((await s.sync()).held_count).toBe(1);+ // Commit 2: the entry the sync admits first (a Tier 1 defect, so it is a census file candidate until it imports) and one far behind it.+ s.write('people/aa-admitted.md', md('Admitted', fixable('Synthetic admitted partnership')));+ s.write('people/zz-ahead.md', md('Ahead', fixable('Synthetic ahead partnership')));+ commit(s.root, 'two fences');+ // Never synced, never committed: a working-tree candidate outside the manifest.+ s.write('people/later.md', md('Later', fixable('Synthetic later partnership')));+ let calls = 0;+ __setChatTransportForTests(async () => { calls++; return answer(CLAIM); });+ const preparing = gate(), between = gate();+ let pausedPreparing = false, pausedBetween = false;+ installFaultHook(async (point: FaultPoint, detail: FaultDetail) => {+ if (detail.sourceId !== s.id) return;+ if (point === 'consumer:preparing' && !pausedPreparing) {+ const [req] = await engine.executeRaw<{ path: string | null }>("SELECT intent->>'path' AS path FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);+ if (req?.path !== 'people/aa-admitted.md') return;+ pausedPreparing = true; preparing.reached(); await preparing.released;+ }+ if (point === 'sync:mid_checkpoint' && pausedPreparing && !pausedBetween && (await s.cursor())?.index === '1') {+ pausedBetween = true; between.reached(); await between.released;+ }+ });+ const sync = s.sync();+ await preparing.hit;+ // Entry 0 is admitted and preparing; entry 1 is frozen in the manifest and not admitted.+ const [running] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state='running'", [s.id]);+ expect(running!.n).toBe(1);+ const busyPreview = await s.run({ only: ['people/aa-admitted.md', 'people/zz-ahead.md'] });+ expect(classes(busyPreview, s.id)).toEqual({ 'people/aa-admitted.md': 'sync_in_progress', 'people/zz-ahead.md': 'sync_in_progress' });+ expect(busyPreview.affected).toBe(0);+ const busyApply = await s.run({ apply: true, only: ['people/aa-admitted.md', 'people/zz-ahead.md'] });+ expect(busyApply).toMatchObject({ applied: 0, remaining: { sync_in_progress: 2 } });+ expect(s.read('people/aa-admitted.md')).toBe(md('Admitted', fixable('Synthetic admitted partnership')));+ expect(s.read('people/zz-ahead.md')).toBe(md('Ahead', fixable('Synthetic ahead partnership')));+ preparing.release();+ await between.hit;+ // Entry 0 committed, entry 1 still ahead: the held and the working-tree candidates repair now; the far-ahead one waits.+ expect(await s.failed()).toEqual([]);+ const preview = await s.run();+ expect(classes(preview, s.id)).toEqual({ 'people/held.md': 'llm', 'people/later.md': 'deterministic', 'people/zz-ahead.md': 'sync_in_progress' });+ const applied = await s.run({ apply: true });+ expect(applied).toMatchObject({ repaired: 2, remaining: { sync_in_progress: 1 } });+ expect(calls).toBe(1);+ expect(s.read('people/held.md')).toContain(FH.split('\n')[0]!);+ expect(s.read('people/later.md')).toContain(FBE);+ expect(s.read('people/zz-ahead.md')).toBe(md('Ahead', fixable('Synthetic ahead partnership')));+ expect(await s.holds()).toEqual([]);+ between.release();+ const result = await sync;+ expect(result.status).not.toBe('error');+ expect(await s.failed()).toEqual([]);+ expect(await s.cursor()).toBeNull();+ // The far-ahead entry imported on the bytes the sync froze, and the import normalized its fence.+ expect(await engine.readPageSnapshot('people/zz-ahead', { sourceId: s.id })).not.toBeNull();+ expect(s.read('people/zz-ahead.md')).toContain(FBE);+ expect((await s.run()).affected).toBe(0);+}), 240_000);++test('a plan approved before a sync started is not applied to a candidate that sync froze; the entry imports once the sync reaches it', () => each(async engine => {+ const s = await managed(engine, { 'notes/plain.md': md('Plain', 'Nothing here.\n') });+ expect((await s.sync()).held_count ?? 0).toBe(0);+ s.write('people/race.md', md('Race', fixable('Synthetic race partnership')));+ commit(s.root, 'a fence');+ // Approved in the same plan, never committed: outside the manifest the sync is about to freeze.+ s.write('people/other.md', md('Other', fixable('Synthetic other partnership')));+ const approved = await s.run();+ expect(classes(approved, s.id)).toEqual({ 'people/race.md': 'deterministic', 'people/other.md': 'deterministic' });+ const frozen = gate();+ let paused = false;+ installFaultHook(async (point: FaultPoint, detail: FaultDetail) => {+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== s.id || paused) return;+ paused = true; frozen.reached(); await frozen.released;+ });+ const sync = s.sync();+ await frozen.hit;+ expect(await s.cursor()).toMatchObject({ index: '0' });+ const raced = await s.run({ apply: true, expect: hashOf(approved) });+ expect(raced).toMatchObject({ applied: 1, outcomes: { skipped: 1, repaired: 1 } });+ expect(raced.outcome_items!.find(item => item.item.endsWith('people/race'))).toMatchObject({ outcome: 'skipped', reason: 'sync_in_progress' });+ expect(raced.outcome_items!.find(item => item.item.endsWith('people/other'))).toMatchObject({ outcome: 'repaired' });+ expect(s.read('people/race.md')).toBe(md('Race', fixable('Synthetic race partnership')));+ expect(s.read('people/other.md')).toContain(FBE);+ frozen.release();+ const result = await sync;+ expect(result.status).not.toBe('error');+ expect(await s.failed()).toEqual([]);+ expect(await engine.readPageSnapshot('people/race', { sourceId: s.id })).not.toBeNull();+ expect(s.read('people/race.md')).toContain(FBE);+}), 240_000);diff --git a/test/repair-fences.test.ts b/test/repair-fences.test.tsindex edd4f6e388..e730feb369 100644--- a/test/repair-fences.test.ts+++ b/test/repair-fences.test.ts@@ -52,6 +52,7 @@ import { runFenceRepairPhase } from '../src/core/cycle/fence-repair.ts';import { fenceIntegrityResult } from '../src/commands/doctor/checks/fence-integrity.ts';import { fencesRepair, type FencesPreviewDetails } from '../src/core/repair/fences.ts';import { readUncommittedFenceRepairs } from '../src/core/fence-repair/uncommitted.ts';+import { fenceHoldStatus } from '../src/core/fence-repair/hold-fix.ts';import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';import { runModels } from '../src/commands/models.ts';import { resolveFenceRepairModel } from '../src/core/fence-repair/model.ts';@@ -163,6 +164,7 @@ async function gitEffectsSettled(engine: BrainEngine, sourceId: string) {throw new Error('git effects did not settle');}+const incarnationOf = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]))[0]!.incarnation;const details = (result: RepairResult) => result.details as unknown as FencesPreviewDetails;const hashOf = (result: RepairResult) => result.apply_command.split('--expect ')[1]!.split(' ')[0]!;const expectNoSecrets = (value: unknown) => { const text = typeof value === 'string' ? value : JSON.stringify(value); for (const secret of [CLAIM, MCLAIM, 'Sentinelclaimzr4', 'Sentinelmanualzr4']) expect(text).not.toContain(secret); };@@ -308,7 +310,7 @@ test('the daily ledger refusing the next call stops the run with the reset time,await engine.executeRaw("DELETE FROM config WHERE key='fences.repair.max_usd_per_day'");}), 240_000);-test('a file changed since the preview, an unfinished sync and a non-owner host write nothing', () => each(async engine => {+test('a file changed since the preview, an unfinished sync whose manifest cannot be read, and a non-owner host write nothing', () => each(async engine => {const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) });await s.sync();transport(() => answer(CLAIM));@@ -319,22 +321,110 @@ test('a file changed since the preview, an unfinished sync and a non-owner hostexpect(s.read('people/model.md')).toBe(edited);expect(calls).toHaveLength(0);s.write('people/model.md', md('Model', noHeader()));+ // An unfinished cursor of this incarnation whose manifest is missing: the busy set fails closed, so every candidate waits.await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,- [`probe-${s.id}`, JSON.stringify([{ sourceId: s.id, runId: 'probe', index: 0, done: false }])]);+ [`probe-${s.id}`, JSON.stringify([{ sourceId: s.id, incarnation: await incarnationOf(engine, s.id), runId: 'probe', index: 0, done: false }])]);+ expect((await s.run()).listing!.find(entry => entry.class === 'sync_in_progress')!.detail).toContain('the manifest of sync run probe is missing');const busy = await s.run({ apply: true });expect(busy).toMatchObject({ applied: 0, remaining: { sync_in_progress: 1 } });expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'sync_in_progress' });await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [`probe-${s.id}`]);- await engine.transaction(async tx => {+ const approved = await s.run();+ expect(approved.affected).toBe(1);+ const stranger = randomUUID();+ const worktree = async (sql: string, params: unknown[]) => engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");- await tx.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$2 LIMIT 1)', [randomUUID(), s.id]);+ await tx.executeRaw(sql, [...params, s.id]);});+ await worktree('UPDATE persistence_worktrees SET owner_host_id=$1::uuid WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$2 LIMIT 1)', [stranger]);+ // An approved set applied after the owner changed: the item is skipped with the reason, the read-only fix and retryable false.+ const skip = (await s.run({ apply: true, expect: hashOf(approved) })).outcome_items![0]!;+ expect(skip).toMatchObject({ outcome: 'skipped', reason: 'host_mismatch', detail: { retryable: false, fix: ['gbrain', 'sources', 'writer', 'status', '--source', s.id, '--json'] } });+ expect(skip.detail!.message).toContain(stranger.slice(0, 8));+ expect(skip.detail!.message).toContain(localHostId().slice(0, 8));+ expect(skip.detail!.why).toContain(join(home, '.gbrain', 'persistence', 'host.json'));const elsewhere = await s.run({ apply: true });- expect(elsewhere).toMatchObject({ applied: 0, remaining: { owner_unavailable: 1 } });+ expect(elsewhere).toMatchObject({ applied: 0, remaining: { host_mismatch: 1 } });+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'host_mismatch' });+ expect(fenceHoldStatus((await s.holds())[0]!.meta).state).toBe('owner');+ const local = (await s.run()).listing!.find(entry => entry.class === 'host_mismatch')!;+ expect(local.detail).toContain(stranger.slice(0, 8));+ expect(local.detail).toContain(join(home, '.gbrain', 'persistence', 'host.json'));+ // A plan for a remote caller gets both ids but never the identity path.+ const remote = (await fencesRepair.plan(engine, await resolveRepairScope(engine, s.id), null, { apply: false, remote: true })).listing!.find(entry => entry.class === 'host_mismatch')!;+ expect(remote.detail).toContain(stranger.slice(0, 8));+ expect(remote.detail).toContain(localHostId().slice(0, 8));+ expect(remote.detail).not.toContain('host.json');+ await worktree('UPDATE persistence_worktrees SET owner_host_id=$1::uuid, state=$2 WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$3 LIMIT 1)', [localHostId(), 'draining']);+ expect(await s.run({ apply: true })).toMatchObject({ applied: 0, remaining: { transfer_in_progress: 1 } });+ await worktree('UPDATE persistence_worktrees SET state=$1 WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$2 LIMIT 1)', ['recovering']);+ expect(await s.run({ apply: true })).toMatchObject({ applied: 0, remaining: { clone_in_progress: 1 } });+ expect((await s.holds())[0]!.meta.fence_repair).toMatchObject({ reason: 'clone_in_progress' });+ await worktree('UPDATE persistence_worktrees SET state=$1 WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$2 LIMIT 1)', ['active']);expect(calls).toHaveLength(0);expect(s.read('people/model.md')).toBe(md('Model', noHeader()));}), 240_000);+test('a running sync no longer skips the source: only candidates in flight or ahead in its frozen manifest wait, and a held path is not busy', () => each(async engine => {+ const s = await managed(engine, { 'people/held.md': md('Held', noHeader()), 'notes/plain.md': md('Plain', 'Nothing here.\n') });+ expect((await s.sync()).held_count).toBe(1);+ s.write('people/ahead.md', md('Ahead', fixable('Synthetic ahead partnership')));+ s.write('people/later.md', md('Later', fixable('Synthetic later partnership')));+ s.write('people/moved.md', md('Moved', fixable('Synthetic moved partnership')));+ commit(s.root, 'more fences');+ const incarnation = await incarnationOf(engine, s.id);+ const entry = (path: string, extra: Record<string, unknown> = {}) => ({ path, sourcePath: path, action: 'import', working: false, slug: path.replace(/\.md$/, ''), ...extra });+ // A frozen catch-up that has passed entry 0 and still has three entries ahead, one of them the held path (its bytes changed since the hold).+ const manifest = [entry('notes/plain.md'), entry('people/ahead.md'), entry('people/held.md'), entry('people/moved.md', { renameFrom: { sourcePath: 'people/later.md', slug: 'people/later', pageId: 1, revision: 'r' } })];+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest','run-ahead',$1::text::jsonb)`, [JSON.stringify(manifest)]);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,+ [`ahead-${s.id}`, JSON.stringify([{ sourceId: s.id, incarnation, runId: 'run-ahead', index: 1, done: false }])]);+ transport(() => answer(CLAIM));+ const preview = await s.run();+ const byItem = Object.fromEntries(preview.listing!.map(entry => [entry.item.slice(s.id.length + 1), entry.class]));+ expect(byItem).toEqual({ 'people/held.md': 'llm', 'people/ahead.md': 'sync_in_progress', 'people/later.md': 'sync_in_progress', 'people/moved.md': 'sync_in_progress' });+ expect(preview.listing!.find(entry => entry.class === 'sync_in_progress')!.detail).toContain('A running sync of');+ const applied = await s.run({ apply: true });+ expect(applied).toMatchObject({ repaired: 1, remaining: { sync_in_progress: 3 } });+ expect(calls).toHaveLength(1);+ expect((await s.holds()).map(h => h.path)).toEqual([]);+ expect(s.read('people/held.md')).toContain(FBE);+ expect(s.read('people/ahead.md')).toBe(md('Ahead', fixable('Synthetic ahead partnership')));+ // The cursor passes the three entries: the next run repairs them with no model call (Tier 1).+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1`,+ [`ahead-${s.id}`, JSON.stringify([{ sourceId: s.id, incarnation, runId: 'run-ahead', index: 4, done: false }])]);+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 3 });+ expect(calls).toHaveLength(1);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE (op='managed-sync' AND fingerprint=$1) OR (op='managed-sync-manifest' AND fingerprint='run-ahead')", [`ahead-${s.id}`]);+}), 240_000);++test('a sync that freezes the candidate while the model answers is caught at the write\'s admission: nothing is written, and the attempt is not spent', () => each(async engine => {+ const s = await managed(engine, { 'notes/plain.md': md('Plain', 'Nothing here.\n') });+ await s.sync();+ s.write('people/model.md', md('Model', noHeader()));+ commit(s.root, 'a model fence');+ const incarnation = await incarnationOf(engine, s.id);+ const freeze = async () => {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest','run-wait',$1::text::jsonb)`,+ [JSON.stringify([{ path: 'people/model.md', sourcePath: 'people/model.md', action: 'import', working: false, slug: 'people/model' }])]);+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,+ [`wait-${s.id}`, JSON.stringify([{ sourceId: s.id, incarnation, runId: 'run-wait', index: 0, done: false }])]);+ };+ let n = 0;+ __setChatTransportForTests(async () => { n++; if (n === 1) await freeze(); return answer(CLAIM); });+ const raced = await s.run({ apply: true });+ expect(raced).toMatchObject({ applied: 0, remaining: { sync_in_progress: 1 } });+ expect(raced.outcome_items![0]).toMatchObject({ outcome: 'skipped', reason: 'sync_in_progress' });+ expect(raced.outcome_items![0]!.detail!.message).toContain('started after this repair was planned');+ expect(n).toBe(1);+ expect(s.read('people/model.md')).toBe(md('Model', noHeader()));+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE (op='managed-sync' AND fingerprint=$1) OR (op='managed-sync-manifest' AND fingerprint='run-wait')", [`wait-${s.id}`]);+ // The attempt memo recorded a transient outcome, so the same bytes are sent again once the sync is gone.+ expect(await s.run({ apply: true })).toMatchObject({ repaired: 1 });+ expect(n).toBe(2);+ expect(s.read('people/model.md')).toContain(NARROW);+}), 240_000);+test('a read-only mirror is repaired in the database only and its hold cleared; the file is never written', () => each(async engine => {const s = await managed(engine, { 'people/model.md': md('Model', noHeader()) }, { mirror: true });await s.sync();