Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane R): cursor readers read the pass row

garrytan39a306f3ad75
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index b0b77b39c3..2cab76f690 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -7,6 +7,7 @@ import { readFenceAutoRepair, type FenceAutoRepair } from '../../../core/fence-r
import { summarizeFenceCensus } from '../../../core/fence-repair/census.ts';
import { agentFix } from '../check-fix.ts';
import { isContentRefusal } from '../../../core/import-screen.ts';
+import { SETTLE_MISMATCH_STREAK } from '../../../core/persistence/sync-pass-row.ts';
const SAMPLE_PATHS = 5;
@@ -23,9 +24,21 @@ const SAMPLE_PATHS = 5;
* Unsupported-image holds (#5493) are listed but never escalate. With fence
* holds, details carry `fences` and `auto_repair` (whether the maintenance run
* repairs them by itself), which the post-upgrade banner reads.
+ * #6712 PR 4b (design v3.2 §3.7): a non-company source whose passes keep
+ * stopping (`passHealth`: the newest ended `blocked`, a `not_converged`
+ * streak, or a `settle_mismatch` streak that becomes a hold) is listed under
+ * `details.passes` with its reason, stop reason, the time it began and the
+ * paths whose settle keeps mismatching, and warns even with no file held.
*/
export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
try {
+ const { readPassReadings, passStuck, passStuckSince } = await import('../../../core/persistence/sync-pass-readers.ts');
+ const passes = (await readPassReadings(engine, { sourceIds, head: false })).filter(reading => passStuck(reading.health)).map(({ source_id, row, health }) => ({
+ source_id, reason: health.reason!, stop_reason: row.value.telemetry.stop_reason, since: passStuckSince(row), not_converged_streak: row.value.obligations.not_converged_streak ?? 0,
+ mismatch: Object.entries(row.value.obligations.mismatch ?? {}).filter(([, entry]) => entry.streak >= SETTLE_MISMATCH_STREAK - 1).map(([path, entry]) => ({ path, streak: entry.streak })).slice(0, SAMPLE_PATHS) }));
+ const passLines = passes.map(pass => `${pass.source_id}: every pass since ${pass.since} stopped ${pass.reason}${pass.stop_reason ? ` (${pass.stop_reason})` : ''}`
+ + (pass.mismatch.length ? `, settle keeps mismatching on ${pass.mismatch.map(entry => entry.path).join(', ')}` : ''));
+ const passNote = passes.length ? ` Managed sync passes that keep stopping: ${passLines.join('; ')}; inspect with ${passes.map(pass => `gbrain sync status --source ${pass.source_id} --json`).join('; ')}.` : '';
const [coverage, policy] = await Promise.all([readHeldCoverage(engine, sourceIds ? { sourceIds } : {}), readSyncHoldPolicy(engine)]);
const listing = new Map((await readGitHoldListing(engine, coverage.map(source => source.source_id), SAMPLE_PATHS)).map(entry => [entry.sourceId, entry.holds]));
const images = await readGitImageHoldCounts(engine, coverage.map(source => source.source_id));
@@ -43,7 +56,11 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
});
const held = sources.reduce((sum, source) => sum + source.held, 0);
const details = { held, source_ids: sources.map(source => source.source_id), sources: sources.map(({ argv: _argv, ...source }) => source), escalate_count: policy.escalateCount,
- ...(fences ? { fences, auto_repair: auto } : {}), docs: 'docs/guides/repair.md#held-files' };
+ ...(fences ? { fences, auto_repair: auto } : {}), ...(passes.length ? { passes } : {}), docs: 'docs/guides/repair.md#held-files' };
+ if (!held && passes.length) return { name: 'git_held_files', status: 'warn', details,
+ message: `No Git source files are held, but managed sync does not converge.${passNote}`,
+ fix: agentFix(['gbrain', 'sync', 'status', '--source', passes[0]!.source_id, '--json'],
+ 'Read-only: the convergence of the source, the reason its passes stop and the next step (a hold to reconcile, a blocked step, or the resume command).', 'git_held_files', { docs: 'docs/guides/repair.md#held-files' }) };
if (!held) return { name: 'git_held_files', status: 'ok', message: 'No Git source files are held.', details };
const escalated = sources.filter(source => source.escalated);
const single = sources.length === 1 ? sources[0]! : undefined;
@@ -60,7 +77,8 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
? 'the write owner (not the files) is the likely cause; inspect it with writer status' : 'a generator or an upgrade is likely writing or reading them wrong; fix the cause'} first. ` : '')
+ 'A page whose newer file is held is read-only for put_page until the file is repaired, so do not retry a refused write. '
+ `Inspect with ${sources.map(source => source.status).join('; ')}; `
- + (sources.some(source => source.fences || source.stalled) ? `then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.` : `preview the fix with ${sources.map(source => source.repair).join('; ')}.`),
+ + (sources.some(source => source.fences || source.stalled) ? `then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.` : `preview the fix with ${sources.map(source => source.repair).join('; ')}.`)
+ + passNote,
fix: single
? agentFix(single.argv, fenceOnly ? `Previews the fence repair of each held file of ${single.source_id} (read-only, no model call): ${single.next}.`
: stalledOnly ? `Shows what the write owner of ${single.source_id} was stuck on (read-only); the held files are fine. ${single.next}.`
diff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.ts
index 2307e3da3b..80bebebcbb 100644
--- a/src/commands/doctor/checks/managed-sync-blocked.ts
+++ b/src/commands/doctor/checks/managed-sync-blocked.ts
@@ -5,6 +5,8 @@
* the other sources look healthy (#6858: one source stopped 21 h while every job reported `completed`). A run blocked
* for less than the threshold warns. Reads the durable cursor and failure rows only; names sources, codes and ages, never
* paths or receipt text.
+ * #6712 PR 4b: a non-company source's passes that keep stopping (`blocked`, a `not_converged` or `settle_mismatch`
+ * streak) count too, aged from when they started stopping (`readBlockedManagedSyncs`).
*/
import type { Check } from '../../doctor.ts';
import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -28,7 +30,7 @@ async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]>
const list = blocked.map(b => `${b.source_id} (${b.code}, blocked ${minutes(b.blocked_since)} min)`).join('; ');
checks.push({ name: 'managed_sync_blocked', status: over.length ? 'fail' : 'warn', readiness_state: 'degraded',
details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },
- message: `${list}: the managed sync run is stopped on a page that did not commit, so the source indexes nothing new until it is cleared`
+ message: `${list}: the managed sync run is stopped on a page that did not commit, or its passes keep stopping without converging, so the source indexes nothing new until it is cleared`
+ `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}. Freshness sync jobs for the source end dead with the run's next step instead of completed.`,
fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],
'Read-only: names the page the run stopped on, its fault class and the next step (a hold to reconcile, a repair to preview, or the resume command).',
diff --git a/src/commands/doctor/checks/managed-sync-movement.ts b/src/commands/doctor/checks/managed-sync-movement.ts
index be081f8ce3..5e047ff5bc 100644
--- a/src/commands/doctor/checks/managed-sync-movement.ts
+++ b/src/commands/doctor/checks/managed-sync-movement.ts
@@ -10,6 +10,10 @@
* with no consumer and no progress for longer than that ceiling: nothing will
* ever drain them, so the check fails and names the resume sync (which runs
* its own consumer) as the safe action. Reads the database only.
+ * #6712 PR 4b (design v3.2 §3.7): a non-company source's pending pass row
+ * counts like a cursor; a pass that keeps stopping (`blocked`, a
+ * `not_converged` or `settle_mismatch` streak) warns as not moving, with
+ * `gbrain sync status` as the read-only fix (it also reads the checkout's HEAD).
*/
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -27,16 +31,24 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>
const parked = pending.filter(m => m.movement_state === 'parked');
const stranded = parked.filter(strandedQueue);
const details = { count: stuck.length, parked: parked.length, stranded: stranded.length, sources: pending.map(m => ({ source_id: m.source_id, movement_state: m.movement_state, data_moving: m.data_moving,
- not_moving_since: m.not_moving_since, last_commit_at: m.last_commit_at, last_progress_at: m.last_progress_at, cursor: m.cursor, head: m.head, live: m.live, admitted: m.admitted,
+ not_moving_since: m.not_moving_since, last_commit_at: m.last_commit_at, last_progress_at: m.last_progress_at, cursor: m.cursor, pass: m.pass, head: m.head, live: m.live, admitted: m.admitted,
ceiling_ms: m.ceiling_ms, writer_status_command: m.writer_status_command })), docs: DOCS };
if (stranded.length) {
const first = stranded[0]!;
checks.push({ name: 'managed_sync_not_moving', status: 'fail', readiness_state: 'degraded', details,
message: `${stranded.map(m => `${m.source_id} (${m.admitted} admitted request(s), no progress since ${m.last_progress_at ?? m.admitted_since})`).join('; ')}: managed sync is parked with a non-empty `
+ `write queue and no consumer for longer than the ${Math.round(first.ceiling_ms / 1000)}s ceiling, so nothing will drain it. Resuming the sync runs its own consumer beside the queue.`,
- fix: agentFix(['gbrain', 'sync', ...(first.cursor?.resume_args ?? ['--source', first.source_id, '--no-pull'])],
+ fix: agentFix(['gbrain', 'sync', ...((first.cursor ?? first.pass)?.resume_args ?? ['--source', first.source_id, '--no-pull'])],
`Resumes ${first.source_id}'s unfinished cursor with its stored options; the run consumes the queued requests itself (one drainer per source) and finishes the frozen manifest.`,
'managed_sync_not_moving', { docs: DOCS }) });
+ } else if (stuck.some(m => m.pass?.stuck)) {
+ const passes = stuck.filter(m => m.pass?.stuck), first = passes[0]!;
+ checks.push({ name: 'managed_sync_not_moving', status: 'warn', readiness_state: 'degraded', details,
+ message: `${passes.map(m => `${m.source_id} (every pass since ${m.pass!.stuck_since} stopped ${m.pass!.stuck}${m.pass!.stop_reason ? `: ${m.pass!.stop_reason}` : ''}, ${m.pass!.remaining} path(s) unsettled)`).join('; ')}: `
+ + 'managed sync does not converge; the source does not reach its checkout\'s HEAD even when pages commit.'
+ + (stuck.length > passes.length ? ` Also not moving: ${stuck.filter(m => !m.pass?.stuck).map(m => `${m.source_id} (since ${m.not_moving_since})`).join('; ')}.` : ''),
+ fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],
+ 'Read-only: the convergence of the source, the reason its passes stop (a hold, a blocked step or a not-converged streak) and the next step.', 'managed_sync_not_moving', { docs: DOCS }) });
} else if (stuck.length) {
const first = stuck[0]!;
checks.push({ name: 'managed_sync_not_moving', status: 'warn', readiness_state: 'degraded', details,
@@ -46,7 +58,7 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>
'Read-only: names the request at the head, its step, what it waits on, the owner process and the next step (`claim.next`) on the running claim.', 'managed_sync_not_moving', { docs: DOCS }) });
} else if (pending.length) {
checks.push({ name: 'managed_sync_not_moving', status: 'ok', severity: 'info', details,
- message: `Managed sync data is moving${parked.length ? `; ${parked.map(m => `${m.source_id} is parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer live; resume: ${m.cursor!.resume_command})`).join('; ')}` : ''}.` });
+ message: `Managed sync data is moving${parked.length ? `; ${parked.map(m => { const work = (m.cursor ?? m.pass)!; return `${m.source_id} is parked at ${work.index}/${work.total} (no sync or consumer live; resume: ${work.resume_command})`; }).join('; ')}` : ''}.` });
} else {
checks.push({ name: 'managed_sync_not_moving', status: 'ok', message: 'No managed sync is pending.', details });
}
diff --git a/src/commands/sources-strategy.ts b/src/commands/sources-strategy.ts
index a3d0a47589..c9ee5ffb5b 100644
--- a/src/commands/sources-strategy.ts
+++ b/src/commands/sources-strategy.ts
@@ -13,6 +13,10 @@
* key under it would make the resumed run and the next full sync disagree
* about which files are pages. The write is updateSourceConfig's single-key
* merge, so every other config key survives. Follows `mirror-readonly`.
+ * #6712 PR 4b (design v3.2 §3.7): a non-company source has no cursor, so it
+ * also refuses while a sync holds the source's drain lease (a pass classifies
+ * under the strategy it pinned) or while a `--full` episode is open (its
+ * selection, strategy included, is what the episode closes over).
*
* Contributed by @rokas-tarasevicius (PR #5955); the surface here is the
* reviewed minimum of that PR.
@@ -29,6 +33,15 @@ export async function unfinishedManagedSyncRuns(engine: BrainEngine, sourceId: s
WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true' AND s.id=$1 ORDER BY c.updated_at`, [sourceId]);
}
+/** Why a strategy change would cut under a running or unfinished pass: a live drain lease, or an open episode (read-only). */
+export async function unfinishedManagedSyncPass(engine: BrainEngine, sourceId: string): Promise<{ lease: string | null; episode: { opened_at: string; full_id: string | null } | null }> {
+ const [{ readDrainHolder }, { readPassRow }] = await Promise.all([import('../core/persistence/sync-lease.ts'), import('../core/persistence/sync-pass-row.ts')]);
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const holder = await readDrainHolder(engine, sourceId);
+ const episode = source ? (await readPassRow(engine, sourceId, source.incarnation))?.value.obligations.episode : undefined;
+ return { lease: holder ? `${holder.kind}${holder.started_at ? ` since ${holder.started_at}` : ''}` : null, episode: episode ? { opened_at: episode.opened_at, full_id: episode.full_id ?? null } : null };
+}
+
export async function runSetStrategy(engine: BrainEngine, args: string[]): Promise<void> {
const [id, strategy] = args;
if (!id || id.startsWith('-') || !strategy) {
@@ -57,6 +70,14 @@ export async function runSetStrategy(engine: BrainEngine, args: string[]): Promi
console.error(` Finish the run first (gbrain sync --source ${id} --no-pull resumes it; gbrain sync status --source ${id} --json shows what holds it), or retire a run nothing can resume (gbrain repair managed-sync-orphans --source ${id}), then set the strategy.`);
process.exit(1);
}
+ const pass = config.strategy !== strategy ? await unfinishedManagedSyncPass(engine, id) : { lease: null, episode: null };
+ if (pass.lease || pass.episode) {
+ console.error(`Error [sync_run_unfinished]: source "${id}" has ${pass.lease ? `a sync running (${pass.lease})` : `an open full re-import (opened ${pass.episode!.opened_at})`}.`);
+ console.error(pass.lease ? ` It classifies the checkout under the current strategy; changing it now would make the running pass and the next one disagree about which files are pages.`
+ : ` It re-imports the source under the selection it was opened with, strategy included; changing the strategy now would leave it unable to close.`);
+ console.error(` ${pass.lease ? 'Wait for the sync to finish' : `Finish it first (gbrain sync --source ${id} --no-pull continues it)`}; gbrain sync status --source ${id} --json shows where it stands. Then set the strategy.`);
+ process.exit(1);
+ }
await engine.updateSourceConfig(id, { strategy });
console.log(`Source "${id}" now syncs with strategy ${strategy}.`);
if (config.strategy !== strategy) {
diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.ts
index 84cf4c690f..29146a3cdf 100644
--- a/src/commands/sources-writer-movement.ts
+++ b/src/commands/sources-writer-movement.ts
@@ -118,7 +118,7 @@ export function movementReport(before: SourceMovement | undefined, after: Source
case 'nothing_pending':
return { source_id: id, state, exit: 0, code: null, why: `${id}: no managed sync is pending${after.holds.count ? ` (${after.holds.count} held file(s) await their repair)` : ''}.`, fix: null, before, after };
case 'moved':
- return { source_id: id, state, exit: 0, code: null, why: `${id}: a page committed at ${after.last_commit_at} inside the ${Math.round(windowMs / 1000)}s window; ${after.cursor ? `${after.cursor.remaining} remaining` : 'the cursor is done'}.`, fix: null, before, after };
+ return { source_id: id, state, exit: 0, code: null, why: `${id}: a page committed at ${after.last_commit_at} inside the ${Math.round(windowMs / 1000)}s window; ${after.cursor ? `${after.cursor.remaining} remaining` : after.pass ? `${after.pass.remaining} path(s) unsettled in the pass` : 'the cursor is done'}.`, fix: null, before, after };
case 'within_allowance':
return { source_id: id, state, exit: 0, code: null, retry_after_ms: windowMs,
why: `${id}: no page committed yet, but the head's step or the cursor advanced inside the window (a multi-wave group commits nothing until its last wave).${head} Check again after one more window.`,
@@ -133,12 +133,17 @@ export function movementReport(before: SourceMovement | undefined, after: Source
fix: renderAction({ argv: route, consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#held-files',
why: kinds.stalled > 0 ? `Read-only: shows the owner the stalled preparations name;${then} once the cause is fixed.` : 'Read-only preview of the repair; it prints the apply command for the user to approve.', verify }, ctx), before, after };
}
- case 'parked':
+ case 'parked': {
+ const work = after.cursor ?? after.pass;
return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',
- why: `${id}: the managed sync cursor is pending at ${after.cursor?.index ?? '?'}/${after.cursor?.total ?? '?'} and nothing live is moving it (no sync run holds the lock; ${after.admitted} admitted request(s), no live consumer on the owner host). After a restart this means the catch-up was not started again.`,
- fix: renderAction({ argv: (after.cursor?.resume_command ?? `gbrain sync --source ${id} --no-pull`).split(' '), consent: [], actor: 'agent', requires_exclusive: false,
- why: 'Resumes the managed catch-up where its cursor stopped; the same command is safe to rerun in a loop.', verify }, ctx), before, after };
+ why: `${id}: the managed sync ${after.cursor ? 'cursor' : 'pass'} is pending at ${work?.index ?? '?'}/${work?.total ?? '?'} and nothing live is moving it (no sync run holds the lock; ${after.admitted} admitted request(s), no live consumer on the owner host). After a restart this means the catch-up was not started again.`,
+ fix: renderAction({ argv: ['gbrain', 'sync', ...(work?.resume_args ?? ['--source', id, '--no-pull'])], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Resumes the managed catch-up ${after.cursor ? 'where its cursor stopped' : 'with a plain sync that reconciles the checkout'}; the same command is safe to rerun in a loop.`, verify }, ctx), before, after };
+ }
case 'not_moving':
+ if (after.pass?.stuck) return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',
+ why: `${id}: every managed sync pass since ${after.pass.stuck_since} stopped ${after.pass.stuck}${after.pass.stop_reason ? ` (${after.pass.stop_reason})` : ''} with ${after.pass.remaining} path(s) unsettled, so the source does not converge even when pages commit.`,
+ fix: renderAction({ ...readFix('Read-only: the convergence of the source, the reason its passes stop and the next step.', { argv: ['gbrain', 'sync', 'status', '--source', id, '--json'] }), verify }, ctx), before, after };
return { source_id: id, state, exit: 1, code: 'managed_sync_not_moving', reason: 'movement_check',
why: `${id}: ${after.cursor ? `${after.cursor.remaining} entries pending, ` : ''}no page committed and no step advance inside the ${Math.round(windowMs / 1000)}s window while ${after.live.drain ? after.live.drain_job_id !== null && after.live.drain_pid === null ? `sync job #${after.live.drain_job_id} is draining it` : `a sync (pid ${after.live.drain_pid}) holds the lock` : 'a consumer is live'}; last progress ${after.last_progress_at ?? 'unknown'}.${head}`,
fix: renderAction({ ...status, verify }, ctx), before, after };
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 05c8f9f822..a3c93497bf 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -29,6 +29,7 @@ import { assertGraduationAdmission } from './graduation-custody.ts';
import { CAPACITY_VERIFY } from './capacity-verify.ts';
import { readManagedMode } from './managed-mode.ts';
import { localHostId } from './identity.ts';
+import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { segmentWriteScope } from '../page-body/ingest.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
@@ -1013,12 +1014,19 @@ export async function sweepSegmentStorage(engine: BrainEngine): Promise<void> {
* is how a resumed run finds what it committed. A receipt of a run whose
* managed-sync cursor is still open (not done) is never compacted, nor the newest
* committed sync receipt of its worktree.
+ * #6712 PR 4b (design v3.2 §3.7): a pass's receipts carry `intent.passId`
+ * instead; one whose pass row is open (`telemetry.outcome = 'open'`, its
+ * `pass_id` equal) is kept the same way, and the newest committed sync receipt
+ * is kept whether it names a run or a pass.
*/
+const OPEN_SYNC_PASS_SQL = (r: string) => `${r}.intent ? 'passId' AND EXISTS (SELECT 1 FROM op_checkpoints p
+ WHERE p.op='${MANAGED_SYNC_PASS_OP}' AND p.completed_keys->0->'telemetry'->>'pass_id'=${r}.intent->>'passId' AND p.completed_keys->0->'telemetry'->>'outcome'='open')`;
export const OPEN_SYNC_CURSOR_EXCLUSION = (r: string) => `AND NOT (${r}.intent ? 'runId' AND EXISTS (SELECT 1 FROM op_checkpoints c
- WHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=${r}.intent->>'runId' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'))`;
+ WHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=${r}.intent->>'runId' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'))
+ AND NOT (${OPEN_SYNC_PASS_SQL(r)})`;
export async function newestSyncReceipt(tx: SqlEngine, row: Pick<WriteRequest, 'id' | 'state' | 'intent' | 'worktree_id'>): Promise<boolean> {
- const intent = row.intent as { runId?: unknown; kind?: unknown } | null;
- if (row.state !== 'committed' || !row.worktree_id || typeof intent?.runId !== 'string' || !String(intent.kind ?? '').startsWith('managed_sync_')) return false;
+ const intent = row.intent as { runId?: unknown; passId?: unknown; kind?: unknown } | null;
+ if (row.state !== 'committed' || !row.worktree_id || (typeof intent?.runId !== 'string' && typeof intent?.passId !== 'string') || !String(intent?.kind ?? '').startsWith('managed_sync_')) return false;
const [newest] = await tx.executeRaw<{ id: string }>(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND state='committed'
AND COALESCE(intent->>'kind','') LIKE 'managed_sync_%' ORDER BY completed_at DESC, sequence DESC LIMIT 1`, [row.worktree_id]);
return newest?.id === row.id;
@@ -1056,7 +1064,8 @@ export const COMPACTABLE_STATES = ['committed', 'conflict', 'failed', 'cancelled
* Compacts one terminal receipt in its own short transaction (#6696 A9, A11): counters locked first in key order, then
* the request row, with transaction-local lock and statement timeouts so a concurrent admission waits at most that
* long. Every eligibility rule is rechecked under the lock: terminal, no recovery, not compacted, `states`,
- * `completedBefore`, no unfinished effect, no open sync cursor for its run, not the worktree's newest sync receipt.
+ * `completedBefore`, no unfinished effect, no open sync cursor for its run, no open pass for its pass id (#6712 PR 4b), not
+ * the worktree's newest sync receipt.
*/
export async function compactReceipt(engine: BrainEngine, row: Pick<WriteRequest, 'id' | 'principal_kind' | 'principal_id'>,
opts: { states?: readonly string[]; completedBefore?: string } = {}): Promise<{ freed_bytes: number } | { skipped: string }> {
@@ -1066,16 +1075,18 @@ export async function compactReceipt(engine: BrainEngine, row: Pick<WriteRequest
await tx.executeRaw("SET LOCAL statement_timeout = '15s'");
const keys = ['brain', principalKey(requestPrincipal(row as WriteRequest))];
await lockCounters(tx, keys);
- const [current] = await tx.executeRaw<WriteRequest & { eligible_age: boolean; open_cursor: boolean }>(`SELECT r.*,
+ const [current] = await tx.executeRaw<WriteRequest & { eligible_age: boolean; open_cursor: boolean; open_pass: boolean }>(`SELECT r.*,
($2::timestamptz IS NULL OR r.completed_at < $2::timestamptz) AS eligible_age,
EXISTS (SELECT 1 FROM op_checkpoints c WHERE r.intent ? 'runId' AND c.op='managed-sync' AND c.completed_keys->0->>'runId'=r.intent->>'runId'
- AND COALESCE(c.completed_keys->0->>'done','false')<>'true') AS open_cursor
+ AND COALESCE(c.completed_keys->0->>'done','false')<>'true') AS open_cursor,
+ COALESCE(${OPEN_SYNC_PASS_SQL('r')}, false) AS open_pass
FROM persistence_requests r WHERE r.id=$1::uuid FOR UPDATE OF r`, [row.id, opts.completedBefore ?? null]);
if (!current || current.compacted || current.recovery || !isTerminal(current)) return { skipped: 'changed' };
if (!(opts.states ?? COMPACTABLE_STATES).includes(current.state) || !current.eligible_age) return { skipped: 'changed' };
const unfinished = await tx.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state<>'committed' LIMIT 1", [row.id]);
if (unfinished.length) return { skipped: 'unfinished_effect' };
if (current.open_cursor) return { skipped: 'open_sync_cursor' };
+ if (current.open_pass) return { skipped: 'open_sync_pass' };
if (await newestSyncReceipt(tx, current)) return { skipped: 'newest_sync_receipt' };
const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytes
FROM persistence_effects WHERE request_id=$1::uuid`, [row.id]);
diff --git a/src/core/persistence/repair-busy.ts b/src/core/persistence/repair-busy.ts
index ca52285886..2158cfbec9 100644
--- a/src/core/persistence/repair-busy.ts
+++ b/src/core/persistence/repair-busy.ts
@@ -18,6 +18,12 @@
* and a repair that changes them is exactly what makes the next sync
* re-screen it.
*
+ * #6712 PR 4b (design v3.2 §3.7, CEO N4): a non-company source's pass adds
+ * nothing here. A pass freezes and admits under the drain lease and its
+ * freeze re-checks each candidate's revision, so busy means its open
+ * requests (the first arm) only; the cursor arm stays for company brains and
+ * for a legacy cursor the first pass has not retired yet.
+ *
* The read fails closed: a query that throws, or an unfinished cursor whose
* manifest cannot be read, makes every candidate busy (`unknown` names why).
* Callers check once when they plan and again at coordinated admission of
diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.ts
index e66e6c1831..3484ab4d37 100644
--- a/src/core/persistence/sync-blocked.ts
+++ b/src/core/persistence/sync-blocked.ts
@@ -5,6 +5,10 @@
* running request (`sync_incomplete`) is draining and not listed, and neither is a cursor saved after its recorded stop:
* the failure row stays until the whole run finishes, so a resumed run that is moving again would otherwise still read
* as blocked. A failure whose cursor is gone is an orphan (`gbrain repair managed-sync-orphans`), not a blocked run.
+ * #6712 PR 4b (design v3.2 §3.7): a non-company source has a pass row instead; it is blocked while its passes keep
+ * stopping (`passHealth`: the newest ended `blocked`, a `not_converged` streak, a `settle_mismatch` streak), with the
+ * newest pass's stop reason as `code`, its pass id as `run_id` and `stuck_since` as `blocked_since`. A source listed by
+ * its pass is not listed again by a legacy cursor.
*/
import type { BrainEngine } from '../engine.ts';
import { readManagedSyncFailures } from './sync-failures.ts';
@@ -18,7 +22,11 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s
const cursors = new Set((await engine.executeRaw<{ fingerprint: string }>(`
SELECT c.fingerprint FROM op_checkpoints c LEFT JOIN op_checkpoints f ON f.op='managed-sync-failure' AND f.fingerprint=c.fingerprint
WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true' AND (f.updated_at IS NULL OR f.updated_at>=c.updated_at)`)).map(row => row.fingerprint));
- return (await readManagedSyncFailures(engine, sourceIds))
- .filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key))
- .map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen }));
+ const { readPassReadings, passStopCode, passStuck, passStuckSince } = await import('./sync-pass-readers.ts');
+ const passes: BlockedManagedSync[] = (await readPassReadings(engine, { sourceIds, head: false })).filter(reading => passStuck(reading.health))
+ .map(reading => ({ source_id: reading.source_id, code: passStopCode(reading), run_id: reading.row.value.telemetry.pass_id, blocked_since: passStuckSince(reading.row) }));
+ const passSources = new Set(passes.map(blocked => blocked.source_id));
+ return [...(await readManagedSyncFailures(engine, sourceIds))
+ .filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key) && !passSources.has(failure.source_id))
+ .map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes];
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index e63236e9d6..e1b3dc895a 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -1092,27 +1092,55 @@ export interface ManagedSyncBacklog {
resume_command: string;
/** #6278: the arguments after `gbrain sync` that resume this cursor with its stored options. */
resume_args: string[];
+ /**
+ * #6712 PR 4b: set when the entry is a non-company source's pass row (design §3.7), not a cursor. `index`/`total` are
+ * then the newest round's settled and candidate paths, `remaining` its unsettled ones, `last_progress_at` the row's
+ * last write, `discovered_at` the pass's start. `converged_target` is where the source last converged and `head` the
+ * checkout's HEAD on this host (null when unread); `stuck` names a pass that keeps stopping (`blocked`,
+ * `not_converged`, `settle_mismatch`) and `stuck_since` when that began.
+ */
+ pass?: { pass_id: string; kind: string; round: number; outcome: string; stop_reason: string | null; target: string; converged_target: string | null; head: string | null;
+ stuck: 'blocked' | 'not_converged' | 'settle_mismatch' | null; stuck_since: string | null };
}
/**
* Unfinished managed cursors with their remaining entries and the rate of
* their latest drain window (CEO-A18), readable from any process.
+ * #6712 PR 4b (design v3.2 §3.7): plus every source whose pass row is not
+ * `nothing_pending` (`passHealth`: converged at the checkout's HEAD and the
+ * newest pass ended `synced` or `up_to_date`); a source's pass entry replaces
+ * a legacy cursor entry of the same source.
*/
export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {
const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; discoveredAt?: string; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };
counts?: { held?: number }; processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] } }>(
`SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);
- return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {
+ const { readPassReadings, passResumeArgs, passStuck, passStuckSince } = await import('./sync-pass-readers.ts');
+ const passes: ManagedSyncBacklog[] = (await readPassReadings(engine, { sourceIds })).filter(r => !r.health.nothing_pending).map(({ source_id, row, head, health }) => {
+ const t = row.value.telemetry, args = passResumeArgs(source_id, row), stuck = passStuck(health) ? health.reason as 'blocked' | 'not_converged' | 'settle_mismatch' : null;
+ return { source_id, index: Number(t.settled ?? 0), total: Number(t.candidates ?? 0), remaining: Number(health.remaining ?? t.remaining ?? 0), rate_pages_per_min: null, eta_seconds: null,
+ last_progress_at: row.updated_at, discovered_at: t.started_at ?? null, held: Number(t.counts?.held ?? 0), resume_command: syncResumeCommand(args), resume_args: args,
+ pass: { pass_id: t.pass_id, kind: t.kind, round: Number(t.round ?? 0), outcome: t.outcome, stop_reason: t.stop_reason ?? null, target: t.target,
+ converged_target: row.value.obligations.converged?.target ?? null, head, stuck, stuck_since: stuck ? passStuckSince(row) : null } };
+ });
+ const passSources = new Set(passes.map(b => b.source_id));
+ return [...rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId)) && !passSources.has(h.sourceId)).map(h => {
const remaining = Math.max(0, Number(h.total) - Number(h.index));
const p = h.progress;
const estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };
const args = managedSyncResumeArgs({ sourceId: h.sourceId, processingOptions: h.processingOptions, syncOptions: h.syncOptions });
return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,
last_progress_at: p ? new Date(p.lastAt).toISOString() : null, discovered_at: h.discoveredAt ?? null, held: Number(h.counts?.held ?? 0), resume_command: syncResumeCommand(args), resume_args: args };
- });
+ }), ...passes];
}
export function formatManagedSyncBacklog(b: ManagedSyncBacklog): string {
+ if (b.pass) {
+ const p = b.pass, behind = p.head && p.converged_target !== p.head && (p.outcome === 'synced' || p.outcome === 'up_to_date');
+ return `${b.source_id}: managed sync pass ${p.outcome === 'open' ? 'running' : `ended ${p.outcome}`}${p.stop_reason ? ` (${p.stop_reason})` : ''}`
+ + (behind ? `, HEAD ${p.head!.slice(0, 8)} is past the converged commit ${p.converged_target?.slice(0, 8) ?? '(none)'}` : ` at round ${p.round} (${b.remaining} of ${b.total} candidate path(s) unsettled)`)
+ + (p.stuck ? `; stopping ${p.stuck} since ${p.stuck_since}` : '') + `. Resume: ${b.resume_command}`;
+ }
return `${b.source_id}: managed sync cursor at ${b.index}/${b.total} (${b.remaining} remaining`
+ (b.rate_pages_per_min !== null ? `, last drain ${b.rate_pages_per_min} pages/min, indexing ETA ${b.eta_seconds === null ? 'unknown' : formatDuration(b.eta_seconds)}` : ', rate unknown')
+ `). Resume: ${b.resume_command}`;
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 54e8279a73..354da65d96 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -38,6 +38,7 @@ import type { Action } from '../agent-output.ts';
import { inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';
import { currentRunDeadline, lastForwardProgressAt, noteForwardProgress } from '../forward-progress.ts';
import { faultPoint } from './fault-points.ts';
+import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { VERSION } from '../../version.ts';
export const DRAIN_LEASE_TTL_MINUTES = 2;
@@ -100,15 +101,19 @@ export async function readDrainHolder(engine: BrainEngine, sourceId: string): Pr
progress: await holderProgress(engine, sourceId, snap.acquired_at).catch(() => null) };
}
-/** The source's managed-sync commits since `since`, and its last commit or cursor save at all. */
+/**
+ * The source's managed-sync commits since `since`, and its last commit, cursor save or (#6712 PR 4b, design v3.2 §3.7)
+ * pass row write at all: a pass writes its row at the pin, per batch and at the stamp.
+ */
async function holderProgress(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, since: Date | null): Promise<DrainHolderProgress> {
const [row] = await engine.executeRaw<{ committed: number | string; last_committed_at: Date | string | null; last_saved_at: Date | string | null }>(`
SELECT (SELECT count(*) FROM persistence_requests r WHERE r.worktree_id=b.worktree_id AND r.state='committed'
AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' AND r.completed_at >= $2::timestamptz) AS committed,
(SELECT max(r.completed_at) FROM persistence_requests r WHERE r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation
AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS last_committed_at,
- (SELECT max(c.updated_at) FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1) AS last_saved_at
- FROM persistence_source_bindings b WHERE b.source_id=$1`, [sourceId, (since ?? new Date(0)).toISOString()]);
+ GREATEST((SELECT max(c.updated_at) FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1),
+ (SELECT c.updated_at FROM op_checkpoints c WHERE c.op=$3 AND c.fingerprint=b.source_id||':'||b.source_incarnation::text)) AS last_saved_at
+ FROM persistence_source_bindings b WHERE b.source_id=$1`, [sourceId, (since ?? new Date(0)).toISOString(), MANAGED_SYNC_PASS_OP]);
const at = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();
const committedAt = at(row?.last_committed_at), savedAt = at(row?.last_saved_at);
return { committed: Number(row?.committed ?? 0), last_committed_at: committedAt,
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index 05ca49a08b..488f056efa 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -31,6 +31,15 @@
* `startMovementWatch` is the serve's unref'd ticker that prints one
* `[gbrain notice managed_sync_not_moving]` when a source flips to not moving
* and one line when it moves again.
+ *
+ * #6712 PR 4b (design v3.2 §3.7): a non-company source has a pass row, not a
+ * cursor, and the backlog reader returns it as an entry with `pass` set; it
+ * lands in the additive `pass` field (`cursor` stays the cursor's). The pass
+ * row's last write is progress. Pending means not `nothing_pending`
+ * (`passHealth`: converged at HEAD and the newest pass ended `synced` or
+ * `up_to_date`). A pass that keeps stopping (`blocked`, a `not_converged`
+ * streak, a `settle_mismatch` streak) is `not_moving` whatever else is live:
+ * every tick may commit pages, yet the source never converges.
*/
import type { BrainEngine } from '../engine.ts';
import { readManagedSyncBacklog, type ManagedSyncBacklog } from './sync-drain.ts';
@@ -63,6 +72,8 @@ export interface SourceMovement {
/** The watermark the verdict used: the newest of a commit, a head step advance and the drain's cursor advance. */
last_progress_at: string | null;
cursor: (Pick<ManagedSyncBacklog, 'index' | 'total' | 'remaining' | 'held' | 'last_progress_at' | 'resume_command' | 'resume_args'>) | null;
+ /** #6712 PR 4b: the source's pending pass row (the backlog's pass entry), null when it has none or nothing is pending. */
+ pass: (Pick<ManagedSyncBacklog, 'index' | 'total' | 'remaining' | 'held' | 'last_progress_at' | 'resume_command' | 'resume_args'> & NonNullable<ManagedSyncBacklog['pass']>) | null;
head: MovementHead | null;
holds: MovementHolds;
/** Managed requests admitted on the worktree and not yet settled (queued or running). */
@@ -152,15 +163,18 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
const ownerHere = binding.owner_host_id === null ? null : binding.owner_host_id === host;
const claimLive = !!claim && (claim.phase === 'preparing' || claim.phase === 'publishing');
const consumer: SourceMovement['live']['consumer'] = claimLive ? 'claim' : ownerHere !== false && localConsumer ? 'local' : ownerHere !== false && await liveHeartbeat() ? 'heartbeat' : null;
- const cursor = backlog.get(binding.source_id) ?? null;
+ const entry = backlog.get(binding.source_id) ?? null;
+ const cursor = entry && !entry.pass ? entry : null;
+ const pass = entry?.pass ? { index: entry.index, total: entry.total, remaining: entry.remaining, held: entry.held, last_progress_at: entry.last_progress_at,
+ resume_command: entry.resume_command, resume_args: entry.resume_args, ...entry.pass } : null;
const holds: MovementHolds = { count: Number(holdRow?.count ?? 0), stalled: Number(holdRow?.stalled ?? 0), fences: Number(holdRow?.fences ?? 0), concurrent: Number(holdRow?.concurrent ?? 0), last_hold_at: iso(holdRow?.updated_at) };
const lastCommitAt = iso(mark?.last_commit_at);
const admitted = Number(mark?.admitted ?? 0);
- const progressAt = newest(lastCommitAt, claimLive ? head?.step_since : null, cursor?.last_progress_at);
+ const progressAt = newest(lastCommitAt, claimLive ? head?.step_since : null, cursor?.last_progress_at, pass?.last_progress_at);
const sampledAt = new Date(now).toISOString();
const base = { source_id: binding.source_id, sampled_at: sampledAt, last_commit_at: lastCommitAt, last_progress_at: progressAt,
cursor: cursor ? { index: cursor.index, total: cursor.total, remaining: cursor.remaining, held: cursor.held, last_progress_at: cursor.last_progress_at, resume_command: cursor.resume_command, resume_args: cursor.resume_args } : null,
- head, holds, admitted, admitted_since: iso(mark?.admitted_since), live: { drain: !!drain || !!jobDrain, drain_pid: drain?.holder_pid ?? null, drain_job_id: jobDrain, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,
+ pass, head, holds, admitted, admitted_since: iso(mark?.admitted_since), live: { drain: !!drain || !!jobDrain, drain_pid: drain?.holder_pid ?? null, drain_job_id: jobDrain, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,
writer_status_command: writerStatusCommand(binding.source_id) };
out.push({ ...base, ...verdict(base, now) });
}
@@ -168,7 +182,8 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
}
function verdict(m: Omit<SourceMovement, 'movement_state' | 'data_moving' | 'not_moving_since'>, now: number): Pick<SourceMovement, 'movement_state' | 'data_moving' | 'not_moving_since'> {
- if (!m.cursor) return { movement_state: 'nothing_pending', data_moving: null, not_moving_since: null };
+ if (!m.cursor && !m.pass) return { movement_state: 'nothing_pending', data_moving: null, not_moving_since: null };
+ if (m.pass?.stuck) return { movement_state: 'not_moving', data_moving: false, not_moving_since: m.pass.stuck_since };
const driving = m.live.drain || (m.admitted > 0 && m.live.consumer !== null);
if (!driving) return { movement_state: 'parked', data_moving: null, not_moving_since: null };
if (m.holds.last_hold_at && (!m.last_commit_at || m.holds.last_hold_at > m.last_commit_at) && m.last_progress_at && m.holds.last_hold_at >= m.last_progress_at) {
@@ -184,11 +199,14 @@ function safeJson(text: string): unknown { try { return JSON.parse(text); } catc
export function formatSourceMovement(m: SourceMovement): string | null {
if (m.movement_state === 'nothing_pending') return null;
const where = m.head?.step ? ` head at step ${m.head.step}${m.head.waiting_on && m.head.waiting_on !== 'unknown' ? ` (waiting on ${m.head.waiting_on})` : ''}${m.head.owner ? `, ${m.head.owner.kind} pid ${m.head.owner.pid}` : ''};` : '';
+ const work = m.cursor ?? m.pass!;
+ if (m.pass?.stuck) return `${m.source_id}: managed sync NOT CONVERGING: every pass since ${m.pass.stuck_since} stopped ${m.pass.stuck}${m.pass.stop_reason ? ` (${m.pass.stop_reason})` : ''}, `
+ + `${m.pass.remaining} path(s) unsettled; inspect: gbrain sync status --source ${m.source_id} --json`;
switch (m.movement_state) {
case 'not_moving': return `${m.source_id}: managed sync NOT MOVING since ${m.not_moving_since} (no committed page or step advance for longer than ${Math.round(m.ceiling_ms / 1000)}s while a ${m.live.drain ? 'sync' : 'consumer'} is live);${where} inspect: ${m.writer_status_command}`;
- case 'parked': return `${m.source_id}: managed sync parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer is live; informational). Resume: ${m.cursor!.resume_command}`;
+ case 'parked': return `${m.source_id}: managed sync parked at ${work.index}/${work.total} (no sync or consumer is live; informational). Resume: ${work.resume_command}`;
case 'held': return `${m.source_id}: managed sync advancing by holds only (${m.holds.count} held, newest ${m.holds.last_hold_at}); the containment is working, not a stall.`;
- default: return `${m.source_id}: managed sync moving (last progress ${m.last_progress_at ?? 'unknown'}, ${m.cursor!.remaining} remaining).`;
+ default: return `${m.source_id}: managed sync moving (last progress ${m.last_progress_at ?? 'unknown'}, ${work.remaining} remaining).`;
}
}
@@ -196,12 +214,14 @@ export function formatSourceMovement(m: SourceMovement): string | null {
export type MovementVerdict = 'moved' | 'within_allowance' | 'held' | 'parked' | 'not_moving' | 'nothing_pending';
export function judgeMovement(before: SourceMovement | undefined, after: SourceMovement): MovementVerdict {
if (after.movement_state === 'nothing_pending') return 'nothing_pending';
+ if (after.pass?.stuck) return 'not_moving';
if (!before) return after.movement_state === 'moving' ? 'moved' : after.movement_state;
if (after.last_commit_at && (!before.last_commit_at || after.last_commit_at > before.last_commit_at)) return 'moved';
if (after.holds.last_hold_at && (!before.holds.last_hold_at || after.holds.last_hold_at > before.holds.last_hold_at)) return 'held';
if (after.movement_state === 'parked') return 'parked';
const stepAdvanced = after.head?.step_since && (!before.head || before.head.request_id !== after.head.request_id || before.head.step_since !== after.head.step_since);
- if (stepAdvanced || (after.cursor && before.cursor && after.cursor.index > before.cursor.index)) return 'within_allowance';
+ const passAdvanced = after.pass && before.pass && (after.pass.pass_id !== before.pass.pass_id || after.pass.last_progress_at !== before.pass.last_progress_at);
+ if (stepAdvanced || passAdvanced || (after.cursor && before.cursor && after.cursor.index > before.cursor.index)) return 'within_allowance';
return 'not_moving';
}
diff --git a/src/core/persistence/sync-pass-readers.ts b/src/core/persistence/sync-pass-readers.ts
new file mode 100644
index 0000000000..2e50443c22
--- /dev/null
+++ b/src/core/persistence/sync-pass-readers.ts
@@ -0,0 +1,65 @@
+/**
+ * #6712 PR 4b (design v3.2 §3.7): the pass row as the former cursor readers see it. A non-company source has no cursor
+ * once its first pass ran, so doctor, the movement reader, the backlog, the blocked-run reader and `sources status`
+ * read its pass row instead, through `passHealth`, the one rule `sync-pass-row.ts` keeps. Company sources and legacy
+ * cursors keep their cursor arm in each reader.
+ *
+ * `nothing_pending` needs the checkout's HEAD: it is read with a hardened `rev-parse` of the source's checkout on this
+ * host. A host with no checkout of the source (or one Git cannot read) gets `head: null`, and the reading then trusts
+ * the converged target the pass recorded, as a cursor reader trusts a missing cursor.
+ */
+import { resolve } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { hardenedGitSync } from '../hardened-git.ts';
+import { managedSyncResumeArgs } from '../sync-reconcile.ts';
+import { localHostId } from './identity.ts';
+import { passHealth, readLivePassRows, type PassHealth, type PassRow } from './sync-pass-row.ts';
+
+export interface PassReading { source_id: string; row: PassRow; head: string | null; health: PassHealth }
+
+/** HEAD of each source's checkout on this host, or null when this host has none or Git cannot read it. */
+export async function readCheckoutHeads(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<Map<string, string | null>> {
+ const heads = new Map<string, string | null>(sourceIds.map(id => [id, null]));
+ if (!sourceIds.length) return heads;
+ const rows = await engine.executeRaw<{ source_id: string; local_path: string; relative_path: string }>(`SELECT b.source_id, h.local_path, b.relative_path
+ FROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$2::uuid
+ WHERE b.source_id=ANY($1::text[])`, [[...sourceIds], localHostId()]);
+ for (const row of rows) {
+ const out = hardenedGitSync(resolve(row.local_path, row.relative_path), ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { timeoutMs: 10_000, maxBytes: 4096 });
+ heads.set(row.source_id, out.ok ? out.stdout.toString('utf8').trim() || null : null);
+ }
+ return heads;
+}
+
+/**
+ * The pass rows of the sources' live incarnations with their health. `stalledMs`: an open pass whose row has not moved
+ * for that long reads `open_stalled` (Infinity: never). `head: false` skips the HEAD read (no `nothing_pending` test).
+ */
+export async function readPassReadings(engine: Pick<BrainEngine, 'executeRaw'>, opts: { sourceIds?: readonly string[]; now?: number; stalledMs?: number; head?: boolean } = {}): Promise<PassReading[]> {
+ const rows = await readLivePassRows(engine, opts.sourceIds);
+ if (!rows.size) return [];
+ const heads = opts.head === false ? new Map<string, string | null>() : await readCheckoutHeads(engine, [...rows.keys()]);
+ return [...rows].sort(([a], [b]) => a.localeCompare(b)).map(([sourceId, row]) => {
+ const head = heads.get(sourceId) ?? null;
+ return { source_id: sourceId, row, head, health: passHealth(row, { head, now: opts.now, stalledMs: opts.stalledMs ?? Infinity }) };
+ });
+}
+
+/** A reason `passHealth` gives for a pass that keeps stopping (an open pass that stalled is the movement reader's call). */
+export const passStuck = (health: PassHealth): boolean => health.reason === 'blocked' || health.reason === 'not_converged' || health.reason === 'settle_mismatch';
+
+/** When the source started reading stuck: the pass row's `stuck_since`, else the newest pass's ending, else the row's last write. */
+export function passStuckSince(row: PassRow): string {
+ return row.value.obligations.stuck_since ?? row.value.telemetry.ended_at ?? row.updated_at;
+}
+
+/** The stop the newest pass names: its stop reason, else the health reason. */
+export function passStopCode(reading: Pick<PassReading, 'row' | 'health'>): string {
+ return reading.row.value.telemetry.stop_reason ?? reading.health.reason ?? reading.row.value.telemetry.outcome;
+}
+
+/** The plain sync that continues the source, carrying the open episode's inherited opt-outs (design §6). */
+export function passResumeArgs(sourceId: string, row: PassRow): string[] {
+ const inherited = row.value.obligations.episode?.inherited;
+ return managedSyncResumeArgs({ sourceId, processingOptions: inherited ? { noEmbed: inherited.noEmbed, noExtract: inherited.noExtract, noSchemaPack: inherited.noSchemaPack } : null });
+}
diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.ts
index 868f9d05a4..7a36baceea 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -62,6 +62,8 @@ export interface ManagedSyncPassValue {
converged?: PassConverged;
mismatch: Record<string, { level: string | null; streak: number }>;
not_converged_streak: number;
+ /** When the current run of unhealthy endings (`blocked`, `not_converged`) began; kept across them, cleared at `synced`/`up_to_date`. The §3.7 readers age a stuck source from it. */
+ stuck_since?: string | null;
faults: Record<string, { level: string | null; class: string; attempts: number }>;
};
telemetry: {
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index aff17521c0..486e029fd9 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -24,6 +24,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { isStatementTimeout } from './bounded-reads.ts';
import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';
+import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import type { PublicCategory } from './public-category.ts';
import { classifyTerminal, dispositionOf, driftSinceAction, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
@@ -221,6 +222,11 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
/**
* PR A's checkpoint blockers for every non-archived source whose managed-sync cursor waits at its checkpoint step
* (the others have none), keyed by source, for `readTerminalFailureSummary`.
+ * #6712 PR 4b (design v3.2 §3.7): also every source whose open pass (pass row `telemetry.outcome = 'open'`) has its
+ * `managed_sync_checkpoint` admitted and not yet committed (`intent.passId` equal to the row's `pass_id`). Its blockers
+ * are what the pass checkpoint's validation refuses on (design v3 §3.3 clauses 1-2): a recovery row on the worktree, and
+ * a queued, running or recovering sync page or checkpoint request of the worktree other than the checkpoint itself.
+ * Both reads go through the partial indexes `persistence_requests_recovery` and `persistence_requests_pending`.
*/
export async function readCheckpointBlockerMap(engine: BrainEngine, sourceIds?: string[]): Promise<NonNullable<Parameters<typeof readTerminalFailureSummary>[1]>['checkpointBlockers'] & {}> {
const { readCheckpointBlockers } = await import('./sync-status.ts');
@@ -230,6 +236,23 @@ export async function readCheckpointBlockerMap(engine: BrainEngine, sourceIds?:
AND ($1::text[] IS NULL OR o.completed_keys->0->>'sourceId'=ANY($1::text[]))`, [sourceIds ?? null]);
const blockers = new Map<string, Awaited<ReturnType<typeof readCheckpointBlockers>>>();
for (const row of atCheckpoint) blockers.set(row.source_id, await readCheckpointBlockers(engine, row.source_id));
+ const passes = await engine.executeRaw<{ source_id: string; worktree_id: string; checkpoint: string }>(`SELECT s.id AS source_id, b.worktree_id::text AS worktree_id, r.request_id::text AS checkpoint
+ FROM sources s JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
+ JOIN op_checkpoints p ON p.op=$1 AND p.fingerprint=s.id||':'||s.incarnation::text AND p.completed_keys->0->'telemetry'->>'outcome'='open'
+ JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.state IN ('queued','running','recovering')
+ AND r.intent->>'kind'='managed_sync_checkpoint' AND r.intent->>'passId'=p.completed_keys->0->'telemetry'->>'pass_id'
+ WHERE s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))`, [MANAGED_SYNC_PASS_OP, sourceIds ?? null]);
+ for (const pass of passes) {
+ if (blockers.has(pass.source_id)) continue;
+ const rows = await engine.executeRaw<{ request_id: string; slug: string; state: string; code: string | null; recovery: boolean }>(`SELECT DISTINCT ON (request_id) request_id, slug, state, code, recovery FROM (
+ (SELECT r.request_id::text AS request_id, r.slug, r.state, r.error_code AS code, true AS recovery, r.sequence FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL ORDER BY r.sequence LIMIT 20)
+ UNION ALL (SELECT r.request_id::text, r.slug, r.state, r.error_code, false, r.sequence FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id::text<>$2
+ AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') ORDER BY r.sequence LIMIT 20)) blockers
+ ORDER BY request_id, recovery DESC`, [pass.worktree_id, pass.checkpoint]);
+ blockers.set(pass.source_id, rows.slice(0, 20).map(row => ({ request_id: row.request_id, slug: row.slug, state: row.state, code: row.code, index: null, recovery: row.recovery === true, knock_on: false })));
+ }
return blockers;
}
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 107b0be5f2..dc35d1cf57 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -275,7 +275,11 @@ async function worktreeRecoveryPending(engine: BrainEngine, binding: WorktreeBin
try { const held = await probe(); return held?.publication === true || held?.topology === true; }
finally { await lock.release(); }
}
-/** Never wait on a sync: an unexhausted cursor names its own resume command. */
+/**
+ * Never wait on a sync: an unexhausted cursor names its own resume command. #6712 PR 4b (design v3.2 §3.3): a
+ * non-company source's pass is never stranded by a checkout move (it reconciles whatever HEAD it pins next), so only
+ * cursors refuse: a company brain's, and a legacy one the first pass has not retired yet.
+ */
async function assertNoUnfinishedSync(engine: BrainEngine, members: string[]): Promise<void> {
const [cursor] = await engine.executeRaw<{ source_id: string; header: Record<string, unknown> }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
c.completed_keys->0 AS header
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index fbddf4e110..4396645c86 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -54,6 +54,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { digest, sha256 } from '../persistence/digest.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { clearGitHold, readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { loadRepairBusySet, repairBusy, repairBusyMessage, type RepairBusySet } from '../persistence/repair-busy.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import type { SyncRename } from '../persistence/sync-discovery.ts';
import { canonicalRepairFields, confinedRepairTarget, managedRepairRoot, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
@@ -391,17 +392,15 @@ async function scan(engine: BrainEngine, scope: RepairScope, selection: Selectio
return out;
}
-/** E9: an unfinished managed sync cursor that still names one of these paths. */
-async function unfinishedSyncPath(engine: BrainEngine, sourceId: string, paths: Set<string>): Promise<string | null> {
- const cursors = await engine.executeRaw<{ run_id: string; index: number | string | null }>(`SELECT completed_keys->0->>'runId' AS run_id, completed_keys->0->>'index' AS index
- FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true' AND completed_keys->0->>'sourceId'=$1`, [sourceId]);
- for (const cursor of cursors) {
- const [manifest] = await engine.executeRaw<{ completed_keys: Array<{ path?: string; sourcePath?: string }> }>(
- "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.run_id]);
- const named = (manifest?.completed_keys ?? []).slice(Number(cursor.index ?? 0)).find(entry => paths.has(entry.path ?? '') || paths.has(entry.sourcePath ?? ''));
- if (named) return named.path ?? named.sourcePath ?? null;
- }
- return null;
+/**
+ * E9: the first approved file a sync or write of the source still names, read through the repair busy set (#6712 PR 4b,
+ * design v3.2 §3.7: one interlock for every repair; an unreadable set names the first file).
+ */
+async function busySyncPath(engine: BrainEngine, sourceId: string, items: Array<{ path: string; source_path?: string | null; slug?: string | null }>): Promise<{ path: string; busy: RepairBusySet } | null> {
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const busy = await loadRepairBusySet(engine, sourceId, source?.incarnation ?? '');
+ const named = items.find(entry => repairBusy(busy, { path: entry.path, sourcePath: entry.source_path, slug: entry.slug }));
+ return named ? { path: named.path, busy } : null;
}
function item(repair: ApprovedRepair, selection: Selection, hash: string, index: number, last: boolean): FrontmatterItem {
@@ -427,8 +426,9 @@ export const frontmatterRepair: RepairHandler = {
emptyHash: async () => previewHash({ kind: 'frontmatter-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])), selection, items: [] }) });
if (approved.items.some(entry => !sameSelection(entry.selection, selection))) throw previewChangedError(opts.expect, shellQuote(preview));
for (const sourceId of new Set(approved.items.map(entry => entry.source_id))) {
- const named = await unfinishedSyncPath(engine, sourceId, new Set(approved.items.filter(entry => entry.source_id === sourceId).flatMap(entry => [entry.path, entry.source_path])));
- if (named) throw opError('sync_in_progress', `Source ${sourceId} has an unfinished managed sync that still names ${named}, so the repair wrote nothing.`,
+ const named = await busySyncPath(engine, sourceId, approved.items.filter(entry => entry.source_id === sourceId));
+ if (named) throw opError('sync_in_progress', named.busy.unknown !== null ? `${repairBusyMessage(named.busy, sourceId, named.path)} The repair wrote nothing.`
+ : `Source ${sourceId} has an unfinished managed sync or write that still names ${named.path}, so the repair wrote nothing.`,
`Finish that sync first: gbrain sync --source ${sourceId} --no-pull — then preview the repair again (${shellQuote(preview)}) and approve its new hash.`,
{ fix: { argv: ['gbrain', 'sync', '--source', sourceId, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false,
why: `Finishes source ${sourceId}'s unfinished sync cursor, which would otherwise race the repair of a file it still names.` } });
diff --git a/test/repair-frontmatter.test.ts b/test/repair-frontmatter.test.ts
index 4630d4560b..0ca255c501 100644
--- a/test/repair-frontmatter.test.ts
+++ b/test/repair-frontmatter.test.ts
@@ -261,7 +261,7 @@ test('apply refuses while an unfinished managed sync cursor still names a select
const hash = preview.apply_command.split('--expect ')[1]!.split(' ')[0]!;
const runId = randomUUID();
await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`,
- [`fixture-${runId}`, JSON.stringify([{ sourceId: s.id, runId, index: 0, total: 1 }])]);
+ [`fixture-${runId}`, JSON.stringify([{ sourceId: s.id, incarnation: (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [s.id]))[0]!.incarnation, runId, index: 0, total: 1 }])]);
await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-manifest',$1,$2::text::jsonb)`,
[runId, JSON.stringify([{ path: 'notes/roundup.md', sourcePath: 'notes/roundup.md', action: 'import', working: false }])]);
try {