Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 2 (L5): sync status reports state and reason, skips heavy reads unless --detail, and never reads as an all-clear
garrytan784d46d9f984
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex d090801d9d..27e4d81469 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -12,7 +12,7 @@ import type { BrainEngine } from '../../core/engine.ts';import { cliRenderContext, renderAction } from '../../core/agent-output.ts';import { writeJsonDocument } from '../../core/cli-force-exit.ts';import { opError } from '../../core/ops/contract.ts';-import { readSyncStatus, unblockSync } from '../../core/persistence/sync-status.ts';+import { readSyncStatus, unblockSync, type SyncStatus } from '../../core/persistence/sync-status.ts';import { HOLD_ATTEMPTS_NEEDS_HUMAN } from '../../core/persistence/sync-fault-class.ts';import { CONTENT_REPAIR_HOLD_KINDS } from '../../core/repair/content-lane.ts';import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';@@ -21,7 +21,7 @@ import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';const CONTENT_HOLD_CODES = Object.entries(CONTENT_REPAIR_HOLD_KINDS).filter(([, kind]) => kind).map(([code]) => code).join(', ');export function printSyncStatusHelp(): void {- console.log(`Usage: gbrain sync status --source <id> [--json]+ console.log(`Usage: gbrain sync status --source <id> [--detail] [--json]Where a managed catch-up stands and what to do next, for an operator agent:the cursor (index/total, pinned target, last advance), pages committed in the@@ -29,10 +29,21 @@ last 10 minutes, every held file and the last recorded failure, each withclass page | connection | systemicsafe_actions retry | retry_when_clean | repair | reconcile | upgrade | noneneeds_human whether a person has to decide or act (human_reason says why)-and one \`next\` action. The loop: run this every few minutes; when-committed_last_10m is 0 and needs_human is false, run-\`gbrain sync unblock --source <id> --apply\`, then the sync it prints; when-needs_human is true, page a person with the slug it names.+and one \`next\` action, plus the source's state (synced | resumable |+blocked) and its reason, the oldest unfinished request and any recovery+record (bounded probes that need no cursor; a probe that times out makes the+state resumable/status_unknown, never synced).++The terminal-failure summary, the checkpoint blocker list and the live cursor+list are heavy reads: a plain status skips them (the fields keep their types,+empty or unknown) and says so in terminal_failures_read, checkpoint_blockers_read+and cursors_read (status not_read, with the --detail command as fix); --detail+runs them. Never read a skipped field as "none".++The loop: run this every few minutes; when committed_last_10m is 0 and+needs_human is false, run \`gbrain sync unblock --source <id> --apply\`, then+the sync it prints; when needs_human is true, page a person with the slug it+names; when a *_read field is not_read and you need it, run its fix.Decision table: docs/guides/sync-unblock-runbook.md`);@@ -82,25 +93,32 @@ function sourceOf(args: string[]): string {export async function runSyncStatus(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) return printSyncStatusHelp();const sourceId = sourceOf(args);- const status = await readSyncStatus(engine, sourceId);+ const status = await readSyncStatus(engine, sourceId, { detail: args.includes('--detail') });const ctx = cliRenderContext();// #6696 (A4): the capacity picture rides every status read (unthrottled), from the 60 s snapshot.const { cachedCapacitySnapshot, capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');const { renderNotice } = await import('../../core/agent-output.ts');const snapshot = await cachedCapacitySnapshot(engine);const notices = (await capacityNotices(engine, { throttle: false })).map(notice => renderNotice(notice, ctx));+ const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,+ checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, ...(notices.length ? { notices } : {}) };if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));const c = status.cursor;- console.log(`Source ${sourceId}: ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`+ console.log(syncStatusHeadline(status));+ console.log(` ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`+ `${c.last_advance_at ? `, last advance ${c.last_advance_at}` : ''}` : 'no managed cursor'}`);console.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);+ const ob = status.oldest_blocker;+ console.log(` oldest unfinished request: ${ob.status === 'unknown' ? `unknown (${ob.reason})` : ob.request ? `${ob.request.request_id} (${ob.request.state}${ob.request.step ? `, step ${ob.request.step}` : ''}${ob.request.blocked_by ? `, blocked by ${ob.request.blocked_by.predicate}` : ''})` : 'none'}`+ + `; recovery records: ${status.recovery.status === 'unknown' ? `unknown (${status.recovery.reason})` : status.recovery.count}`);const t = status.terminal_failures;- if (t.status === 'unknown') console.log(` terminal write failures: unknown (${t.reason})`);+ if (status.terminal_failures_read.status === 'not_read') console.log(' terminal write failures, checkpoint blockers and cursors: not read (run with --detail)');+ else if (t.status === 'unknown') console.log(` terminal write failures: unknown (${t.reason})`);else {const oldest = t.unresolved.oldest_age_seconds === null ? '' : `, oldest ${Math.round(t.unresolved.oldest_age_seconds / 3600)} h`;console.log(` terminal write failures (last ${t.window_days} d): ${t.active_blockers.length} active blocker(s), ${t.unresolved.rows} unresolved (${t.unresolved.distinct_slugs} page(s), `@@ -113,6 +131,24 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promiselse console.log(' Next: nothing; the source is synced and holds nothing.');}+/** #6712 PR 2 (L5): the one headline per state; the reason names why. */+export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'state' | 'reason' | 'cursor' | 'run_id' | 'holds' | 'live_job_id'>): string {+ const c = status.cursor;+ switch (status.reason) {+ case 'nothing_pending': return `Source ${status.source_id} is synced${c?.done ? ` (last run ${status.run_id?.slice(0, 8) ?? '?'} finished at ${c.index}/${c.total})` : ''}.`;+ case 'held_by_design': return `Source ${status.source_id} is synced; ${status.holds.length} file(s) stay held by design.`;+ case 'live_job': return `Source ${status.source_id} is resumable: sync job #${status.live_job_id} is draining it.`;+ case 'cursor_unfinished': return `Source ${status.source_id} is resumable: run ${status.run_id?.slice(0, 8) ?? '?'} stands at ${c?.index ?? '?'}/${c?.total ?? '?'}; the next sync resumes it.`;+ case 'last_error': return `Source ${status.source_id} is resumable: the last run recorded a failure that a rerun holds or retries.`;+ case 'holds_actionable': return `Source ${status.source_id} is resumable: held files have a safe action (sync unblock).`;+ case 'recovery_pending': return `Source ${status.source_id} is resumable: a write's recovery record waits for an owner pass.`;+ case 'status_unknown': return `Source ${status.source_id}: state unknown (a probe did not answer); not reported synced.`;+ case '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.`;+ }+}+export async function runSyncUnblock(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) return printSyncUnblockHelp();const sourceId = sourceOf(args);diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 56eb50f267..37a7dc09a5 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -1057,7 +1057,9 @@ export function drainJsonFields(result: SyncResult, resumeCommand: string, sourcexport function formatDrainSummary(result: SyncResult, resumeCommand: string, sourceId: string): string[] {const d = result.drain;if (!d) return [];- const lines = [`Managed sync ${d.outcome}: ${d.processed} entries this run (${d.written} written, ${d.waived} waived)`+ // #6712 PR 2 (L5): one headline per state; a drain that finished a run an earlier invocation started says so.+ const resumed = d.outcome === 'synced' && result.runId && ((result.managedCursor?.progress?.startIndex ?? 0) > 0 || result.cursorAdopted) ? `resumed run ${result.runId} and converged, ` : '';+ const lines = [`Managed sync ${d.outcome}: ${resumed}${d.processed} entries this run (${d.written} written, ${d.waived} waived)`+ (d.remaining ? `, ${d.remaining} remaining` : '') + (d.rate_pages_per_min !== null ? `, ${d.rate_pages_per_min} pages/min` : '')+ (d.remaining && d.eta_seconds !== null ? `, indexing ETA ${formatDuration(d.eta_seconds)}` : '') + '.'];if (d.capacity) lines.push(` Waited ${d.capacity.waited_seconds}s for write capacity: ${d.capacity.outstanding ?? '?'} of ${d.capacity.limit ?? '?'} ${d.capacity.scope ?? 'principal'} outstanding-request slots in use.`);diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex da44544fed..ede527dfe1 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -37,8 +37,8 @@ import { headCommittedBytes } from './sync-page-fault.ts';import { laneFaultInMessage } from './sync-window.ts';import { cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';import { listIncompleteSyncReceipts, type SyncSettledIndexes } from './checkpoint-validation.ts';-import { drainEstimate } from './sync-drain.ts';-import { classifyRecordedFault, type TerminalCategory } from './terminal-classify.ts';+import { drainEstimate, engineStallProbe } from './sync-drain.ts';+import { classifyRecordedFault, classifyTerminal, type TerminalCategory } from './terminal-classify.ts';import type { PublicCategory } from './public-category.ts';import { resolveManagedSyncContext } from './sync-discovery.ts';@@ -104,7 +104,34 @@ export interface SyncStatus {/** #6650: the source's terminal write receipts that did not commit, summarized (`terminal-failures.ts`); `unknown` when the bounded read timed out. */terminal_failures: SyncTerminalSummary;next: Action | null;+ /**+ * #6712 PR 2 (L5): the source's state in the sync outcome vocabulary (`synced` | `resumable` | `blocked`) and why+ * (`SYNC_STATUS_REASONS`). Never `synced` while a probe this read relies on did not answer.+ */+ state: SyncStatusState;+ reason: SyncStatusReason;+ /** #6712 PR 2: the source's oldest unfinished request (its running one first), bounded; works without a cursor. `unknown` when the read timed out. */+ oldest_blocker: { status: 'ok'; request: { request_id: string; state: string; phase: string | null; step: string | null; lapsed: boolean; blocked_by: { predicate: string; state: string | null; intervention: boolean } | null } | null }+ | { status: 'unknown'; reason: string };+ /** #6712 PR 2: requests of the source still holding a publication recovery record (they hold their root), bounded. */+ recovery: { status: 'ok'; count: number; first: { request_id: string; slug: string; blocked: boolean } | null } | { status: 'unknown'; reason: string };+ /**+ * #6712 PR 2: whether each heavy read ran. A plain `sync status` skips them (the fields keep their types: arrays stay+ * empty, `terminal_failures` reads `unknown`); `not_read` carries the `--detail` command that runs them. An agent never+ * reads an empty skipped field as "none".+ */+ checkpoint_blockers_read: SyncStatusRead;+ cursors_read: SyncStatusRead;+ terminal_failures_read: SyncStatusRead;}+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', 'status_unknown',+ 'needs_human', 'head_blocked', 'recovery_blocked'] 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). */+export const SYNC_STATUS_PROBE_MS = 2_000;export type SyncTerminalSummary = { status: 'unknown'; reason: string } | {status: 'ok'; window_days: number; active_blockers: Array<{ kind: 'recovery' | 'checkpoint'; request_id: string; slug?: string; category: string }>;@@ -180,7 +207,13 @@ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHoretry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record, auto) };}-export async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {+/**+ * `detail` (default true for library callers; the CLI's plain `sync status` passes false) runs the heavy reads: the+ * terminal-failure summary, the checkpoint blocker list and the live-cursor join. Without it each is skipped with its+ * `<field>_read` sibling, and the bounded oldest-blocker and recovery probes still run.+ */+export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts: { detail?: boolean } = {}): Promise<SyncStatus> {+ const detail = opts.detail !== false;const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');@@ -243,14 +276,72 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro: 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;- const blockers = await checkpointBlockers(engine, header);+ const [oldest, recovery] = await Promise.all([oldestBlocker(engine, sourceId), recoveryProbe(engine, sourceId)]);+ const notRead = (field: string): { status: 'not_read'; fix: Action } => ({ status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--detail', '--json'], consent: [], actor: 'agent',+ requires_exclusive: false, why: `This status skipped the ${field} read (a heavy read); --detail runs it. Read-only.` } });+ const blockers = detail ? await checkpointBlockers(engine, header) : { checkpoint_blockers: [] };// #6650: a receipt still holding a recovery record holds its root, so a source with nothing else to do names it as `next`.- const { recovery_next, ...terminal } = await terminalSummary(engine, sourceId, blockers.checkpoint_blockers);+ const { 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 [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0 });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: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),- terminal_failures: terminal, next: next ?? recovery_next ?? null };+ resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],+ terminal_failures: terminal, next: next ?? recovery_next ?? (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') };+}++/** #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] {+ 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'];+ 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.recovery.status !== 'ok') return ['resumable', 'status_unknown'];+ return ['synced', s.holds ? 'held_by_design' : 'nothing_pending'];+}++/** #6712 PR 2: the source's oldest unfinished request, read through the drain's own bounded head probe. */+async function oldestBlocker(engine: BrainEngine, sourceId: string): Promise<SyncStatus['oldest_blocker']> {+ const head = engineStallProbe(engine, sourceId).head!;+ try {+ const row = await Promise.race([head(), new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`no answer within ${SYNC_STATUS_PROBE_MS} ms`)), SYNC_STATUS_PROBE_MS + 1_000).unref?.())]);+ if (!row) return { status: 'ok', request: null };+ return { status: 'ok', request: { request_id: row.request_id ?? '', state: row.head_state, phase: row.claim?.phase ?? null, step: row.claim?.step ?? null, lapsed: row.claim?.lapsed === true,+ blocked_by: row.blocked_by ? { predicate: row.blocked_by.predicate, state: row.blocked_by.state, intervention: row.blocked_by.intervention } : null } };+ } catch (error) {+ return { status: 'unknown', reason: error instanceof Error ? error.message : String(error) };+ }+}++/** #6712 PR 2: the source's requests holding a publication recovery record, bounded; it needs no cursor. */+async function recoveryProbe(engine: BrainEngine, sourceId: string): Promise<SyncStatus['recovery']> {+ try {+ const rows = await engine.executeRaw<{ n: number | string; request_id: string | null; slug: string | null; blocked: boolean | null }>(+ `SELECT count(*) AS n, (array_agg(request_id::text ORDER BY sequence))[1] AS request_id, (array_agg(slug ORDER BY sequence))[1] AS slug,+ (array_agg(blocked_reason IN ('unexpected_staging_bytes','unexpected_file_bytes') ORDER BY sequence))[1] AS blocked+ FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL`, [sourceId], { timeoutMs: SYNC_STATUS_PROBE_MS, signal: AbortSignal.timeout(SYNC_STATUS_PROBE_MS + 500) });+ const row = rows[0];+ const count = Number(row?.n ?? 0);+ return { status: 'ok', count, first: count && row?.request_id ? { request_id: row.request_id, slug: row.slug ?? '', blocked: row.blocked === true } : null };+ } catch (error) {+ return { status: 'unknown', reason: error instanceof Error ? error.message : String(error) };+ }+}++/** The recovery record's next step, as the terminal-failure summary names it (`classifyTerminal`'s recovery verdict). */+function recoveryAction(sourceId: string, first: { request_id: string; slug: string; blocked: boolean }): Action {+ return classifyTerminal({ request_id: first.request_id, source_id: sourceId, slug: first.slug, operation: 'submit_job', state: 'running', error_code: null, recovery: true,+ blocked_reason: first.blocked ? 'unexpected_file_bytes' : null, compacted: false })!.action;}/**diff --git a/test/sync-status-checkpoint-blockers-shape.test.ts b/test/sync-status-checkpoint-blockers-shape.test.tsindex 28c4f1e8c5..5e503d5705 100644--- a/test/sync-status-checkpoint-blockers-shape.test.ts+++ b/test/sync-status-checkpoint-blockers-shape.test.ts@@ -10,6 +10,9 @@* (that receipt, marked `recovery`). `cursors` stays an array in each.* Fails when: the field is left out for an absent, unfinished or finished cursor (master before this change* omitted it in all three).+ * #6712 PR 2 (L5): the blocker list is a heavy read a plain status skips; the array stays (empty) and+ * `checkpoint_blockers_read` says `not_read` with the --detail command, which lists the receipt. The fourth test pinned+ * the list on a plain status; it now asserts both reads.* PGLite in-memory; no production seam.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';@@ -58,11 +61,11 @@ beforeEach(async () => {});/** The JSON document `gbrain sync status --source <id> --json` prints. */-async function statusJson(): Promise<Record<string, unknown>> {+async function statusJson(...extra: string[]): Promise<Record<string, unknown>> {const lines: string[] = [];const log = console.log;console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };- try { await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, () => runSyncStatus(engine, ['--source', SOURCE, '--json'])); } finally { console.log = log; }+ try { await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, () => runSyncStatus(engine, ['--source', SOURCE, '--json', ...extra])); } finally { console.log = log; }return JSON.parse(lines.join('\n')) as Record<string, unknown>;}async function cursor(header: Record<string, unknown>): Promise<string> {@@ -110,9 +113,13 @@ describe('sync status --json checkpoint_blockers is always an array', () => {await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`, [`fp-${runId}`, JSON.stringify([{runId, sourceId: SOURCE, incarnation, index: 3, total: 3, target: 'a'.repeat(40), binding: { worktree_id: worktreeId },pending: { requestId: randomUUID(), intent: { kind: 'managed_sync_checkpoint' } } }])]);- const status = await statusJson();+ const plain = await statusJson();+ expect(plain.checkpoint_blockers).toEqual([]);+ expect(plain.checkpoint_blockers_read).toMatchObject({ status: 'not_read', fix: { next: 'run', argv: ['gbrain', 'sync', 'status', '--source', SOURCE, '--detail', '--json'] } });+ const status = await statusJson('--detail');expect(status.cursor).toMatchObject({ index: 3, total: 3, done: false });expect(status.checkpoint_blockers).toEqual([expect.objectContaining({ request_id: blocker, slug: 'notes/two', recovery: true, knock_on: false })]);+ expect(status.checkpoint_blockers_read).toEqual({ status: 'read' });expect(Array.isArray(status.cursors)).toBe(true);});});diff --git a/test/sync-status-fast-l5.test.ts b/test/sync-status-fast-l5.test.tsnew file mode 100644index 0000000000..4ef959f1cd--- /dev/null+++ b/test/sync-status-fast-l5.test.ts@@ -0,0 +1,96 @@+/**+ * #6712 PR 2 (L5): a plain `gbrain sync status` skips its heavy reads but never reads as an all-clear (DX F1).+ *+ * Protects: every field keeps its type when skipped (arrays stay arrays, `terminal_failures` reads `unknown`) and its+ * `<field>_read` sibling says `not_read` with the --detail command; `state` / `reason` are in the outcome vocabulary;+ * the bounded oldest-blocker and recovery probes run without any cursor, so a source whose only problem is a recovery+ * record (or a queued write) is not `synced` and `next` names the recovery step; a probe that does not answer makes the+ * state `resumable` / `status_unknown`, never `synced`; --detail reads everything. One text headline per state.+ * Fails on the base: no `state`, `reason`, `oldest_blocker`, `recovery` or `*_read` fields.+ * PGLite in-memory.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { readSyncStatus, SYNC_STATUS_REASONS, type SyncStatus } from '../src/core/persistence/sync-status.ts';+import { syncStatusHeadline } from '../src/commands/sync/operator.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const SOURCE = 'fast-src';+let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [SOURCE]);+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await engine.executeRaw('DELETE FROM persistence_requests'); });++async function seed(o: { state: string; recovery?: unknown; blocked?: string | null }) {+ const requestId = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,+ state,error_code,error_message,recovery,blocked_reason,intent,completed_at,updated_at,admitter_version)+ VALUES('local_cli','fixture',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),'notes/held',$3,'{}'::jsonb,0,0,$4,NULL,NULL,$5::text::jsonb,$6,'{"content":"x"}'::jsonb,+ now()-interval '1 hour',now()-interval '1 hour','0.60.256.0')`,+ [requestId, SOURCE, randomUUID(), o.state, o.recovery === undefined ? null : JSON.stringify(o.recovery), o.blocked ?? null]);+ return requestId;+}+const RECOVERY = { version: 1, path: '/nonexistent/x.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' };++describe('plain sync status', () => {+ test('a clean source: synced/nothing_pending, skipped fields keep their types and say not_read', async () => {+ const status = await readSyncStatus(engine, SOURCE, { detail: false });+ expect(status).toMatchObject({ state: 'synced', reason: 'nothing_pending', oldest_blocker: { status: 'ok', request: null }, recovery: { status: 'ok', count: 0, first: null } });+ expect(status.checkpoint_blockers).toEqual([]);+ expect(status.cursors).toEqual([]);+ expect(status.terminal_failures).toMatchObject({ status: 'unknown' });+ for (const read of [status.checkpoint_blockers_read, status.cursors_read, status.terminal_failures_read]) {+ expect(read).toMatchObject({ status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', SOURCE, '--detail', '--json'] } });+ }+ expect(SYNC_STATUS_REASONS).toContain(status.reason);+ expect(status.next).toBeNull();+ });++ test('a recovery record with no cursor is not an all-clear: resumable/recovery_pending and next is the recovery step', async () => {+ const held = await seed({ state: 'committed', recovery: RECOVERY });+ const status = await readSyncStatus(engine, SOURCE, { detail: false });+ expect(status.cursor).toBeNull();+ expect(status).toMatchObject({ state: 'resumable', reason: 'recovery_pending', recovery: { status: 'ok', count: 1, first: { request_id: held, blocked: false } } });+ expect(status.next?.argv).toEqual(['gbrain', 'sync', '--source', SOURCE, '--no-pull', '--json']);+ const detailed = await readSyncStatus(engine, SOURCE);+ expect(detailed.next?.argv).toEqual(status.next?.argv);+ });++ test('a recovery record that found changed bytes blocks the source', async () => {+ await seed({ state: 'committed', recovery: RECOVERY, blocked: 'unexpected_file_bytes' });+ expect(await readSyncStatus(engine, SOURCE, { detail: false })).toMatchObject({ state: 'blocked', reason: 'recovery_blocked' });+ });++ test('a probe that does not answer makes the state unknown, never synced', async () => {+ const failing = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return (sql: string, ...rest: unknown[]) => /recovery IS NOT NULL/.test(sql) && /count\(\*\)/.test(sql)+ ? Promise.reject(Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }))+ : (target.executeRaw as (...a: unknown[]) => unknown).call(target, sql, ...rest);+ return Reflect.get(target, prop, receiver);+ } }) as unknown as BrainEngine;+ const status = await readSyncStatus(failing, SOURCE, { detail: false });+ expect(status).toMatchObject({ state: 'resumable', reason: 'status_unknown', recovery: { status: 'unknown' } });+ expect(status.next?.argv).toEqual(['gbrain', 'sync', 'status', '--source', SOURCE, '--json']);+ });++ test('--detail reads everything and marks it read', async () => {+ const status = await readSyncStatus(engine, SOURCE, { detail: true });+ expect(status.terminal_failures).toMatchObject({ status: 'ok' });+ for (const read of [status.checkpoint_blockers_read, status.cursors_read, status.terminal_failures_read]) expect(read).toEqual({ status: 'read' });+ });+});++describe('one headline per state', () => {+ const base = { source_id: SOURCE, cursor: null, run_id: null, holds: [], live_job_id: null } as unknown as Pick<SyncStatus, 'source_id' | 'state' | 'reason' | 'cursor' | 'run_id' | 'holds' | 'live_job_id'>;+ test('every reason has a headline that names the state', () => {+ for (const reason of SYNC_STATUS_REASONS) {+ const line = syncStatusHeadline({ ...base, reason, state: 'synced' });+ expect(line.startsWith(`Source ${SOURCE}`)).toBe(true);+ expect(line).toMatch(/is synced|is resumable|is blocked|state unknown/);+ }+ });+});diff --git a/test/sync-status-terminal-6650.test.ts b/test/sync-status-terminal-6650.test.tsindex 2817f106e6..5cf79cd445 100644--- a/test/sync-status-terminal-6650.test.ts+++ b/test/sync-status-terminal-6650.test.ts@@ -48,7 +48,8 @@ async function human(sourceId: string): Promise<string> {const lines: string[] = [];const log = console.log;console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };- try { await withEnv({ GBRAIN_SOURCE: undefined }, () => runSyncStatus(engine, ['--source', sourceId])); } finally { console.log = log; }+ // #6712 PR 2 (L5): the terminal summary is a heavy read a plain status skips; these assertions read it with --detail.+ try { await withEnv({ GBRAIN_SOURCE: undefined }, () => runSyncStatus(engine, ['--source', sourceId, '--detail'])); } finally { console.log = log; }return lines.join('\n');}