Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 2 (L5): review fixes — status reports an unfinished write as request_pending, the tail keeps one deadline and reports a failed read, sync --all surfaces the tail; convergence harness reads --detail and checks plain status skips
garrytan176329dcd6d9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 255ed13d39..e0d63a9cec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,9 +18,9 @@ identifiers and attribution are available in the pre-removal Git revision|---|---|---|| a managed sync's checkpoint commits, then link extraction runs for minutes | the drain lease and the governed pass stayed held through the tail | the run returns `synced` at the commit; the tail runs after the lease is released, bounded, and a second sync can take the lease at once || the process dies between the checkpoint commit and the tail | statistics and links for that run were never redone | the checkpoint recorded the tail as owed; the next sync of the source runs it |-| the tail fails, is cut short or the deadline left no time | silent | the run stays `synced` with one `[gbrain notice sync_tail_degraded]` and its fix (`gbrain extract --stale --source <id>`, or doctor for statistics) |+| the tail fails, is cut short or the deadline left no time | silent | the run stays `synced` with one `[gbrain notice sync_tail_degraded]` and its fix (`gbrain extract --stale --source <id>`, or doctor for statistics); `sync --all` prints it per source and puts `tail` and `notices` in each source's JSON entry || a pass admits nothing with no unfinished request | `drain_stalled` / `no_admission`, a pooler warning, and a delegated run's one-time fallback | `drain_stalled` / `no_progress` with the same step and statement; `no_admission` is a retired reason |-| `gbrain sync status` on a large brain | every heavy read on every call | a plain status skips the terminal summary, blocker list and cursor join (`*_read: not_read`, fix `--detail`); `state`, `reason` and bounded oldest-blocker / recovery probes always run; under 30 ms on a 61k-request fixture |+| `gbrain sync status` on a large brain | every heavy read on every call | a plain status skips the terminal summary, blocker list and cursor join (`*_read: not_read`, fix `--detail`); `state`, `reason` and bounded oldest-blocker / recovery probes always run (an unfinished write is `resumable` / `request_pending`, never synced); under 30 ms on a 61k-request fixture || a status whose probe timed out | could read as nothing pending | `state: resumable`, `reason: status_unknown`, never `synced` || a hold, `last_error`, a receipt, `managedWrite` or doctor `sync_failures` | internal codes only | `public_category` (drift, conflict, content_refused, file_missing, permission, storage, config, superseded, transient, defect) beside the unchanged `category` |diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 27e4d81469..5a0c839b10 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -142,6 +142,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'statecase '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 'request_pending': return `Source ${status.source_id} is resumable: a write request is still unfinished; the next sync drains it.`;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.`;diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 0e55fe8d96..7a52ef10f4 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -40,6 +40,7 @@ import { runSyncTrigger } from './trigger.ts';import { drainJsonFields, formatDrainSummary, syncOutcome } from '../../core/persistence/sync-drain.ts';import { readManagedMode } from '../../core/persistence/ownership.ts';import { writeJsonDocument } from '../../core/cli-force-exit.ts';+import { cliRenderContext, renderNotice } from '../../core/agent-output.ts';/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */const emitJson = (text: string): void => { void writeJsonDocument(text); };@@ -62,13 +63,23 @@ type PerSourceResult = {*/async function syncCapacityNotices(engine: BrainEngine, json: boolean, result?: SyncResult): Promise<{ notices?: unknown[] }> {const { capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');- const { cliRenderContext, renderNotice } = await import('../../core/agent-output.ts');// #6712 PR 2 (L5): a degraded post-checkpoint tail rides the same notices.const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...await capacityNotices(engine).catch(() => [])].map(notice => renderNotice(notice, cliRenderContext()));if (!json) for (const notice of notices) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);return notices.length ? { notices } : {};}+/** #6712 PR 2 (L5): one source's post-checkpoint tail in a `sync --all` receipt: its report and its rendered degraded notice. */+function syncTailJsonFields(result: SyncResult): { tail?: Omit<NonNullable<SyncResult['tail']>, 'notice'>; notices?: unknown[] } {+ if (!result.tail) return {};+ const { notice, ...tail } = result.tail;+ return { tail, ...(notice ? { notices: [renderNotice(notice, cliRenderContext())] } : {}) };+}++function printTailNotice(result: SyncResult): void {+ if (result.tail?.notice) process.stderr.write(`[gbrain notice ${result.tail.notice.code}] ${result.tail.notice.why}\n`);+}+export async function runSyncInner(engine: BrainEngine, args: string[]) {// v0.40 Federated Sync v2: `gbrain sync trigger` subcommand// Routes to runSyncTrigger which queues a 'sync' minion job with@@ -660,6 +671,7 @@ export async function dispatchSyncAll(input: {writeHuman(` ${syncOutcome(r.value.result) === 'blocked' ? '✗' : '✓'} ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);if (syncOutcome(r.value.result) === 'blocked') printSyncResult(r.value.result, humanSink);else printHoldNotes(r.value.result, writeHuman);+ printTailNotice(r.value.result);perSourceResults.push({sourceId: src.id,sourceName: src.name,@@ -683,6 +695,7 @@ export async function dispatchSyncAll(input: {try {const result = await runOne(src);printSyncResult(result, humanSink);+ printTailNotice(result);perSourceResults.push({sourceId: src.id,sourceName: src.name,@@ -735,6 +748,7 @@ function emitSyncAllEnvelope(input: {...(r.result.reason ? { reason: r.result.reason } : {}),...(r.result.managedWrite ? { managed_write: r.result.managedWrite } : {}),...drainJsonFields(r.result, resumeCommand, r.sourceId),+ ...syncTailJsonFields(r.result),added: r.result.added,modified: r.result.modified,deleted: r.result.deleted,@@ -946,7 +960,8 @@ async function runSingleSourceSync(const capacity = await syncCapacityNotices(engine, jsonOut, result);if (jsonOut) {emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),- ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId), ...capacity }));+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId),+ ...(result.tail ? { tail: syncTailJsonFields(result).tail } : {}), ...capacity }));}return;}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 37a7dc09a5..35a5f5ee35 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -306,7 +306,7 @@ export interface StallProbe {*/fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'>; claim?: DrainClaim | null } | null>;/** #6278: the source's head while a pass runs (its oldest running request, else its oldest queued one); null when nothing is unfinished. Bounded; may reject. */- head?(): Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null; claimable_here?: boolean | null; blocked_by?: HeadBlocker | null; consumer?: string } | null>;+ head?(): Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null; write_request_id?: string | null; claimable_here?: boolean | null; blocked_by?: HeadBlocker | null; consumer?: string } | null>;/** #6317: the head owner's heartbeat row on this host, or null (no row: an older owner, PGLite, the table absent, or another host). Never rejects. */owner?(claim: DrainClaim): Promise<DrainOwnerRow | null>;/** #6317: whether a consumer here could reclaim a lapsed head: this process's own, or a live full row on this host. Never rejects. */@@ -750,18 +750,19 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallPreturn (await listHostConsumers(engine, localHostId()).catch(() => [])).some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');},...(sourceId ? { async head() {- const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null; head_request_id: string | null }>(- `SELECT h.state AS head_state, h.id::text AS head_request_id, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,+ const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null; head_request_id: string | null;+ head_write_request_id: string | null }>(+ `SELECT h.state AS head_state, h.id::text AS head_request_id, h.request_id::text AS head_write_request_id, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,(h.claim_expires_at IS NOT NULL AND h.claim_expires_at < now()) AS head_lapsed, h.intent->>'kind' AS head_kindFROM persistence_source_bindings bJOIN sources s ON s.id = b.source_id AND s.incarnation = b.source_incarnation- JOIN LATERAL (SELECT e.id, e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests e+ JOIN LATERAL (SELECT e.id, e.request_id, e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests eWHERE e.worktree_id = b.worktree_id AND e.state IN ('queued','running','recovering') ORDER BY (e.state <> 'running'), e.sequence LIMIT 1) h ON trueWHERE b.source_id = $1`, [sourceId], { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) });if (!row) return null;const { localHostId } = await import('./identity.ts');const bound = { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) };- return { head_state: row.head_state, request_id: row.head_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))),+ return { head_state: row.head_state, request_id: row.head_request_id, write_request_id: row.head_write_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))),...await headClaimability(engine, { id: row.head_request_id, state: row.head_state }, localHostId(), bound), consumer: await describeHostConsumer(engine, { signal: bound.signal }) };} } : {}),};diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex ed7b5da8cd..aa40d6db7c 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1395,7 +1395,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slconst remote = currentSubmissionAuthority()?.kind === 'remote_generic';return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null }, remote },signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice))- .then(result => withSyncTail(engine, sourceId, result, { signal: opts.signal, deadlineAtMs: opts.deadlineAtMs }))+ // #6712 PR 2: an owner slice is time-bounded, so its tail gets the slice's budget (pages it leaves stay stale, with the notice).+ .then(result => withSyncTail(engine, sourceId, result, { signal: opts.signal, deadlineAtMs: opts.deadlineAtMs, ...(slice ? { budgetMs: slice.maxMs } : {}) })).catch(async error => {if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(sourceId)) throw error;return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote });diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex ede527dfe1..d2ea43eeae 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -126,8 +126,8 @@ 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', 'status_unknown',- 'needs_human', 'head_blocked', 'recovery_blocked'] as const;+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;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). */@@ -288,7 +288,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optscursor: 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, next: next ?? recovery_next ?? (stateReason === 'status_unknown' ? { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ terminal_failures: terminal, next: next ?? recovery_next ?? (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'),@@ -306,6 +308,7 @@ function statusState(s: { human: boolean; oldest: SyncStatus['oldest_blocker'];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.oldest.request) return ['resumable', 'request_pending'];if (s.oldest.status !== 'ok' || s.recovery.status !== 'ok') return ['resumable', 'status_unknown'];return ['synced', s.holds ? 'held_by_design' : 'nothing_pending'];}@@ -316,7 +319,7 @@ async function oldestBlocker(engine: BrainEngine, sourceId: string): Promise<Syntry {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,+ return { status: 'ok', request: { request_id: row.write_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) };@@ -327,9 +330,9 @@ async function oldestBlocker(engine: BrainEngine, sourceId: string): Promise<Synasync 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) });+ `SELECT (SELECT count(*) FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL) AS n, f.request_id::text AS request_id, f.slug,+ f.blocked_reason IN ('unexpected_staging_bytes','unexpected_file_bytes') AS blocked+ FROM (SELECT 1) one LEFT JOIN LATERAL (SELECT request_id, slug, blocked_reason FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL ORDER BY sequence LIMIT 1) f ON true`, [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 };diff --git a/src/core/persistence/sync-tail.ts b/src/core/persistence/sync-tail.tsindex 49cc442242..f6f97361c3 100644--- a/src/core/persistence/sync-tail.ts+++ b/src/core/persistence/sync-tail.ts@@ -41,27 +41,32 @@ export interface SyncTailReport {*/export async function runSyncTail(engine: BrainEngine, sourceId: string, opts: { signal?: AbortSignal; deadlineAtMs?: number; budgetMs?: number } = {}): Promise<SyncTailReport | null> {let owed: TailObligation[] | null;- try { owed = await readSyncTail(engine, sourceId); } catch { return null; }+ try { owed = await readSyncTail(engine, sourceId); } catch (error) {+ const failure = `reading the scheduled step failed: ${error instanceof Error ? error.message : String(error)}`;+ return { status: 'failed', runs: 0, statistics: 'not_needed', notice: tailNotice(sourceId, 'failed', { statistics: 'not_needed', failure }) };+ }if (!owed) return null;- const budgetMs = Math.max(0, Math.min(opts.budgetMs ?? SYNC_TAIL_BUDGET_MS, opts.deadlineAtMs === undefined ? Infinity : opts.deadlineAtMs - Date.now()));+ const deadlineAt = Date.now() + Math.max(0, Math.min(opts.budgetMs ?? SYNC_TAIL_BUDGET_MS, opts.deadlineAtMs === undefined ? Infinity : opts.deadlineAtMs - Date.now()));const changed = owed.reduce((sum, item) => sum + (Number(item.changed) || 0), 0);const extract = owed.some(item => item.extract);- let statistics: SyncTailReport['statistics'] = 'not_needed', links: ManagedLinkExtraction | undefined, failure: string | null = null, linksStarted = 0;+ let statistics: SyncTailReport['statistics'] = 'not_needed', links: ManagedLinkExtraction | undefined, failure: string | null = null, slugs: string[] = [];try {await faultPoint('sync:tail_started', { sourceId });if (changed > 0) statistics = await refreshProjectionStatistics(engine, changed) ? 'refreshed' : 'failed';- if (extract && budgetMs > 0) {- const slugs = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT e->>'slug' AS slug FROM op_checkpoints m, jsonb_array_elements(m.completed_keys) e- WHERE m.op='managed-sync-manifest' AND m.fingerprint=ANY($1::text[]) AND e->>'action'='import' AND e->>'slug' IS NOT NULL`, [owed.map(item => item.run_id)])).map(row => row.slug);- linksStarted = Date.now();- links = await extractManagedStaleLinks(engine, { sourceId, maxPages: SYNC_TAIL_MAX_PAGES, timeBudgetMs: budgetMs, signal: opts.signal, mentions: false, slugs });+ if (extract && deadlineAt > Date.now()) {+ slugs = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT e->>'slug' AS slug FROM op_checkpoints m, jsonb_array_elements(m.completed_keys) e+ WHERE m.op='managed-sync-manifest' AND m.fingerprint=ANY($1::text[]) AND e->>'action'='import' AND e->>'slug' IS NOT NULL LIMIT ${SYNC_TAIL_MAX_PAGES + 1}`,+ [owed.map(item => item.run_id)], { timeoutMs: Math.max(1, deadlineAt - Date.now()) })).map(row => row.slug);+ if (deadlineAt > Date.now()) links = await extractManagedStaleLinks(engine, { sourceId, maxPages: SYNC_TAIL_MAX_PAGES, timeBudgetMs: deadlineAt - Date.now(), signal: opts.signal, mentions: false, slugs });}} catch (error) {failure = error instanceof Error ? error.message : String(error);}const ran = failure === null && (!extract || links !== undefined);if (ran) await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [SYNC_TAIL_OP, sourceId, JSON.stringify(owed)]).catch(() => undefined);- const status: SyncTailReport['status'] = failure !== null ? 'failed' : !ran ? 'deferred' : links && links.remaining > 0 && (Date.now() - linksStarted >= budgetMs || links.pages + links.skipped >= SYNC_TAIL_MAX_PAGES) ? 'truncated' : statistics === 'failed' ? 'degraded' : 'done';+ // Imported pages are re-derived even when a sweep stamped them fresh, so an unvisited one is truncation whatever `remaining` says.+ const truncated = !!links && (links.remaining > 0 || slugs.length > links.pages + links.skipped) && (Date.now() >= deadlineAt || links.pages + links.skipped >= SYNC_TAIL_MAX_PAGES);+ const status: SyncTailReport['status'] = failure !== null ? 'failed' : !ran ? 'deferred' : truncated ? 'truncated' : statistics === 'failed' ? 'degraded' : 'done';return { status, runs: owed.length, statistics, ...(links ? { links } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, links, failure }) }) };}@@ -71,7 +76,7 @@ function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'],verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } };if (status === 'truncated') {return { code: 'sync_tail_degraded', kind: 'degraded', fix: extract,- why: `The sync of source ${sourceId} is synced, but link extraction stopped at its budget with ${d.links!.remaining} page(s) still stale; their links and backlinks are missing until they are extracted.` };+ why: `The sync of source ${sourceId} is synced, but link extraction stopped at its budget with ${d.links!.remaining || 'some'} imported page(s) not yet derived; their links and backlinks are missing until they are extracted.` };}if (status === 'degraded') {return { code: 'sync_tail_degraded', kind: 'degraded',@@ -88,7 +93,7 @@ function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'],* links ran). A dry run, a run that never held the lease (a follower) and a call still inside a lease (its holder runs* the tail) run none.*/-export async function withSyncTail(engine: BrainEngine, sourceId: string, result: SyncResult, opts: { signal?: AbortSignal; deadlineAtMs?: number } = {}): Promise<SyncResult> {+export async function withSyncTail(engine: BrainEngine, sourceId: string, result: SyncResult, opts: { signal?: AbortSignal; deadlineAtMs?: number; budgetMs?: number } = {}): Promise<SyncResult> {if (result.status === 'dry_run' || result.leaseHeld || currentDrainLease(sourceId)) return result;const tail = await runSyncTail(engine, sourceId, opts);if (!tail) return result;diff --git a/test/sync-convergence.serial.test.ts b/test/sync-convergence.serial.test.tsindex 7d36408cb2..5b5f48b3ae 100644--- a/test/sync-convergence.serial.test.ts+++ b/test/sync-convergence.serial.test.ts@@ -175,9 +175,18 @@ interface StatusExpectation { holds?: Array<{ code: string; path: string }>; nee/*** What a converged source's status must say. Field-present assertions first: a renderer that drops a field fails* here, not in an agent's loop. `checkpoint_blockers` and `cursors` are arrays on every status (#6712 PR 0 made- * `checkpoint_blockers` always present). TODO(PR 2 of #6712): read `sync status --json --detail` once it exists,- * with the heavy reads it moves behind the flag.+ * `checkpoint_blockers` always present). The harness reads `sync status --json --detail`: since #6712 PR 2 the+ * terminal summary, blocker list and cursor join run only behind the flag.*/+/** The default (no `--detail`) status after the chaos: every skipped heavy read says so and names the `--detail` command (#6712 PR 2, DX F1). */+function fastStatusProblems(status: Record<string, unknown> | null): string[] {+ if (!status) return ['sync status --json printed no JSON document'];+ return (['checkpoint_blockers_read', 'cursors_read', 'terminal_failures_read'] as const).flatMap(field => {+ const read = status[field] as { status?: string; fix?: { argv?: string[] } } | undefined;+ return read?.status === 'not_read' && read.fix?.argv?.includes('--detail') ? [] : [`sync status --json: ${field} is ${JSON.stringify(read)}, expected not_read with a --detail fix`];+ });+}+function statusProblems(status: Record<string, unknown> | null, expected: StatusExpectation = {}): string[] {if (!status) return ['sync status --json printed no JSON document'];const out = STATUS_FIELDS.filter(field => !(field in status)).map(field => `sync status --json: field ${field} missing`);@@ -570,9 +579,9 @@ class Brain {const head = this.git('rev-parse', 'HEAD');return source.last_commit === head ? [] : [`sources.last_commit ${source.last_commit} is not HEAD ${head}`];}- async status(): Promise<Record<string, unknown> | null> {- const r = await this.spawnCli(['sync', 'status', '--source', SOURCE, '--json']).result;- this.keepLog('status.json', `${r.out}\n${r.err}`);+ async status(detail = true): Promise<Record<string, unknown> | null> {+ const r = await this.spawnCli(['sync', 'status', '--source', SOURCE, '--json', ...(detail ? ['--detail'] : [])]).result;+ this.keepLog(detail ? 'status.json' : 'status-fast.json', `${r.out}\n${r.err}`);return lastJson(r.out);}recoveryProblems(): string[] {@@ -748,6 +757,7 @@ function oracleTests(b: Brain, end: () => EndState): void {b.verdict(await b.ledgerProblems());});test(as('wedge', 'sync status --json reports the converged state with every field present'), async () => b.verdict(statusProblems(await b.status(), end().status)));+ test(as('wedge', 'plain sync status --json names every heavy read it skipped instead of reading as all-clear'), async () => b.verdict(fastStatusProblems(await b.status(false))));if (end().bigPage !== false) test(as('lost_write', 'the large page keeps every fence fact exactly once and loses no timeline entry'), async () => {const { problems, timelineDuplicates, timelineStrays } = await b.childRowProblems();b.note(`large page timeline (measured, not asserted): ${timelineDuplicates} duplicate rows, ${timelineStrays} rows not in the file`);@@ -781,6 +791,13 @@ describe('convergence harness calibration (#6650 L0, #6712 PR 0)', () => {expect(statusProblems(converged())).toEqual([]);expect(statusProblems({ ...converged(), cursor: null, run_id: null })).toEqual([]);});+ test('the fast-status oracle accepts named skipped reads and fails a skipped read that looks read', () => {+ const notRead = { status: 'not_read', fix: { argv: ['gbrain', 'sync', 'status', '--source', SOURCE, '--detail', '--json'] } };+ const fast = { checkpoint_blockers_read: notRead, cursors_read: notRead, terminal_failures_read: notRead };+ expect(fastStatusProblems(fast)).toEqual([]);+ expect(fastStatusProblems({ ...fast, terminal_failures_read: { status: 'read' } })).toEqual(['sync status --json: terminal_failures_read is {"status":"read"}, expected not_read with a --detail fix']);+ expect(fastStatusProblems({ ...fast, cursors_read: undefined })).toHaveLength(1);+ });// Forced probe: every field the oracle requires fails it when missing, so a renderer that drops one cannot pass.test('the status oracle fails when any required field is missing or not an array', () => {for (const field of STATUS_FIELDS) {diff --git a/test/sync-drain-finish-tail.test.ts b/test/sync-drain-finish-tail.test.tsindex e4b6889000..9874f5d7db 100644--- a/test/sync-drain-finish-tail.test.ts+++ b/test/sync-drain-finish-tail.test.ts@@ -149,4 +149,12 @@ test('a --no-extract run owes statistics only, and a run past its deadline deferexpect(await readSyncTail(engine, id)).not.toBeNull();expect((await runSyncTail(engine, id))?.status).toBe('done');expect(await stale(id)).toBe(0);+ // An obligation that cannot be read is a failed tail with its notice, never a silent synced receipt.+ const unreadable = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return (sql: string, ...rest: unknown[]) => /managed-sync-tail|op=\$1 AND fingerprint=\$2/.test(sql) && /^SELECT completed_keys/.test(sql)+ ? Promise.reject(new Error('connection terminated'))+ : (target.executeRaw as (...a: unknown[]) => unknown).call(target, sql, ...rest);+ return Reflect.get(target, prop, receiver);+ } }) as unknown as BrainEngine;+ expect(await runSyncTail(unreadable, id)).toMatchObject({ status: 'failed', runs: 0, notice: { code: 'sync_tail_degraded', kind: 'degraded' } });}), 120_000);diff --git a/test/sync-status-fast-l5.test.ts b/test/sync-status-fast-l5.test.tsindex 4ef959f1cd..2d44559b9e 100644--- a/test/sync-status-fast-l5.test.ts+++ b/test/sync-status-fast-l5.test.ts@@ -4,7 +4,7 @@* 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+ * record (or a queued write) is not `synced` and `next` names the recovery step (or the sync that drains the write); 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.@@ -23,17 +23,27 @@ beforeAll(async () => {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'); });+beforeEach(async () => {+ await engine.executeRaw('DELETE FROM persistence_requests');+ await engine.executeRaw('DELETE FROM persistence_source_bindings');+});-async function seed(o: { state: string; recovery?: unknown; blocked?: string | null }) {+async function seed(o: { state: string; recovery?: unknown; blocked?: string | null; worktreeId?: string }) {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)+ state,error_code,error_message,recovery,blocked_reason,intent,completed_at,updated_at,admitter_version,worktree_id)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]);+ CASE WHEN $4 IN ('queued','running') THEN NULL ELSE now()-interval '1 hour' END,now()-interval '1 hour','0.60.256.0',$7::uuid)`,+ [requestId, SOURCE, randomUUID(), o.state, o.recovery === undefined ? null : JSON.stringify(o.recovery), o.blocked ?? null, o.worktreeId ?? null]);return requestId;}+/** A worktree bound to the source, the way every managed write of a source is queued. */+async function bindWorktree(): Promise<string> {+ const worktreeId = randomUUID();+ await engine.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id) VALUES($1::uuid,$2::uuid)', [worktreeId, randomUUID()]);+ await engine.executeRaw('INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id) SELECT id,incarnation,$2::uuid FROM sources WHERE id=$1', [SOURCE, worktreeId]);+ return worktreeId;+}const RECOVERY = { version: 1, path: '/nonexistent/x.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' };describe('plain sync status', () => {@@ -65,6 +75,15 @@ describe('plain sync status', () => {expect(await readSyncStatus(engine, SOURCE, { detail: false })).toMatchObject({ state: 'blocked', reason: 'recovery_blocked' });});+ test('an unfinished write with no cursor and no recovery record is not an all-clear: resumable/request_pending and next drains it', async () => {+ const queued = await seed({ state: 'queued', worktreeId: await bindWorktree() });+ const status = await readSyncStatus(engine, SOURCE, { detail: false });+ expect(status.cursor).toBeNull();+ expect(status).toMatchObject({ state: 'resumable', reason: 'request_pending', oldest_blocker: { status: 'ok', request: { request_id: queued, state: 'queued' } }, recovery: { status: 'ok', count: 0 } });+ expect(status.next?.argv).toEqual(['gbrain', 'sync', ...status.resume_argv]);+ expect(status.next?.why).toContain(queued);+ });+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)