Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP #6643: fault classes, sync status cursors, knock-on limits, error code

garrytan4dda35db8ebf
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 940fa3c0b6..c2104414cc 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -98,6 +98,10 @@ Every hold and error has three fields, from one table
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
| `source_changed` | page | retry | no | the same path fails again after a rerun |
| `cancelled` | page | retry | no | the same group is cancelled again after a rerun |
+| `knock_on` | page | retry | no | the same root request is named again after a rerun |
+| `run_replaced` | page | retry | no | never: another run of the source superseded this one and covers its pages |
+| `outside_fence` | systemic | none | yes | always: a request published outside the cursor that admitted it |
+| `knock_on_exhausted` | systemic | none | yes | always: re-freezing did not get past the failing page |
| `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command |
| `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) |
| `database_contention` | connection | retry | no | three reruns in a row stop on it |
@@ -122,6 +126,19 @@ or `statement_timeout` on a parallel publish lane) also carries that fault as
The verdict is the same retry; the detail says the database, not the page,
ended the group.
+A page that only waited on another page of the same sync (a knock-on: its
+group, window or lane predecessor did not commit) is re-frozen by the sync
+itself under a fresh request on the next pass; `--retry-failed` is not
+needed for it. Its error carries `last_error.detail: knock_on` and
+`last_error.root_cause` (the request, page and error it waited on); act on
+the root. A cursor refusal is classified by its recorded cause:
+`run_replaced` (another run of the source took over; nothing to do),
+`window_dropped` (a knock-on), or `outside_fence` (a request was not the
+entry its cursor held: a person stops the extra drain and reports it).
+After `sync.knock_on_refreeze_limit` re-freezes at one index (default 3;
+0 turns automatic re-freeze off), or 25 in one run, the run stops with
+`knock_on_exhausted` and names the root.
+
An unknown code is systemic and human: `gbrain errors <code>` explains it
offline, `gbrain doctor --json` says what the brain thinks.
@@ -157,7 +174,9 @@ it and kept going; the receipt lists the hold (`held`, `held_count`) and
- `revision_conflict`, `page_identity_changed`, `pinned_git_worktree_conflict`
as a `last_error` come from a run on an older release; this release holds
them. Rerun with `--retry-failed`: the stopped entry converts in place, the
- manifest is not re-frozen.
+ manifest is not re-frozen. A `revision_conflict` or `cancelled` error with
+ `detail: knock_on` needs no flag: the next plain sync re-freezes the entry
+ (act on `root_cause` instead).
### Connection
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index dbe861706d..931fd56e28 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -22,7 +22,7 @@ export interface SyncResult {
/** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */
retryWait?: import('../core/persistence/sync-run.ts').RetryWait;
/** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */
- knockOns?: { refrozen: number; perIndexLimit: number; runLimit: number };
+ knockOns?: { refrozen: number };
status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';
fromCommit: string | null;
toCommit: string;
diff --git a/src/core/config.ts b/src/core/config.ts
index c466addef0..cba31a1939 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1736,6 +1736,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.hold_escalate_count',
'sync.hold_escalate_pct',
'sync.parser_regression',
+ // #6643: knock-on re-freezes in a row at one index (default 3; 0 turns automatic re-freeze off) and per run (default 25).
+ 'sync.knock_on_refreeze_limit',
+ 'sync.knock_on_run_limit',
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on
'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 758261d4c4..06db42d622 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -361,6 +361,12 @@ export const CODES = {
preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },
profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },
projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },
+ // #6643: a managed sync stopped re-freezing pages that only waited on another page of the same sync.
+ knock_on_exhausted: { class: 'server', summary: "A managed sync kept re-freezing a page that only waited on another page of the same sync, and stopped at its limit because that earlier page still did not commit.",
+ why: "A page cancelled or refused only because an earlier page of its sync did not commit published nothing, so the sync re-freezes it under a fresh request by itself; the limit stops a loop when the earlier page keeps failing.",
+ docs: 'docs/guides/sync-unblock-runbook.md#decision-table',
+ suggestion: 'Read gbrain sync status --source <id> --json: last_error.root_cause names the request that keeps failing. Fix that request, or raise sync.knock_on_refreeze_limit / sync.knock_on_run_limit, then rerun the same sync.',
+ fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the root request, its page and error; read-only.' } },
keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's CJK keyword arm hit its deadline or candidate cap on a large corpus, so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan; the arm is bounded so a large brain cannot stall every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Narrow the search with --source-id (MCP source_id), or ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },
projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },
provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 00d21b4447..a2b189422c 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -64,6 +64,14 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ code: 'pinned_git_worktree_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'source_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'cancelled', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same group is cancelled again after a rerun' },
+ // #6643: refinements of `cancelled` / `revision_conflict` by the receipt's recorded cause; they take precedence over the code.
+ { code: 'knock_on', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same root request is named again after a rerun',
+ human_reason: 'This page only waited on another page of the same sync; the next sync re-freezes it by itself. Fix the root request the error names.' },
+ { code: 'run_replaced', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: another run of the source superseded this one and covers its pages' },
+ { code: 'outside_fence', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: a request published outside the cursor that admitted it',
+ human_reason: 'A sync request was not the entry its cursor held (two drains of one cursor, or a writer defect). gbrain sync status --source <source> --json lists the live cursors; stop the extra drain (gbrain autopilot pause --reason <why>) and report the fence snapshot the error carries.' },
+ { code: 'knock_on_exhausted', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: re-freezing did not get past the failing page',
+ human_reason: 'The same page kept being cancelled because an earlier page of the sync never committed. Fix the root request the error names, or raise sync.knock_on_refreeze_limit, then rerun the sync; the count resets when the page commits.' },
{ code: 'sync_incomplete', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: an unfinished cursor resumes with the same command' },
// Connection class: transport only; the cursor and manifest stand.
{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index d53d368dc4..7081ded3ce 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -7,6 +7,7 @@ import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
+import { readFix } from '../ops/op-fix.ts';
import type { RegistryCode } from '../error-registry.ts';
import { ownerGateInput, ownerImportTrust } from '../trust/channel.ts';
import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';
@@ -127,7 +128,7 @@ async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncInten
},
() => readSyncCursorFence(tx, p.cursorKey),
async () => {
- if (after && !await windowPredecessorAllows(tx, row)) throw withSyncRefusal(syncPublicationRefusal('revision_conflict', EARLIER_PAGE_REFUSAL_MESSAGE, row, p,
+ if (after && !await windowPredecessorAllows(tx, row)) throw withSyncRefusal(knockOnRefusal(EARLIER_PAGE_REFUSAL_MESSAGE, row,
`Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`), knockOnDetail('window_predecessor', after));
},
async () => {
@@ -162,6 +163,17 @@ function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteR
+ `Once it is final and the cause is fixed, run: ${rerun}`, { fix, ...extra });
}
+/**
+ * #6643: a refusal that is not a failure of its page (a knock-on, or a request whose run another run replaced). Its
+ * next step is the status read, never a `--retry-failed` rerun: the next sync pass re-freezes the entry by itself.
+ */
+function knockOnRefusal(message: string, row: WriteRequest, cause: string): OperationError {
+ const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];
+ return opError('revision_conflict', message, `${cause} Request ${row.request_id} in ${row.source_id} published nothing, and the next sync pass re-freezes its page by itself; `
+ + `${status.join(' ')} names the request it waited on (root_cause). Do not resubmit it.`,
+ { fix: readFix('Shows the sync cursor, the root cause of this refusal and the next step, read-only.', { argv: status }) });
+}
+
/** #6643: attaches the owner-side classification the coordinator stores as the receipt's `error_detail`. */
function withSyncRefusal(error: OperationError, detail: object): OperationError {
error.syncRefusal = { ...detail };
@@ -181,7 +193,8 @@ function cursorFenceRefusal(row: WriteRequest, p: SyncIntent, cursor: SyncCursor
const cause = cursor.run_id !== p.runId ? 'run_replaced'
: p.kind !== 'managed_sync_checkpoint' && cursorIndex !== null && Number.isFinite(cursorIndex) && p.index > cursorIndex ? 'window_dropped' : 'outside_fence';
const fence = { run_id: cursor.run_id, expected_run_id: p.runId, request_id: cursor.request_id, members: cursor.group?.length ?? 0, index: cursorIndex, request_index: p.index };
- const error = syncPublicationRefusal('revision_conflict', CURSOR_CHANGED_REFUSAL_MESSAGE, row, p,
+ const error = (cause === 'outside_fence' ? (why: string) => syncPublicationRefusal('revision_conflict', CURSOR_CHANGED_REFUSAL_MESSAGE, row, p, why)
+ : (why: string) => knockOnRefusal(CURSOR_CHANGED_REFUSAL_MESSAGE, row, why))(
cause === 'run_replaced' ? `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`
: cause === 'window_dropped' ? `Request ${row.request_id} was admitted ahead of the cursor of ${row.source_id}, which dropped it after an earlier page of the same run did not commit.`
: `Request ${row.request_id} is not the entry the cursor of ${row.source_id} holds (cursor at index ${cursorIndex ?? 'unknown'}, request ${cursor.request_id ?? 'none'}), so it must not publish.`);
@@ -450,7 +463,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
() => validateSyncAuthority(tx, p.syncAuthority, row.slug),
async () => {
const failed = await earlierGroupMemberFailed(tx, row);
- if (failed) throw withSyncRefusal(syncPublicationRefusal('revision_conflict', EARLIER_PAGE_REFUSAL_MESSAGE, row, p,
+ if (failed) throw withSyncRefusal(knockOnRefusal(EARLIER_PAGE_REFUSAL_MESSAGE, row,
`Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`), knockOnDetail('group_member', failed));
},
async () => {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index b94ed2bbfd..bd5b2b6af0 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -302,6 +302,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
filesImported: cursor.index, bankedFiles: cursor.index,
managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },
...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
+ ...(cursor.knockOns ? { knockOns: { refrozen: cursor.knockOns } } : {}),
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
}
@@ -724,14 +725,19 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:
/** #6643: the terminal code of a run that stopped re-freezing knock-ons (per-index limit or per-run breaker). */
export const KNOCK_ON_EXHAUSTED = 'knock_on_exhausted';
-/** #6643: the most knock-on re-freezes one run makes before it stops with the root cause (a per-run breaker, like `breakerAfter`). */
-export const KNOCK_ON_RUN_LIMIT = 25;
const CHECKPOINT_REVIVAL_LIMIT = 3;
-/** `sync.knock_on_refreeze_limit`: knock-on re-freezes in a row at one index (default 3; 0 turns automatic re-freeze off). */
-export async function knockOnRefreezeLimit(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {
- const raw = (await engine.getConfig('sync.knock_on_refreeze_limit').catch(() => null))?.trim();
- const parsed = raw ? Number(raw) : NaN;
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : 3;
+/**
+ * #6643: `sync.knock_on_refreeze_limit`, knock-on re-freezes in a row at one index (default 3; 0 turns automatic
+ * re-freeze off), and `sync.knock_on_run_limit`, the most one run makes before it stops with the root cause (default
+ * 25, a per-run breaker like `breakerAfter`).
+ */
+export async function knockOnLimits(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ perIndex: number; perRun: number }> {
+ const read = async (key: string, fallback: number) => {
+ const raw = (await engine.getConfig(key).catch(() => null))?.trim();
+ const parsed = raw ? Number(raw) : NaN;
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
+ };
+ return { perIndex: await read('sync.knock_on_refreeze_limit', 3), perRun: await read('sync.knock_on_run_limit', 25) };
}
type SettleInput = Parameters<typeof settleFailedRequest>[1];
@@ -741,17 +747,17 @@ type SettleInput = Parameters<typeof settleFailedRequest>[1];
* is re-frozen under a fresh request, whatever the hold policy, the source kind or `--retry-failed`: a knock-on never
* published anything, so it is not a failure of its page. The re-freeze goes through the narrowed gate
* (`holdUnderGate`), which settles the run's suffix under the cursor fence and records every stale receipt at the
- * index as superseded. Bounded per index (`sync.knock_on_refreeze_limit`) and per run (`KNOCK_ON_RUN_LIMIT`).
+ * index as superseded. Bounded per index (`sync.knock_on_refreeze_limit`) and per run (`sync.knock_on_run_limit`).
*/
-async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<null | 'pending' | { cursor: Cursor } | { exhausted: { attempts: number; limit: number; runCount: number } }> {
+async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<null | 'pending' | { cursor: Cursor } | { exhausted: { attempts: number; limit: number; runCount: number; runLimit: number } }> {
const { cursor, key, pending, done, assertActive } = input;
if (pending.intent.kind === 'managed_sync_checkpoint' || !isSyncKnockOn(done)) return null;
const entry = cursor.entries[cursor.index];
if (!entry || entry.path !== pending.intent.path) return null;
- const limit = await knockOnRefreezeLimit(engine);
- if (limit === 0) return null;
+ const limits = await knockOnLimits(engine);
+ if (limits.perIndex === 0) return null;
const attempts = pending.knockOn?.attempts ?? 0, runCount = cursor.knockOns ?? 0;
- if (attempts >= limit || runCount >= KNOCK_ON_RUN_LIMIT) return { exhausted: { attempts, limit, runCount } };
+ if (attempts >= limits.perIndex || runCount >= limits.perRun) return { exhausted: { attempts, limit: limits.perIndex, runCount, runLimit: limits.perRun } };
const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;
const refrozen = await freezeEntry(engine, base, key, assertActive, input.run);
assertActive();
@@ -836,7 +842,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
const exhausted = knockOn && 'exhausted' in knockOn ? knockOn.exhausted : null;
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
code: exhausted ? KNOCK_ON_EXHAUSTED : done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'),
- message: exhausted ? `This page was re-frozen ${exhausted.attempts} time(s) at the same index (limit ${exhausted.limit}), or this run re-froze ${exhausted.runCount} knock-on page(s) (limit ${KNOCK_ON_RUN_LIMIT}), and an earlier page of the same sync still did not commit; the run stopped instead of re-freezing again.`
+ message: exhausted ? `This page was re-frozen ${exhausted.attempts} time(s) at the same index (sync.knock_on_refreeze_limit ${exhausted.limit}), or this run re-froze ${exhausted.runCount} knock-on page(s) (sync.knock_on_run_limit ${exhausted.runLimit}), and an earlier page of the same sync still did not commit; the run stopped instead of re-freezing again.`
: done.error_message ?? 'The accepted sync request did not commit.',
...(rootCause ? { root_cause: rootCause } : {}),
request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 8ecb6f4411..ad28cc5174 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -62,6 +62,8 @@ export interface SyncStatusError extends SyncFaultVerdict {
phase: ManagedSyncFailure['phase'];
first_seen: string;
attempts: number;
+ /** #6643: what caused this failure (a knock-on's root request, or the receipt blocking a checkpoint). */
+ root_cause?: ManagedSyncFailure['root_cause'];
}
export interface SyncStatus {
@@ -79,6 +81,8 @@ export interface SyncStatus {
human_reason?: string;
/** The resume arguments after `gbrain sync` for this source's cursor (its stored options when one exists). */
resume_argv: string[];
+ /** #6643: every managed-sync cursor of the source under its current incarnation, newest first (at most 20). */
+ cursors: SyncStatusCursor[];
next: Action | null;
}
@@ -140,13 +144,19 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');
const failure = failures[0];
const reason = typeof failure?.write_error_detail?.reason === 'string' ? failure.write_error_detail.reason : null;
- const laneFault = (failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null) ?? reason;
+ // #6643: a stop the run itself declared, then the root's recorded cause, then a knock-on, then the lane fault or reason.
+ const rootCause = failure?.root_cause;
+ const laneFault = failure?.code === 'knock_on_exhausted' ? null
+ : (rootCause?.cause === 'outside_fence' || rootCause?.cause === 'run_replaced' ? rootCause.cause : null)
+ ?? (rootCause && failure && ['cancelled', 'revision_conflict'].includes(failure.code) ? 'knock_on' : null)
+ ?? (failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null) ?? reason;
const retired = failure || header ? null : await retiredCursorStands(engine, sourceId, source.incarnation);
const repairPreview: Action = { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
why: 'Previews the sync bookkeeping nothing current can resume or clear (an old incarnation\'s cursor and failure rows, stale mirror rows) with the hash its --apply takes; writes nothing.' };
const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, ...(failure.write_error_detail ? { write_error_detail: failure.write_error_detail } : {}),
path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,
- ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }
+ ...(failure.request_id ? { request_id: failure.request_id } : {}), ...(rootCause ? { root_cause: rootCause } : {}),
+ ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }
: retired ? { code: 'cursor_incarnation_retired', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `
+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;
const unfinished = !!header && !header.done;
@@ -155,6 +165,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
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 });
const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);
+ // #6643: a knock-on or a superseded run needs no --retry-failed: the plain sync re-freezes the entry.
+ const selfHealing = lastError?.detail === 'knock_on' || lastError?.detail === 'run_replaced';
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
const next: Action | null = human
@@ -167,14 +179,40 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
+ ' and names the sync to run; it refuses the rest by name and drops nothing.' }
: retired ? { ...repairPreview, verify }
: unfinished || lastError
- ? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
- why: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
+ ? { argv: ['gbrain', 'sync', ...resume, ...(lastError && !selfHealing ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: lastError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${lastError.detail}); the same sync re-freezes it by itself${lastError.root_cause?.request_id ? `, and request ${lastError.root_cause.request_id} is what it waited on` : ''}.`
+ : lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
: `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }
: 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, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
- resume_argv: resume, next };
+ resume_argv: resume, cursors: await liveCursors(engine, sourceId, source.incarnation, header?.runId ?? null), next };
+}
+
+/** #6643: one managed-sync cursor of the source (the cursor key digests the writer principal, authority and options, so a source can have several). */
+export interface SyncStatusCursor {
+ key_prefix: string; run_id: string; index: number; total: number; done: boolean;
+ /** The principal whose syncs select this cursor (with matching options). */
+ writer: { kind: string; id: string } | null;
+ pending: { request_id: string; kind: string | null; state: string | null } | null;
+ updated_at: string;
+ /** The cursor the top-level `cursor`, `run_id` and `next` describe (the newest of the current incarnation). */
+ shown: boolean;
+ resume_argv: string[];
+}
+
+async function liveCursors(engine: BrainEngine, sourceId: string, incarnation: string, shownRun: string | null): Promise<SyncStatusCursor[]> {
+ const rows = await engine.executeRaw<{ fingerprint: string; header: CursorHeader & { authority?: { writer?: { principal?: { kind: string; id: string } } }; pending?: { requestId?: string; intent?: { kind?: string } } };
+ updated_at: string; state: string | null }>(
+ `SELECT c.fingerprint, c.completed_keys->0 AS header, to_char(c.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_at, r.state
+ FROM op_checkpoints c LEFT JOIN persistence_requests r ON r.source_id=$1 AND r.request_id::text=c.completed_keys->0->'pending'->>'requestId'
+ WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1 AND c.completed_keys->0->>'incarnation'=$2 ORDER BY c.updated_at DESC LIMIT 20`, [sourceId, incarnation]);
+ return rows.map(row => ({ key_prefix: row.fingerprint.slice(0, 12), run_id: row.header.runId, index: Number(row.header.index), total: Number(row.header.total), done: !!row.header.done,
+ writer: row.header.authority?.writer?.principal ?? null,
+ pending: row.header.pending?.requestId ? { request_id: row.header.pending.requestId, kind: row.header.pending.intent?.kind ?? null, state: row.state } : null,
+ updated_at: row.updated_at, shown: row.header.runId === shownRun,
+ resume_argv: managedSyncResumeArgs({ sourceId, processingOptions: row.header.processingOptions, syncOptions: row.header.syncOptions }) }));
}
/** #6377: what the content-repair lane did to one held path during `unblock --apply`; codes, tiers and hashes only. */