Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane B): remote reconcile_host_required, live convergence status and pass reasons
garrytan29a806a6d602
diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 78686a759a..b05ca55c59 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -113,6 +113,8 @@ export interface SyncResult {reason?: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable' | 'writer_pending' | 'writer_yield' | 'connector_item_failures' | 'connector_partial' | 'drain_lease_held'/** #6712 PR 4b (design v3.2 §9): a live pass's endings. `selection_scoped` rides a converged scoped pass (`synced`). */| 'not_converged' | 'admission_paused' | 'reconcile_host_required' | 'grant_scope' | 'reconcile_read_incomplete' | 'selection_scoped';+ /** #6712 PR 4b (design §5): a remote caller's `reconcile_host_required` ending: what it committed, what it left by reason, and the owner-host fix. */+ reconcile?: import('../core/persistence/sync-pass-apply.ts').RemoteReconcile;/** #6712 PR 4b: the live pass that produced this result (non-company managed sources; sync-pass-run.ts). */pass?: { pass_id: string; kind: 'idle' | 'hold_only' | 'full'; round: number; outcome: string; stop_reason: string | null; candidates: number; settled: number;remaining: number; not_converged_streak: number };diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex c12ac5e28a..df768bc565 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -150,6 +150,12 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'statecase 'needs_human': return `Source ${status.source_id} is blocked: a person has to decide (see NEEDS HUMAN below).`;case 'head_blocked': return `Source ${status.source_id} is blocked: its oldest write waits on something only an operator clears.`;case 'recovery_blocked': return `Source ${status.source_id} is blocked: a write's recovery record found changed bytes on disk.`;+ case 'pass_unfinished': return `Source ${status.source_id} is resumable: the newest sync pass did not finish; the next sync continues it.`;+ case 'not_converged': return `Source ${status.source_id} is resumable: the newest sync pass ran out of rounds before every path settled.`;+ case 'settle_mismatch': return `Source ${status.source_id} is resumable: a path keeps settling without reading settled; three passes in a row hold it.`;+ case 'deletes_withheld': return `Source ${status.source_id} is blocked: sync withheld a mass delete; the rest of the source is synced.`;+ case 'selection_scoped': return `Source ${status.source_id} is synced at a narrower selection; the plain sync runs the configured one.`;+ case 'admission_paused': return `Source ${status.source_id} is resumable: sync.admission pauses what sync admits.`;}}diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex 348038d857..7d4e238a4f 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -48,6 +48,8 @@ import type { ShadowLevel, ShadowPath } from './sync-pass.ts';import { SETTLE_MISMATCH_STREAK, type ManagedSyncPassValue, type PassRoundSummary } from './sync-pass-row.ts';import { syncClassAction, type SyncClassAction } from './sync-classify.ts';import type { SyncAdmission } from './sync-admission.ts';+import type { Action } from '../agent-output.ts';+import { slugUnderBoundPrefixes } from '../ops/context.ts';/** Legacy pages the sweep screens per pass after the incarnation's first full round (design §2.7, [estimated]). */export const PASS_LEGACY_SWEEP_MAX = 500;@@ -94,6 +96,8 @@ export interface PassApplyInput {obligations: ManagedSyncPassValue['obligations'];context: ManagedSyncContext;processingOptions: SyncProcessingOptions;+ /** A remote caller's slug-prefix grant (null: source-wide): paths outside it are left unsettled and never counted (design §5). */+ grantPrefixes?: readonly string[] | null;/** Test seam: the read-only same-content screen (default `readOnlySameContentScreen`). */screen?: (level: ShadowLevel, paths: ShadowPath[]) => Promise<Map<string, 'same' | 'differs' | 'unknown'>>;}@@ -116,8 +120,11 @@ function levelMeta(level: ShadowLevel, entry: ShadowPath): Partial<GitHoldMeta>/** Runs the round's settle-side work (module header) and settles the paths it finished in `level.paths`. */export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {if (input.fullRound && !input.remote) await retireMarkers(engine, level, state);+ if (input.remote && input.grantPrefixes) {+ for (const entry of level.paths) if (!grantSees(level, entry, input.grantPrefixes) && !entry.result.settled) settleAs(entry, { settled: true, action: 'none', classAction: 'none' });+ }await applyDeleteValve(engine, level, input, state);- if (input.remote) return;+ if (input.remote) { summarizeRound(level, state); return; }await writePassHolds(engine, level, input, state);await adoptRecords(engine, level, state);await sweepLegacy(engine, level, input, state);@@ -336,6 +343,40 @@ async function admitKeepDb(engine: BrainEngine, level: ShadowLevel, input: PassA}}+/** Whether a slug-prefix grant sees the path's page (its live slug, else the slug its origin imports to). */+function grantSees(level: ShadowLevel, entry: ShadowPath, prefixes: readonly string[]): boolean {+ const slug = entry.slug ?? resolveSlugForPath(passEntryPaths(level, entry.path).sourcePath);+ return !!slug && slugUnderBoundPrefixes(prefixes, slug);+}++/** Why a remote caller left a visible path unsettled (design §5). */+export type RemoteUnsettledReason = 'drift' | 'bootstrap' | 'unproven_delete' | 'grant_scope';+export interface RemoteReconcile { committed: number; unsettled: Partial<Record<RemoteUnsettledReason, number>>; fix: Action }++/**+ * Design §5: a remote caller's ending. It admitted the one-sided work it could (`committed`), and leaves to the owner host+ * what only the host settles: two-sided paths (`drift`), legacy pages the host's sweep checks (`bootstrap`), deletions+ * without a proof (`unproven_delete`), and, for a slug-fenced grant, the stamp itself (`grant_scope`). Counts cover only+ * pages the grant sees; nothing here implies another writer.+ */+export function remoteReconcile(level: ShadowLevel, input: { committed: number; grantPrefixes: readonly string[] | null }): RemoteReconcile {+ const unsettled: RemoteReconcile['unsettled'] = {};+ const bump = (reason: RemoteUnsettledReason) => { unsettled[reason] = (unsettled[reason] ?? 0) + 1; };+ for (const entry of level.paths) {+ if (input.grantPrefixes && !grantSees(level, entry, input.grantPrefixes)) continue;+ const r = entry.result;+ if (r.cls === 'legacy_unverified') { bump('bootstrap'); continue; }+ if (r.settled || r.inFlight) continue;+ if (r.cls === 'delete_drift') bump('unproven_delete');+ else if (['drift', 'keep_db', 'deleted_edited', 'dirty', 'spelling', 'held'].includes(r.cls)) bump('drift');+ }+ if (input.grantPrefixes) unsettled.grant_scope = 1;+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', level.sourceId, '--json'] };+ return { committed: input.committed, unsettled, fix: { argv: ['gbrain', 'sync', '--source', level.sourceId], consent: [], actor: 'user', requires_exclusive: false, verify,+ user_message: `Run gbrain sync --source ${level.sourceId} on the brain host that owns this source: it settles what a remote caller cannot (${Object.keys(unsettled).join(', ') || 'the converged stamp'}).`,+ why: `This remote sync committed ${input.committed} one-sided write(s). Holds, deletion markers, keep_db writes and the converged stamp are written only by the owner host's own sync, so the source is not stamped until it runs there.` } };+}+/** Once per pass: release the concept drift skips of pages the pass classified `matched` (§4). */export async function finishPassApply(engine: BrainEngine, sourceId: string, state: PassApplyState): Promise<number> {return state.matchedSlugs.length ? releaseMatchedDriftSkips(engine, sourceId, state.matchedSlugs) : 0;diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 1309c91f75..9d7ef7513c 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -40,7 +40,7 @@ import { resolveSlugForPath } from '../sync.ts';import { syncOriginPath } from './sync-origin.ts';import { originMarkerFingerprint } from './sync-markers.ts';import { passResumeArgs } from './sync-pass-readers.ts';-import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts } from './sync-pass-apply.ts';+import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';import { currentEmbeddingPricePerMTok } from '../embedding.ts';@@ -348,8 +348,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrlevelSlugMode = level.slugMode;lastLevel = level;value.telemetry.timings_ms = level.timings_ms;- if (bootstrap && round === 1) await writeLegacyMarkers(engine, level);- await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions }, applied);+ if (bootstrap && round === 1 && !remote) await writeLegacyMarkers(engine, level);+ await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,+ grantPrefixes: remote ? authority.writer.slugPrefixes : null }, applied);assertActive();if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];@@ -369,7 +370,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prif (r.action === 'delete') {if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }deletes.push(entry);- } else if (r.action === 'import' || r.action === 'reparse' || r.cls === 'drift' || r.cls === 'dirty') imports.push(entry);+ } else if (r.action === 'import' || r.action === 'reparse' || (!remote && (r.cls === 'drift' || r.cls === 'dirty'))) imports.push(entry);else owed.push(entry);}const candidates = deletes.length + imports.length;@@ -384,8 +385,13 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr}if (!candidates && inFlight.length) { await save('resumable', 'writer_pending'); return result('partial', 'writer_pending'); }if (!candidates) {+ if (remote) {+ // Design §5: a remote caller stops after its one-sided work; the owner host settles and stamps the rest.+ const reconcile = remoteReconcile(level, { committed: counts.added + counts.modified + counts.deleted + counts.renamed, grantPrefixes: authority.writer.slugPrefixes });+ await save('blocked', 'reconcile_host_required');+ return { ...result('blocked_by_failures', 'reconcile_host_required'), reconcile };+ }if (mismatch.length || owed.length) break;- if (remote) { await save('blocked', 'reconcile_host_required'); return result('blocked_by_failures', 'reconcile_host_required'); }if (round === 1 && configured && context.source.last_commit === head && !episode && !retry.length && !tail) {// v3 §3.3: a pass that finds nothing at last_commit = T admits no checkpoint; it keeps master's up_to_date (only// last_sync_at), and its full round refreshes the converged watermark so the next tick can be idle.diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsnew file mode 100644index 0000000000..3e4466d338--- /dev/null+++ b/src/core/persistence/sync-pass-status.ts@@ -0,0 +1,92 @@+/**+ * #6712 PR 4b (design v3.2 §9): `sync status --json`'s live `convergence` block and the pass's status reason, read from+ * the pass row (one primary-key read) plus the withheld-delete record, the holds the status already read and+ * `sync.admission`'s status. Additive: no other status field changes meaning. A source with no pass row yet (or a+ * company-brain source) keeps PR 4a's shadow under `--detail`.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import type { SyncAdmissionStatus } from './sync-admission.ts';+import { fileDriftSide, type GitHoldRecord } from './sync-holds.ts';+import { readDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';+import { NOT_CONVERGED_REPORT_STREAK, passHealth, type PassRoundSummary, type PassRow } from './sync-pass-row.ts';++export interface PassConvergence {+ schema: 'convergence/1'; dry_run: false; source_id: string;+ pass_id: string; kind: string; outcome: string; stop_reason: string | null; target: string; converged_at: string | null;+ round: number; candidates: number; settled: number; remaining: number; eta_seconds: null; eta_reason: 'pass_round_local';+ counts: Record<string, number>;+ decisions: { both: number; unknown: number; deleted: number };+ db_ahead: PassRoundSummary['db_ahead']; full_skipped_db_ahead: number;+ legacy_unverified: number; legacy_pageless: number;+ keep_db_admitted: number; keep_db_pending: number;+ deletes_withheld: { count: number; ratio: number; set_hash: string; samples: string[] } | null;+ classes: Record<string, { count: number; action: 'none' | 'owner' | 'repair' }>;+ settle_mismatch: string[];+ episode: { full_id: string | null; opened_at: string; inherited: { noEmbed: boolean; noExtract: boolean; noSchemaPack: boolean; from: string }; selection_fp: string | null;+ reserved_usd: number | null; approved_usd: number | null } | null;+ admission: SyncAdmissionStatus;+ not_converged_streak: number;+ duration_ms: number | null; timings_ms: Record<string, number>; last_full_at: string | null;+}++/** The live block of one source's pass row (design §9's field table). `holds` are the incarnation's holds the status read. */+export async function passConvergence(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; row: PassRow; holds: readonly GitHoldRecord[];+ admission: SyncAdmissionStatus; withheld?: DeletesWithheld | null }): Promise<PassConvergence> {+ const { telemetry: t, obligations: o } = input.row.value;+ const withheld = input.withheld !== undefined ? input.withheld : await readDeletesWithheld(engine, input.sourceId, input.incarnation);+ const decisions = { both: 0, unknown: 0, deleted: 0 };+ for (const hold of input.holds) if (hold.code === 'file_drift') { const side = fileDriftSide(hold.meta); if (side) decisions[side]++; }+ const summary = t.summary ?? { db_ahead: { pending: 0, db_only: 0, unproven: 0, by_prefix: {} }, full_skipped_db_ahead: 0, legacy_unverified: 0, legacy_pageless: 0 };+ const episode = o.episode;+ return { schema: 'convergence/1', dry_run: false, source_id: input.sourceId, pass_id: t.pass_id, kind: t.kind, outcome: t.outcome, stop_reason: t.stop_reason, target: t.target,+ converged_at: o.converged?.at ?? null, round: t.round, candidates: t.candidates, settled: t.settled, remaining: t.remaining, eta_seconds: null, eta_reason: 'pass_round_local',+ counts: t.counts, decisions, db_ahead: summary.db_ahead, full_skipped_db_ahead: summary.full_skipped_db_ahead, legacy_unverified: summary.legacy_unverified,+ legacy_pageless: summary.legacy_pageless, keep_db_admitted: t.counts.keep_db_admitted ?? 0, keep_db_pending: t.counts.keep_db_pending ?? 0,+ deletes_withheld: withheld ? { count: withheld.count, ratio: withheld.ratio, set_hash: withheld.set_hash, samples: withheld.samples } : null,+ classes: t.classes ?? {}, settle_mismatch: Object.keys(o.mismatch ?? {}).sort(),+ episode: episode ? { full_id: episode.full_id ?? null, opened_at: episode.opened_at, inherited: episode.inherited, selection_fp: null,+ reserved_usd: o.cost?.reserved_usd ?? null, approved_usd: o.cost?.approved_usd ?? null } : null,+ admission: input.admission, not_converged_streak: o.not_converged_streak ?? 0,+ duration_ms: t.duration_ms, timings_ms: t.timings_ms, last_full_at: o.converged?.last_full_at ?? null };+}++export type PassStatusReason = 'pass_unfinished' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused';++/** The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged. Null: nothing to add. */+export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, now = Date.now()): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {+ const t = row.value.telemetry;+ if (t.outcome === 'open' || (t.outcome === 'resumable' && t.stop_reason !== 'not_converged' && t.stop_reason !== 'admission_paused')) return ['resumable', 'pass_unfinished'];+ if (t.stop_reason === 'admission_paused') return ['resumable', 'admission_paused'];+ if (t.stop_reason === 'not_converged' || (row.value.obligations.not_converged_streak ?? 0) > 0) return ['resumable', 'not_converged'];+ if (passHealth(row, { now, stalledMs: Number.POSITIVE_INFINITY }).reason === 'settle_mismatch') return ['resumable', 'settle_mismatch'];+ if (withheld) return ['blocked', 'deletes_withheld'];+ if (t.outcome === 'synced' && t.stop_reason === 'selection_scoped') return ['synced', 'selection_scoped'];+ return null;+}++/** The next step for a pass reason (`resume`: the plain sync's arguments). */+export function passStatusNext(sourceId: string, reason: PassStatusReason, row: PassRow, resume: string[]): Action {+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };+ const sync: Action = { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify, why: '' };+ switch (reason) {+ case 'not_converged':+ return (row.value.obligations.not_converged_streak ?? 0) >= NOT_CONVERGED_REPORT_STREAK+ ? { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `The last ${row.value.obligations.not_converged_streak} passes of ${sourceId} ended not converged; another sync will not change that. Report what doctor shows with the gbrain version (read-only).` }+ : { ...sync, why: 'The last pass ran out of rounds before every path settled; the same sync continues from the current level.' };+ case 'deletes_withheld':+ return { argv: ['gbrain', 'sync', '--source', sourceId, '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false, verify,+ user_message: `Sync of ${sourceId} withheld a mass delete (more than half of its file-backed pages). If the checkout is the wrong one or incomplete, restore it and sync again; if the deletion is intended, run GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source ${sourceId} on the brain host.`,+ why: 'The dry run lists the withheld set and its hash (read-only); everything else of the source is synced.' };+ case 'admission_paused':+ return { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify,+ user_message: `sync.admission pauses what sync admits for ${sourceId}; restore it with gbrain config set sync.admission normal when the pause is over.`,+ why: 'The pause is the owner\'s setting; it is never lifted automatically.' };+ case 'selection_scoped':+ return { ...sync, why: 'The last pass converged at a narrower selection and did not advance last_commit; the plain sync runs the configured selection.' };+ default:+ return { ...sync, why: reason === 'settle_mismatch' ? 'A path keeps settling without reading settled; the next sync re-admits it once and holds it after three passes in a row.'+ : 'The newest pass did not finish; the plain sync continues it from the current level.' };+ }+}diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 02f860b2fa..f019c3bc87 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -42,6 +42,10 @@ import { classifyRecordedFault, classifyTerminal, type TerminalCategory } from 'import type { PublicCategory } from './public-category.ts';import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';import { sha256 } from './digest.ts';+import { readPassRow } from './sync-pass-row.ts';+import { readDeletesWithheld } from './sync-markers.ts';+import { passResumeArgs } from './sync-pass-readers.ts';+import { passConvergence, passStatusNext, passStatusState } from './sync-pass-status.ts';export interface SyncStatusHold extends SyncFaultVerdict {code: string;@@ -134,7 +138,7 @@ export interface SyncStatus {* only \`--detail\` runs it (\`convergence_read\`). Null when not read, on a brain that is not managed, or for a company-brain* source; \`status: 'unavailable'\` names why a read could not run. No other field's meaning depends on it.*/- convergence: import('./sync-convergence.ts').ConvergenceReceipt | { dry_run: true; status: 'unavailable'; code: string; message: string } | null;+ convergence: import('./sync-convergence.ts').ConvergenceReceipt | { dry_run: true; status: 'unavailable'; code: string; message: string } | import('./sync-pass-status.ts').PassConvergence | null;convergence_read: SyncStatusRead;/** #6712 PR 4b: `sync.admission` (brain-wide), when it was set, and whether it is in effect for this source (sync-admission.ts). */admission: import('./sync-admission.ts').SyncAdmissionStatus;@@ -142,7 +146,9 @@ export interface SyncStatus {export type SyncStatusState = 'synced' | 'resumable' | 'blocked';/** Why the source is in its state; one closed list. */export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'cursor_unfinished', 'live_job', 'last_error', 'holds_actionable', 'recovery_pending', 'request_pending',- 'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked'] as const;+ 'status_unknown', 'needs_human', 'head_blocked', 'recovery_blocked',+ // #6712 PR 4b (design v3.2 §9): the live pass's reasons.+ 'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused'] as const;export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];export type SyncStatusRead = { status: 'read' } | { status: 'not_read'; fix: Action };/** The bound of each default probe (the oldest blocker, the recovery records). */@@ -269,7 +275,11 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;const p = header?.progress;const estimate = unfinished && p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };- const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });+ // #6712 PR 4b (design §9): the pass row (one primary-key read) and the withheld-delete record make the live `convergence` block.+ const passRow = await readPassRow(engine, sourceId, source.incarnation);+ const withheld = passRow ? await readDeletesWithheld(engine, sourceId, source.incarnation) : null;+ const passState = passRow ? passStatusState(passRow, withheld) : null;+ const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);// #6643: a knock-on or a superseded run is not a failure of its page: the resume re-freezes the entry.const selfHealing = lastError?.detail === 'knock_on' || lastError?.detail === 'run_replaced';@@ -303,35 +313,42 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst { recovery_next, ...terminal } = detail ? await terminalSummary(engine, sourceId, blockers.checkpoint_blockers): { status: 'unknown' as const, reason: 'not_read: run sync status with --detail', recovery_next: recovery.status === 'ok' && recovery.first ? recoveryAction(sourceId, recovery.first) : undefined };const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);- const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0 });+ const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });+ const admission = await (await import('./sync-admission.ts')).syncAdmissionStatus(engine, sourceId, source.incarnation);+ const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume) : null;return { source_id: sourceId, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],- terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,+ terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? passNext ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Action: stateReason === 'status_unknown' ? { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The oldest-blocker or recovery probe did not answer within ${SYNC_STATUS_PROBE_MS / 1000} s, so this status does not know the state (it is not reported synced). Rerun it after a short wait; gbrain doctor --json checks the database if it keeps timing out.` } satisfies Action : null),state, reason: stateReason,oldest_blocker: oldest, recovery, checkpoint_blockers_read: detail ? { status: 'read' } : notRead('checkpoint blocker list'),cursors_read: detail ? { status: 'read' } : notRead('live cursor'), terminal_failures_read: detail ? { status: 'read' } : notRead('terminal-failure summary'),- convergence: detail ? await (await import('./sync-pass.ts')).statusConvergence(engine, sourceId) : null, convergence_read: detail ? { status: 'read' } : notRead('convergence shadow'),- admission: await (await import('./sync-admission.ts')).syncAdmissionStatus(engine, sourceId, source.incarnation) };+ convergence: passRow ? await passConvergence(engine, { sourceId, incarnation: source.incarnation, row: passRow, holds: records, admission, withheld })+ : detail ? await (await import('./sync-pass.ts')).statusConvergence(engine, sourceId) : null,+ convergence_read: passRow || detail ? { status: 'read' } : notRead('convergence shadow'),+ admission };}/** #6712 PR 2: the state and its reason, from what this read saw; a probe that did not answer never yields `synced`. */function statusState(s: { human: boolean; oldest: SyncStatus['oldest_blocker']; recovery: SyncStatus['recovery']; liveJob: boolean; unfinished: boolean; lastError: boolean;- actionable: boolean; holds: boolean }): [SyncStatusState, SyncStatusReason] {+ actionable: boolean; holds: boolean; pass?: [SyncStatusState, SyncStatusReason] | null }): [SyncStatusState, SyncStatusReason] {if (s.human) return ['blocked', 'needs_human'];if (s.recovery.status === 'ok' && s.recovery.first?.blocked) return ['blocked', 'recovery_blocked'];if (s.oldest.status === 'ok' && s.oldest.request?.blocked_by?.intervention && s.oldest.request.state === 'queued') return ['blocked', 'head_blocked'];if (s.liveJob) return ['resumable', 'live_job'];if (s.unfinished) return ['resumable', 'cursor_unfinished'];if (s.lastError) return ['resumable', 'last_error'];+ // #6712 PR 4b: never `synced` while the newest pass is open or ended unconverged (a scoped convergence stays `synced`).+ if (s.pass && s.pass[0] !== 'synced') return s.pass;if (s.actionable) return ['resumable', 'holds_actionable'];if (s.recovery.status === 'ok' && s.recovery.count > 0) return ['resumable', 'recovery_pending'];if (s.oldest.status === 'ok' && s.oldest.request) return ['resumable', 'request_pending'];if (s.oldest.status !== 'ok' || s.recovery.status !== 'ok') return ['resumable', 'status_unknown'];+ if (s.pass) return s.pass;return ['synced', s.holds ? 'held_by_design' : 'nothing_pending'];}