Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712 PR1 lane C: sync-side single fate, deferral, dependency edges, #6600 settle, knock_on tombstone
garrytanb3321c3f2240
diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex a33e82590d..2ced529f49 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -21,10 +21,9 @@ export interface SyncResult {managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;/** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */retryWait?: import('../core/persistence/sync-run.ts').RetryWait;- /** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. *//** #6693: caller remembers refused while their page's file awaited import (or was held), replayed after this sync imported it. */replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;- knockOns?: { refrozen: number }; /** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;+ /** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';fromCommit: string | null;toCommit: string;diff --git a/src/core/config.ts b/src/core/config.tsindex 759dee75c2..2cd24e5ba8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1740,9 +1740,6 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['sync.hold_escalate_count','sync.hold_escalate_pct','sync.parser_regression',- // #6643: knock-on re-freezes in a row at one index (default 3; 0 turns automatic re-freeze off) and per run (default 25).- 'sync.knock_on_refreeze_limit',- 'sync.knock_on_run_limit','fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spenddiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex cf04bfd125..4711bc45d3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -43,6 +43,12 @@ export interface CodeEntry {/** CLI exit code; default derives from class (1). */exit?: number;retryable?: boolean;+ /**+ * The release that retired this code: nothing emits it any more, but receipts and ledger rows an older build wrote still+ * carry it, so the entry stays and `gbrain errors <code>` still answers. Its fix names the current path, never a retired+ * key or flag (`test/error-registry-retired.test.ts`).+ */+ retired_in?: string;}export const CODES = {@@ -381,12 +387,13 @@ export const CODES = {preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },- // #6643: a managed sync stopped re-freezing pages that only waited on another page of the same sync.- knock_on_exhausted: { class: 'server', summary: "A managed sync kept re-freezing a page that only waited on another page of the same sync, and stopped at its limit because that earlier page still did not commit.",- why: "A page cancelled or refused only because an earlier page of its sync did not commit published nothing, so the sync re-freezes it under a fresh request by itself; the limit stops a loop when the earlier page keeps failing.",+ // #6643, retired by #6712 (one page, one fate): no page waits on another page's fate any more, so nothing re-freezes knock-ons.+ knock_on_exhausted: { class: 'server', retired_in: '0.60.249.0',+ summary: "Retired: an older gbrain stopped a managed sync that kept re-freezing a page cancelled only because another page of the same sync did not commit. This build never cancels a page for another page's failure, so the stop is superseded.",+ why: "Since #6712 each page of a sync has its own fate: a page that does not commit is held or stops the run on its own, and the pages after it still publish. A ledger row or receipt with this code was written by an older build.",docs: 'docs/guides/sync-unblock-runbook.md#decision-table',- suggestion: 'Read gbrain sync status --source <id> --json: last_error.root_cause names the request that keeps failing. Fix that request, or raise sync.knock_on_refreeze_limit / sync.knock_on_run_limit, then rerun the same sync.',- fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the root request, its page and error; read-only.' } },+ suggestion: 'Rerun the same plain gbrain sync --source <id> --no-pull; it resumes the stopped entry under a fresh request. gbrain sync status --source <id> --json shows what remains.',+ fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the cursor and the next step; read-only. A plain sync of the source resumes the stopped entry.' } },keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's CJK keyword arm hit its deadline or candidate cap on a large corpus, so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan; the arm is bounded so a large brain cannot stall every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Narrow the search with --source-id (MCP source_id), or ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 3f7a44c702..4ec0835e47 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -23,7 +23,6 @@ import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } fromimport { docsAnchor } from './connector-errors.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import type { SyncCursorOptions } from './sync-prepare.ts';-import { syncKnockOnSql } from './sync-knock-on.ts';export const CHECKPOINT_VALIDATION_TIMEOUT = 'checkpoint_validation_timeout';export const CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE = 'The sync checkpoint validation timed out on a large request table; the checkpoint did not commit.';@@ -32,9 +31,9 @@ export const REQUEST_INDEXES_REPAIR_COMMAND = 'gbrain repair request-indexes --aconst SYNC_PAGE_KINDS = "r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')";/*** #6643: clause 3 skips a terminal, recovery-free receipt the cursor settled another way: one the run converted in place- * ($3, #5988), one at an index the cursor passed without a commit (waived or held: the settled ranges $4..$5), and, only- * below $6 (the index from which the cursor recorded its settled ranges, i.e. a cursor that began before #6643), a- * knock-on (sync-knock-on.ts), which never published and whose entry the cursor re-froze when it reached it.+ * ($3, #5988) and one at an index the cursor passed without a commit (waived or held: the settled ranges $4..$5).+ * #6712 retired the knock-on exemption ($6): no page is cancelled for another page's failure any more, and the cursor+ * converts a legacy knock-on it meets in place (sync-run.ts `refreezeInPlace`).*/export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS request_id FROM persistence_requests rWHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)@@ -48,8 +47,7 @@ export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS requesAND committed.state='committed' AND committed.intent ? 'runId')AND NOT (r.request_id::text=ANY($3::text[]))AND NOT (r.state IN ('failed','cancelled','conflict') AND r.recovery IS NULL- AND EXISTS (SELECT 1 FROM unnest($4::int[], $5::int[]) AS settled(lo, hi) WHERE (r.intent->>'index')::int BETWEEN settled.lo AND settled.hi))- AND NOT ((r.intent->>'index')::int < $6::int AND ${syncKnockOnSql('r')}) LIMIT 1)+ AND EXISTS (SELECT 1 FROM unnest($4::int[], $5::int[]) AS settled(lo, hi) WHERE (r.intent->>'index')::int BETWEEN settled.lo AND settled.hi)) LIMIT 1)LIMIT 1`;/** #6643: the index ranges a cursor passed without a commit, and the index it began recording them at. */@@ -63,11 +61,11 @@ export interface SyncSettledIndexes { from: number; ranges: Array<[number, numbe* commit; null for a checkpoint frozen before #6643, whose whole run predates it.*/export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = [],- settled: SyncSettledIndexes | null = null, total = 0): Promise<string | null> {+ settled: SyncSettledIndexes | null = null): Promise<string | null> {try {const ranges = settled?.ranges ?? [];const [row] = await tx.executeRaw<{ request_id: string }>(INCOMPLETE_SYNC_RECEIPT_SQL,- [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1]), settled ? settled.from : total]);+ [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1])]);return row?.request_id ?? null;} catch (error) {const failure = error as { code?: string; message?: string };@@ -83,11 +81,11 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa* knock-on from a root; read-only. The checkpoint itself names only the first (`findIncompleteSyncReceipt`).*/export async function listIncompleteSyncReceipts(engine: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = [],- settled: SyncSettledIndexes | null = null, total = 0): Promise<Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean }>> {+ settled: SyncSettledIndexes | null = null): Promise<Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean }>> {const ranges = settled?.ranges ?? [];return engine.executeRaw(`SELECT r.request_id::text AS request_id, r.slug, r.state, r.error_code AS code, (r.intent->>'index')::int AS index, r.recovery IS NOT NULL AS recoveryFROM persistence_requests r WHERE r.request_id::text IN (SELECT request_id FROM (${INCOMPLETE_SYNC_RECEIPT_SQL.replaceAll('LIMIT 1', 'LIMIT 20')}) blockers) ORDER BY r.sequence LIMIT 20`,- [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1]), settled ? settled.from : total]);+ [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1])]);}/** #6643: `settled` with `[from, to]` added, merged into the last range when contiguous. */diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex e2cdf876d2..c00316a944 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -18,6 +18,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'consumer:preparing' | 'lane:applied'// #6712 PR 0: after `freezeEntry` froze an import entry (its bytes are read) and before the request is admitted or published.| 'sync:after_freeze'+ // #6712 PR 1 (L2): after the cursor step that holds a failed entry and settles its index commits (`holdUnderGate`), and after+ // the cursor step that defers an entry whose file changed after admission past the manifest end (`deferChangedEntry`).+ | 'sync:held_settled' | 'sync:retry_deferred'// #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 07272a5493..6ae2051f58 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -384,10 +384,16 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, creturn hold && !hold.meta.blob_oid && !hold.meta.working && blob ? [blob] : [];});const contents = readBlobContents(gitRoot, unversioned);+ // #6712: a deterministic `concurrent_write` hold re-screens when its page's revision moves (a reconcile, an authorized delete).+ const watched = checked.flatMap(path => { const hold = holdByPath.get(path); return hold?.code === 'concurrent_write' && hold.page_id != null && hold.meta.page_revision ? [Number(hold.page_id)] : []; });+ const revisions = new Map(watched.length ? (await engine.executeRaw<{ id: number; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])',+ [sourceId, watched])).map(row => [Number(row.id), row.revision]) : []);for (const path of checked) {const hold = holdByPath.get(path), gitPath = toGitPath(path), blob = blobs.get(gitPath);const workingHold = working && (hold?.meta.working === true || !blob);- let changed = !hold || holdRescreenDue(hold, retry.has(path));+ // #6712 dependency edge: a hold that waits on an earlier entry's hold re-screens once that hold is gone.+ let changed = !hold || holdRescreenDue(hold, retry.has(path)) || (!!hold.meta.blocked_on && !holdByPath.has(hold.meta.blocked_on))+ || (hold.code === 'concurrent_write' && hold.page_id != null && !!hold.meta.page_revision && revisions.get(Number(hold.page_id)) !== hold.meta.page_revision);let present = !!blob;if (workingHold) {let bytes: Buffer | null = null;diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 43611cb3d2..3b8e6df66e 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -65,13 +65,12 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'source_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },{ code: 'cancelled', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same group is cancelled again after a rerun' },// #6643: refinements of `cancelled` / `revision_conflict` by the receipt's recorded cause; they take precedence over the code.- { code: 'knock_on', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same root request is named again after a rerun',- human_reason: 'This page only waited on another page of the same sync; the next sync re-freezes it by itself. Fix the root request the error names.' },+ // #6712 retired both producers (one page, one fate); the rows render what older builds wrote as superseded.+ { code: 'knock_on', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: superseded; an older gbrain cancelled this page for another page\'s failure and a plain sync re-freezes it' },{ code: 'run_replaced', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: another run of the source superseded this one and covers its pages' },{ code: 'outside_fence', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: a request published outside the cursor that admitted it',human_reason: 'A sync request was not the entry its cursor held (two drains of one cursor, or a writer defect). gbrain sync status --source <source> --json lists the live cursors; stop the extra drain (pause autopilot with gbrain autopilot pause) and report the fence snapshot the error carries.' },- { code: 'knock_on_exhausted', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: re-freezing did not get past the failing page',- human_reason: 'The same page kept being cancelled because an earlier page of the sync never committed. Fix the root request the error names, or raise sync.knock_on_refreeze_limit (per page) or sync.knock_on_run_limit (per sync), then rerun the sync; the per-page count resets when the page commits.' },+ { code: 'knock_on_exhausted', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: superseded; a plain sync resumes the entry an older gbrain stopped on' },{ code: 'sync_incomplete', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: an unfinished cursor resumes with the same command' },// Connection class: transport only; the cursor and manifest stand.{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex a4a372f90b..e95f2a1a8c 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -105,14 +105,23 @@ export function nextGroupSize(settings: BulkSettings, perMemberMs: number | nullreturn Math.max(1, Math.min(settings.size, Math.floor(budget / perMemberMs)));}+/** #6712: the page keys a sync member occupies (its slug, and its page id when it has one); two members sharing one depend on each other. */+export function dependencyKeys(member: Pick<WaiverEntry, 'slug' | 'pageId'>): string[] {+ return [`slug:${member.slug}`, ...(member.pageId !== null ? [`page:${member.pageId}`] : [])];+}+/*** Followers for a group: frozen in manifest order after the head, four at a* time, stopping at the first entry that is not groupable, was overtaken by* another cursor, would be waived (the waiver handles it as a head) or is held (#5988).+ * #6712 dependency edges: also at the first entry that shares a slug or page id with a member still in flight or held by+ * the run (`taken`: the head, the groups admitted ahead, the run's held entries, and the followers frozen so far), so a+ * delete and an import of one slug are never co-scheduled and the later one is frozen only after the earlier one settled.*/export async function freezeFollowers<P extends WaiverEntry & { rebound?: true }>(engine: BrainEngine, cursor: WaiverCursor & { entries: unknown[] }, config: GBrainConfig,- count: number, freezeAt: (index: number) => Promise<P | null>): Promise<P[]> {+ count: number, freezeAt: (index: number) => Promise<P | null>, taken: Iterable<string> = []): Promise<P[]> {const followers: P[] = [];+ const occupied = new Set(taken);for (let next = cursor.index + 1; followers.length < count && next < cursor.entries.length;) {const batch = Array.from({ length: Math.min(4, count - followers.length, cursor.entries.length - next) }, (_, i) => next + i);const frozen = await Promise.all(batch.map(async index => {@@ -120,7 +129,8 @@ export async function freezeFollowers<P extends WaiverEntry & { rebound?: true }return !entry || entry.rebound || !groupableIntent(entry.intent) || await wouldWaiveEntry(engine, { ...cursor, index }, entry, config) ? null : entry;}));for (const entry of frozen) {- if (!entry) return followers;+ if (!entry || dependencyKeys(entry).some(key => occupied.has(key))) return followers;+ for (const key of dependencyKeys(entry)) occupied.add(key);followers.push(entry);}next += batch.length;diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 0ddeb1f9e8..1830052d8e 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -47,6 +47,7 @@ import { isMultimodalEnabled } from '../sync.ts';import { VERSION } from '../../version.ts';import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';import { gitBlobOid, sha256 } from './digest.ts';+import { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';export const GIT_HOLD_OP = 'sync-hold';export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';@@ -114,6 +115,11 @@ export interface GitHoldMeta {stall?: PreparationStallMeta;/** #6278: the held entry is a deletion (the file is gone); discovery re-screens it on request or a gbrain change, not on its absence. */deleted?: true;+ /**+ * #6712 dependency edge: the path of an earlier entry of the same sync, sharing this entry's slug or page id, that was+ * held in that sync; this entry waits on it with the same code, and discovery re-screens it once that hold is gone.+ */+ blocked_on?: string;}/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */@@ -389,13 +395,16 @@ export async function readGitHoldListing(engine: Exec, sourceIds: string[], limi* parser regressions), or when the gbrain that wrote it read frontmatter or* screened fences with an older version than this one. #6278: a* `preparation_stalled` hold re-screens when the gbrain version changed (the- * stall was the owner's, not the file's); otherwise it waits for- * `sources retry-held`. #6529: a `managed_image_sync_unsupported` hold+ * stall was the owner's, not the file's), and #6712 on every sync until it+ * has been held `HOLD_ATTEMPTS_NEEDS_HUMAN` times (attempts count real+ * re-holds); past that it waits for `sources retry-held`. #6529: a `managed_image_sync_unsupported` hold* re-screens whenever multimodal embedding is on, since managed sync then* imports the image instead of holding it.*/export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'].includes(record.code)+ // #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.+ || (record.code === 'preparation_stalled' && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())|| record.meta.recovery_version < RECOVERY_VERSION|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)diff --git a/src/core/persistence/sync-knock-on.ts b/src/core/persistence/sync-knock-on.tsindex 86a8d50762..5aa69fb860 100644--- a/src/core/persistence/sync-knock-on.ts+++ b/src/core/persistence/sync-knock-on.ts@@ -2,12 +2,12 @@* #6643: a managed-sync page request that ended without committing only because another request of the same sync did* not commit (a knock-on), told apart from a page that really failed.*- * A knock-on never published anything: it was cancelled before its claim published (`cancelRows`, the bulk group's- * member cancel) or refused by a dependency validation before any write ("An earlier page of this sync did not- * commit."). It is therefore never a reason to block a sync: the run re-freezes its entry under a fresh request- * (sync-run.ts `recoverKnockOn`), and the checkpoint does not wait for it (`checkpoint-validation.ts`).+ * #6712 (one page, one fate) retired every producer: no page is cancelled or refused for another page's failure any+ * more. What stays is the legacy predicate over receipts older builds wrote: such a receipt published nothing, so the+ * terminal classifier renders it superseded and a resumed cursor that meets one re-freezes its entry in place+ * (sync-run.ts `refreezeInPlace`).*- * The canceller records why and which request it depended on in the receipt's `error_detail` (`origin:+ * Older cancellers recorded why and which request they depended on in the receipt's `error_detail` (`origin:* 'sync_knock_on'`), which outlives receipt compaction. Receipts written before #6643 carry no marker; they are matched* by the exact messages their producers wrote, and nothing else: an operator's cancel ("Cancelled before* publication."), an authority or restore cancel, and a compacted receipt with no message are never knock-ons.@@ -19,6 +19,7 @@ export type KnockOnReason = 'group_member' | 'window_predecessor' | 'predecessor| 'suffix_cancelled' | 'bulk_group' | 'window_dropped';export interface KnockOnDetail { origin: typeof SYNC_KNOCK_ON_ORIGIN; reason: KnockOnReason; root_request_id: string | null }+/** The marker older cancellers stamped (no producer since #6712); legacy fixtures build it. */export const knockOnDetail = (reason: KnockOnReason, rootRequestId: string | null | undefined): KnockOnDetail =>({ origin: SYNC_KNOCK_ON_ORIGIN, reason, root_request_id: rootRequestId ?? null });diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.tsindex 6af9c00976..ad7209a3c6 100644--- a/src/core/persistence/sync-page-fault.ts+++ b/src/core/persistence/sync-page-fault.ts@@ -36,7 +36,7 @@ import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry, type Synimport { readTreeBlobs } from './sync-blobs.ts';import type { SyncIntent } from './sync-prepare.ts';import type { HeldEntry } from './sync-screen.ts';-import type { GitHoldMeta } from './sync-holds.ts';+import type { GitHoldMeta, GitHoldRecord } from './sync-holds.ts';import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';export { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';@@ -79,6 +79,42 @@ export async function pageChangeProof(engine: Pick<BrainEngine, 'executeRaw'>, ireturn { request_id: writer.request_id, operation: writer.operation, revision: page.revision };}+/**+ * #6600: proof that a deletion entry the origin check refuses was already carried out: its exact page (the id and the+ * revision this sync enumerated) is soft-deleted, the revision was written by a committed, authorized delete of that+ * page in the same source incarnation, and no live page records the entry's origin. Such an entry settles as an+ * idempotent deletion and clears its hold; a live replacement at the origin, a revision that moved since enumeration or+ * any other writer keeps the hold.+ */+export async function idempotentDeletionProof(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; pageId: number | null;+ revision: string | null; sourcePath: string }): Promise<{ request_id: string } | null> {+ if (input.pageId === null || input.revision === null) return null;+ const [page] = await engine.executeRaw<{ revision: string; writer: string | null; deleted: boolean }>(+ 'SELECT knowledge_revision::text AS revision, revision_write_request_id::text AS writer, deleted_at IS NOT NULL AS deleted FROM pages WHERE id=$1 AND source_id=$2', [input.pageId, input.sourceId]);+ if (!page?.deleted || !page.writer || page.revision !== input.revision) return null;+ const [writer] = await engine.executeRaw<{ request_id: string; operation: string; kind: string | null; state: string; incarnation: string; page_id: number | null }>(+ `SELECT request_id::text, operation, intent->>'kind' AS kind, state, source_incarnation::text AS incarnation, page_id FROM persistence_requests WHERE id=$1::uuid`, [page.writer]);+ if (!writer || writer.state !== 'committed' || writer.incarnation !== input.incarnation || Number(writer.page_id) !== input.pageId+ || !(writer.operation === 'delete_page' || writer.kind === 'managed_sync_delete')) return null;+ const live = await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id<>$2 AND source_path=$3 LIMIT 1', [input.sourceId, input.pageId, input.sourcePath]);+ return live.length ? null : { request_id: writer.request_id };+}++/**+ * #6712 dependency edge: the hold of an entry whose slug or page id an earlier entry of the same sync shares, when that+ * entry was held in the sync: it takes the predecessor's code and waits on it (`meta.blocked_on`) instead of publishing+ * against a page whose earlier change never landed.+ */+export function dependentHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid'>,+ predecessor: { path: string; code: GitHoldRecord['code'] }): HeldEntry {+ const rename: SyncRename | undefined = entry.renameFrom ?? entry.renameHeld;+ return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: predecessor.code,+ message: `${entry.path} changes page ${slug}, which ${predecessor.path} changes earlier in the same sync, and ${predecessor.path} is held (${predecessor.code}); this file waits on it and the next sync after that hold clears imports it.`,+ upstream_version: typeof intent.content === 'string' ? sha256(intent.content) : null,+ meta: { recovery_version: RECOVERY_VERSION, ...(typeof intent.blobOid === 'string' ? { blob_oid: intent.blobOid } : {}), ...(entry.working ? { working: true } : {}),+ ...(rename ? { rename_from: rename } : {}), ...(entry.action === 'delete' ? { deleted: true as const } : {}), blocked_on: predecessor.path } };+}+/*** The page's current revision, soft-deleted pages included (a deletion advances the revision, and a new-file entry whose slug* a page now occupies has moved too); null when no row exists. For a hold that records what it observed.diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 8921dfbc22..1c238d121e 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -408,7 +408,7 @@ async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p:const [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,`The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);- const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? [], p.settled ?? null, p.total);+ const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? [], p.settled ?? null);if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,`Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `+ `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 3e886c07c1..8487d9209d 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -25,7 +25,8 @@ import { startClaimPhase } from './claim-phase.ts';import { screeningRequest } from './noop-kernel.ts';import { FINISH_BUDGET_MS, stampDrainStep } from './drain-step.ts';import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';-import { resolve } from 'node:path';+import { existsSync } from 'node:fs';+import { join, resolve } from 'node:path';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';@@ -39,9 +40,9 @@ import { principalKey, type WriteRequest } from './model.ts';import { readJournalLimits } from './limits.ts';import { assertManagedSyncAllowed } from './worktree-refresh.ts';import type { GBrainConfig } from '../config.ts';-import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';-import { cancelRowsUnderCursor, cancelWindow } from './sync-window.ts';-import { cursorFenceCause, isSyncKnockOn, knockOnDetail, knockOnRoot } from './sync-knock-on.ts';+import { admitGroup, dependencyKeys, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';+import { cursorFenceCause, isSyncKnockOn } from './sync-knock-on.ts';+import { classifyTerminal } from './terminal-classify.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { isContentRefusal } from '../import-screen.ts';@@ -53,13 +54,13 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';import { publicFailureDetail } from './publication-failure.ts';-import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';+import { dependentHold, fileChangedAfterAdmission, headCommittedBytes, idempotentDeletionProof, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';-import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';+import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';import { withScreeningPaths } from './screening-paths.ts';import { withBoundedReadSession } from './bounded-reads.ts';@@ -81,14 +82,12 @@ export interface ManagedSyncWriteDiagnostic {interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true;/** #5988: re-frozen in place from a failed content refusal; a second refusal of the same bytes stays blocked. */converted?: true;- /**- * #6643: re-frozen in place because the request before it at this index was a knock-on (`attempts` such re-freezes in- * a row at this index, `root` the request the last knock-on depended on). Kept apart from `converted`, so a knock-on- * never uses up the content/file-change allowance. The entry then publishes on its own (no group, no window).- */- knockOn?: { attempts: number; root: string | null }; }+ /** #6712: re-frozen in place after the run stopped on this entry (a transport or systemic fault, a legacy knock-on); the re-freezes in a row here. */+ stops?: number; }/** #5988: the frozen entry is held instead of admitted. #6340 `overtaken`: another cursor of the source imported the entry's page meanwhile (#5522), so the checkpoint accepts a source already at this target. */interface Held { hold: HeldEntry; overtaken?: true }+/** #6600: the frozen deletion was already carried out by a committed, authorized delete of its exact page (`idempotentDeletionProof`); it settles with no admission and clears its hold. */+interface Settled { settled: { path: string; request_id: string } }interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;@@ -104,14 +103,16 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authorityconvertedFromFailed?: string[];/** #6643: the indexes this cursor passed without a commit (waived or held), recorded from `settled.from` on; the checkpoint carries them. */settled?: SyncSettledIndexes;- /** #6643: knock-on re-freezes this run made (the per-run breaker), and checkpoint revivals. */- knockOns?: number; checkpointRevivals?: number;+ /** #6643: checkpoint revivals. */+ checkpointRevivals?: number;/**- * #6643: the window members this run dropped after an earlier page did not commit, each with the request whose- * failure dropped it (newest last, at most `DROPPED_KEPT`). A member already claimed when its window was cancelled- * can still validate later; the cursor fence names it a knock-on of `root` only from this record.+ * #6712: entries whose file changed after admission (`source_changed`), retried after the manifest's last entry instead+ * of slept on: each with its deferrals so far (at most `DEFER_PER_ENTRY`, then a `worktree_dirty` hold). `deferrals`+ * counts this run's deferrals (at most `DEFER_PER_RUN`).*/- dropped?: Array<{ requestId: string; root: string | null }>;+ deferred?: Array<{ index: number; attempts: number }>; deferrals?: number;+ /** #6712 dependency edges: the page keys (`dependencyKeys`) of entries this run held, with the held path and code; a later entry sharing one is held behind it. */+ heldKeys?: Record<string, { path: string; code: GitHoldCode }>;/** #6278 (1.5): the systemic breaker over this run's `preparation_stalled` receipts; recorded with the cursor CAS that consumes each. */breaker?: CursorBreaker;/** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */@@ -119,9 +120,10 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority/** #5984 bulk: the frozen head (also `pending`) and the members admitted with it, in manifest order. */group?: Pending[];/**- * #5984 admit-ahead: groups frozen and admitted after `group` while it publishes, in manifest order- * (at most one today). Each member's intent names the previous group's last request (`after`); a- * window group publishes only after that request committed, and is cancelled when it did not.+ * #5984 admit-ahead: groups frozen and admitted after `group` while it publishes, in manifest order. Each member's+ * intent names the previous group's last request (`after`), which orders lane commits. #6712: the members of a group+ * after one that did not commit lead the window too, so every admitted request's identity stays in the cursor until+ * its own receipt is read, whenever it commits.*/window?: Pending[][]; }export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }@@ -182,12 +184,6 @@ function stampProgress(prior: CursorProgress | undefined, fromIndex: number, indconst OP = 'managed-sync';type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });-const DROPPED_KEPT = 512;-/** #6643: `dropped` with every member of `window` recorded as dropped by `root`. */-function withDropped(dropped: Cursor['dropped'], window: Pending[][] | undefined, root: string | null): Cursor['dropped'] {- const members = (window ?? []).flat().map(member => ({ requestId: member.requestId, root }));- return members.length ? [...(dropped ?? []), ...members].slice(-DROPPED_KEPT) : dropped;-}/** A managed sync run stopped before admitting the current entry; the recorded failure lets --retry-failed rediscover. */function syncRunRefusal(code: RegistryCode, message: string, retry: Parameters<typeof checkpointRetryCommand>[0], cause: string): OperationError {return opError(code, message, `${cause} Pages committed earlier in this run stay committed. Check the source with the command in fix, then run: ${checkpointRetryCommand(retry)}`,@@ -272,11 +268,11 @@ async function currentCursor(engine: BrainEngine, key: string, cached: Cursor):return current;}/** The cursor after a waived entry: counted under `waived`, plus the #5751 kernel breakdown kept for `legacySkips`. */-function waivedCursor(cursor: Cursor, waived: NoopWaiver): Cursor {+function waivedCursor(cursor: Cursor, waived: NoopWaiver, index = cursor.index): Cursor {const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };- const next: Cursor = { ...cursor, index: cursor.index + 1, settled: settleIndex(cursor), counts: { ...cursor.counts,+ const passed: Cursor = { ...cursor }; delete passed.pending; delete passed.group;+ const next: Cursor = { ...settledPast(passed, index), counts: { ...cursor.counts,waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };- delete next.pending; delete next.group;if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;return next;@@ -317,7 +313,6 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], reafilesImported: cursor.index, bankedFiles: cursor.index,managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),- ...(cursor.knockOns ? { knockOns: { refrozen: cursor.knockOns } } : {}),...(cursor.counts.sizeStates?.total ? { size_states: cursor.counts.sizeStates } : {}),...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };@@ -333,7 +328,7 @@ function remember(snapshot: PageSnapshot | null | undefined, pending: Pending):return pending;}async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,- run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal; embedDeferred?: boolean }): Promise<Pending | Held> {+ run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal; embedDeferred?: boolean }): Promise<Pending | Held | Settled> {assertActive();const entry = cursor.entries[cursor.index];const retry = { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath };@@ -362,6 +357,11 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass}), engine.readPageSnapshot(entry.slug!, { sourceId: cursor.sourceId, includeDeleted: true })]);assertActive();if (occupant && 'originFault' in occupant) {+ if (entry.action === 'delete' && snapshot?.page.deleted_at != null && !existsSync(join(cursor.root, entry.path))) {+ const done = await idempotentDeletionProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId: entry.pageId ?? null, revision: entry.revision ?? null, sourcePath: entry.sourcePath });+ assertActive();+ if (done) return { settled: { path: entry.path, request_id: done.request_id } };+ }return { hold: await originFaultHold(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, entry, observed: snapshot, message: occupant.originFault.message }), overtaken: true };}let bytes: Buffer | null = null;@@ -500,13 +500,59 @@ const holdClear = (cursor: Cursor, path: string | null | undefined, observedAt:const heldWrite = (held: Cursor, hold: HeldEntry, observedAt: string) => (tx: BrainEngine) => writeGitHold(tx, { source_id: held.sourceId, incarnation: held.incarnation, ...hold,observed_at: observedAt, run_id: held.runId, mode: 'managed' });-/** #5988: the cursor one entry on, past a held entry (no request admitted for it). */-function advanceHeld(held: Cursor, converted?: string[]): Cursor {- const next: Cursor = { ...held, index: held.index + 1, settled: settleIndex(held), counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 },- ...(converted ? { convertedFromFailed: converted } : {}) };- delete next.pending;+/** #5988: the cursor past a held entry (no request admitted for it, or none committed); #6712: `index` may name a deferred entry. */+function advanceHeld(held: Cursor, converted?: string[], index = held.index): Cursor {+ const next: Cursor = { ...held, counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 }, ...(converted ? { convertedFromFailed: converted } : {}) };+ delete next.pending; delete next.group;+ return settledPast(next, index);+}+/**+ * #6712: the cursor with entry `index` settled without a commit: the cursor's own entry advances the cursor, a deferred+ * entry leaves the deferred list. Either way the index joins the settled ranges the checkpoint skips.+ */+function settledPast(cursor: Cursor, index: number): Cursor {+ if (index === cursor.index) return promoteWindow({ ...cursor, index: cursor.index + 1, settled: settleIndex(cursor) });+ const next: Cursor = { ...cursor, deferred: (cursor.deferred ?? []).filter(entry => entry.index !== index),+ settled: addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, index, index) };+ if (!next.deferred!.length) delete next.deferred;return next;}+/**+ * #6712: a cursor with no pending entry whose window starts at its index takes the window's first group as its group:+ * those requests were admitted after an entry the cursor has now passed, and are read, never frozen again.+ */+function promoteWindow(cursor: Cursor): Cursor {+ const [first, ...rest] = cursor.window ?? [];+ if (cursor.pending || !first?.length || first[0]!.intent.index !== cursor.index) return cursor;+ const next: Cursor = { ...cursor, pending: first[0], group: first };+ if (rest.length) next.window = rest; else delete next.window;+ return next;+}+/** #6712: the cursor past its committed pending entry: its own entry advances it, a deferred one leaves the deferred list (its receipt is its record). */+function committedPast(cursor: Cursor, pending: Pending): Cursor {+ const index = indexOf(cursor, pending);+ const next: Cursor = { ...cursor }; delete next.pending; delete next.group;+ if (index === cursor.index) return promoteWindow({ ...next, index: cursor.index + 1 });+ next.deferred = (cursor.deferred ?? []).filter(entry => entry.index !== index);+ if (!next.deferred.length) delete next.deferred;+ return next;+}+/** #6712: the entry a pending request was frozen for: the cursor's own, or a deferred one past the manifest end. */+const indexOf = (cursor: Cursor, pending: Pending) => typeof pending.intent.index === 'number' ? pending.intent.index : cursor.index;+const entryOf = (cursor: Cursor, pending: Pending) => cursor.entries[indexOf(cursor, pending)];+/** #6712: the cursor without `pending` and the group it heads; the window (later admitted requests) stays. */+function withoutPending(cursor: Cursor): Cursor {+ const base: Cursor = { ...cursor }; delete base.pending; delete base.group;+ return base;+}+/** #6600: the cursor past an idempotent deletion: counted as a waived delete, its index settled. */+const deletionSettled = (cursor: Cursor, index: number) => waivedCursor(withoutPending(cursor), { kind: 'delete', kernel: [] }, index);+/** #6712: the cursor with `hold`'s page keys recorded, so a later entry of the run that shares one is held behind it. */+function withHeldKeys(cursor: Cursor, hold: HeldEntry): Cursor {+ if (!hold.slug) return cursor;+ const keys = dependencyKeys({ slug: hold.slug, pageId: hold.page_id ?? null });+ return { ...cursor, heldKeys: { ...cursor.heldKeys, ...Object.fromEntries(keys.map(key => [key, { path: hold.path, code: hold.code }])) } };+}/** #6278: the terminal code an owner stamps on a request whose preparation never settled within its attempts (Lane A, consumer.ts). */export const PREPARATION_STALLED = 'preparation_stalled';@@ -518,87 +564,74 @@ const resumeArgsOf = (cursor: Cursor, run: { syncOptions: SyncCursorOptions; repmanagedSyncResumeArgs({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath });/**- * #6278 (1.2b): the hold gate. Before this change both converters waited until- * no request on the whole source was unfinished, so one stuck preparation or a- * stream of maintenance writes on other pages kept every hold pending forever.- *- * Invariant the source-wide wait protected, kept by this narrower one: no entry- * after the held one publishes a change that depends on the held entry's- * outcome (the same path or origin, either side of a rename, a delete of the- * same slug), and the cursor never checkpoints past an entry whose request is- * still unfinished. It holds because (1) the failed entry's obsolete admitted- * suffix (its group's later members, the admit-ahead window, this run's lane- * groups: every queued request of the run admitted after it) is cancelled- * first, so no successor of this run can publish against the held entry and- * no queued successor can wait behind a blocked root while this gate waits for- * it; (2) the gate then waits only for requests that are still active in that- * suffix (claimed, recovering, or carrying a recovery record) and for any- * unfinished or recovery-bearing request that names the entry's page by slug,- * page id, path, origin or rename endpoint (`UNFINISHED_PAGE_REQUEST_SQL`);- * (3) the predicate is evaluated inside the transaction that writes the hold- * and swaps the cursor, after taking the page keys and before the cursor row- * (the lock order every waiver and publication uses), so a same-page write- * admitted meanwhile either committed before the hold or waits behind it and- * re-reads the page. The checkpoint's own validation then finds every- * non-committed receipt of the run superseded (`convertedFromFailed` carries- * the failed receipt and every earlier uncommitted receipt at the same index)- * or committed by a later request at its index. A hold never turns a failed- * predecessor into a committed one; cancelled successors are re-frozen under a- * fresh dependency chain when the run continues.+ * #6278 (1.2b) / #6712: the hold gate. A failed entry's hold and the cursor step that settles its index commit in one+ * transaction (one cursor compare-and-swap), after the entry's page keys are locked and only while no unfinished or+ * recovery-bearing request names its page by slug, page id, path, origin or rename endpoint+ * (`UNFINISHED_PAGE_REQUEST_SQL`), so a same-page write admitted meanwhile either committed before the hold or waits+ * behind it and re-reads the page (the lock order every waiver and publication uses). Nothing after the entry depends+ * on it: dependency edges keep same-page entries apart (`freezeFollowers`, `heldKeys`), so the run's later requests are+ * neither cancelled nor waited for; they stay in the cursor's window and are settled by their own receipts. Every+ * failed receipt at the entry's index is recorded as converted. A hold never turns a failed request into a committed one.*/async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; assertActive: () => void;- observedAt: string; waitMs: number; failedId: string; base?: Cursor } & ({ hold: HeldEntry; refrozen?: undefined } | { hold?: undefined;- /** #6340: instead of a hold, the entry re-frozen under a fresh request (its file changed after admission); same gate, same conversion record. */- refrozen: Pending;- /** #6643: the re-freeze replaces a knock-on: the new pending carries this instead of `converted`, and the run counts it. */- knockOn?: { attempts: number; root: string | null } })): Promise<Cursor | 'pending'> {+ observedAt: string; waitMs: number; hold: HeldEntry; base?: Cursor }): Promise<Cursor | 'pending'> {const { cursor, key, pending, assertActive } = input;- const principal = cursor.authority.writer.principal;- const base: Cursor = input.base ?? { ...cursor }; delete base.group; delete base.window; delete base.pending;- const [failedRow] = await engine.executeRaw<{ sequence: string | number | null }>('SELECT sequence::text AS sequence FROM persistence_requests WHERE id=$1::uuid', [input.failedId]);- const after = failedRow?.sequence == null ? null : String(failedRow.sequence);+ const base: Cursor = input.base ?? withoutPending(cursor);+ const index = indexOf(cursor, pending);const keys = [{ sourceId: cursor.sourceId, slug: pending.slug }, ...(pending.intent.renameFrom && pending.intent.renameFrom.slug !== pending.slug ? [{ sourceId: cursor.sourceId, slug: pending.intent.renameFrom.slug }] : [])];const deadline = performance.now() + input.waitMs;- // #6643: the window and the run's queued suffix are cancelled only while the cursor still holds this entry, so a- // converter that lost the cursor swap to another drainer never cancels the replacement the winner admitted.- const fence = { cursorKey: key, expectedRequestId: cursor.pending?.requestId ?? pending.requestId, principal, worktreeId: cursor.binding.worktree_id };for (;;) {assertActive();- if (cursor.window?.length && !await cancelWindow(engine, cursor.window, principal, pending.requestId, fence)) return currentCursor(engine, key, cursor);- if (after !== null) {- const queued = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND state='queued'- AND ${SYNC_PAGE_KINDS_SQL} AND sequence>$3::bigint ORDER BY sequence`, [cursor.binding.worktree_id, cursor.runId, after]);- if (queued.length && !await cancelRowsUnderCursor(engine, fence, queued, knockOnDetail('suffix_cancelled', pending.requestId))) return currentCursor(engine, key, cursor);- }const saved = await engine.transaction(async tx => {assertActive();await tx.lockPageKeys(keys);- const [samePage, suffix] = await Promise.all([- tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending)),- after === null ? Promise.resolve([]) : tx.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND sequence>$3::bigint- AND ${SYNC_PAGE_KINDS_SQL} AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [cursor.binding.worktree_id, cursor.runId, after]),- ]);- if (samePage.length || suffix.length) return null;+ if ((await tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending))).length) return null;const stale = await tx.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2- AND ${SYNC_PAGE_KINDS_SQL} AND intent->>'index'=$3 AND state IN ('failed','cancelled','conflict')`, [cursor.binding.worktree_id, cursor.runId, String(cursor.index)]);+ AND ${SYNC_PAGE_KINDS_SQL} AND intent->>'index'=$3 AND state IN ('failed','cancelled','conflict')`, [cursor.binding.worktree_id, cursor.runId, String(index)]);const converted = [...new Set([...(cursor.convertedFromFailed ?? []), ...stale.map(row => row.request_id), pending.requestId])];- const dropped = withDropped(cursor.dropped, cursor.window, pending.requestId);- if (dropped) base.dropped = dropped;- const next: Cursor = input.hold ? advanceHeld(base, converted)- : input.knockOn ? { ...base, convertedFromFailed: converted, knockOns: (cursor.knockOns ?? 0) + 1,- pending: { ...input.refrozen, ...(pending.converted ? { converted: true as const } : {}), knockOn: input.knockOn } }- : { ...base, convertedFromFailed: converted, pending: { ...input.refrozen, converted: true } };- return writeCursor(tx, key, cursor, next, async inner => {- if (input.hold) await heldWrite(cursor, input.hold, input.observedAt)(inner);- await recordSyncConversion(inner, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: input.hold ? 'held' : 'refrozen' });+ return writeCursor(tx, key, cursor, withHeldKeys(advanceHeld(base, converted, index), input.hold), async inner => {+ await heldWrite(cursor, input.hold, input.observedAt)(inner);+ await recordSyncConversion(inner, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'held' });}, true);});- if (saved) { await faultPoint('sync:mid_checkpoint', { sourceId: cursor.sourceId }); return saved; }+ if (saved) { await faultPoint('sync:held_settled', { sourceId: cursor.sourceId, path: pending.intent.path ?? undefined }); return saved; }if (performance.now() >= deadline) return 'pending';await new Promise(resolve => setTimeout(resolve, 50));}}+/** #6712: an entry is retried after the manifest end this many times when its file keeps changing after admission, then held `worktree_dirty`. */+export const DEFER_PER_ENTRY = 3;+/** #6712: the most deferrals one run makes; past it a changed file is held at once. */+export const DEFER_PER_RUN = 200;+/**+ * #6712: an import whose file changed after admission (`source_changed`: the bytes moved between freeze and publication)+ * is deferred: the cursor passes it now and retries it under a fresh request after the manifest's last entry, instead of+ * sleeping on it or blocking the entries after it. Bounded per entry (`DEFER_PER_ENTRY`) and per run (`DEFER_PER_RUN`);+ * past either bound the entry is held `worktree_dirty` (the file keeps changing without settling). The deferral commits+ * in the cursor step that passes the entry, so a kill after it re-runs nothing twice. `revision_conflict` and+ * `concurrent_write` get no such retry: `freezeEntry`'s rebind-or-hold already rebinds only when the database content+ * equals the file, so no retry can overwrite a database-only write.+ */+async function deferChangedEntry(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; assertActive: () => void;+ observedAt: string; waitMs: number; base: Cursor }): Promise<Cursor | 'pending'> {+ const { cursor, pending, base } = input;+ const index = indexOf(cursor, pending), entry = entryOf(cursor, pending)!;+ const attempts = (cursor.deferred?.find(deferred => deferred.index === index)?.attempts ?? 0) + 1;+ if (attempts > DEFER_PER_ENTRY || (cursor.deferrals ?? 0) >= DEFER_PER_RUN) {+ let bytes: Buffer | null = null;+ try { bytes = readSyncFile(cursor.root, entry.path); } catch { /* the hold records no working hash */ }+ return holdUnderGate(engine, { ...input, hold: worktreeDirtyHold(entry, pending.slug, pending.pageId, { ...pending.intent, rawHash: bytes === null ? null : sha256(bytes) }) });+ }+ const passed: Cursor = index === base.index ? promoteWindow({ ...base, index: base.index + 1 }) : base;+ const next: Cursor = { ...passed, deferred: [...(base.deferred ?? []).filter(deferred => deferred.index !== index), { index, attempts }], deferrals: (base.deferrals ?? 0) + 1,+ convertedFromFailed: [...new Set([...(cursor.convertedFromFailed ?? []), pending.requestId])] };+ const saved = await saveCursor(engine, input.key, cursor, next, false, input.assertActive,+ tx => recordSyncConversion(tx, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'refrozen' }));+ await faultPoint('sync:retry_deferred', { sourceId: cursor.sourceId, path: entry.path });+ return saved;+}+/*** #5988 (E6): a cursor blocked by a failed content refusal converts in place* with its stored options: held when the screen holds the frozen entry,@@ -621,32 +654,39 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sconst previous = blocked.pending!;const failed = await getWriteRequest(engine, blocked.authority.writer.principal, previous.requestId);if (!failed || !['failed', 'conflict', 'cancelled'].includes(failed.state)) return blocked;- // #6643: a knock-on is re-frozen by the drain itself (settleFailedRequest → recoverKnockOn), with or without a screen.+ // #6712: a legacy knock-on is re-frozen in place by the drain itself (settleFailedRequest → refreezeInPlace).if (isSyncKnockOn(failed)) return blocked;- const entry = blocked.entries[blocked.index];+ const entry = entryOf(blocked, previous), index = indexOf(blocked, previous);+ const at = (cursor: Cursor): Cursor => ({ ...cursor, index });+ const holdWith = async (hold: HeldEntry, base?: Cursor) => {+ const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, ...(base ? { base } : {}) });+ return held === 'pending' ? blocked : held;+ };+ const settleWith = (base: Cursor, done: Settled) => saveCursor(engine, key, blocked, { ...deletionSettled(base, index), convertedFromFailed: [...(blocked.convertedFromFailed ?? []), previous.requestId] },+ false, assertActive, holdClear(blocked, done.settled.path, run.observedAt ?? new Date().toISOString()));if (preparationStalled(failed)) {if (blocked.companyPlan || previous.intent.kind === 'managed_sync_checkpoint' || !entry || entry.path !== previous.intent.path) return blocked;const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];if (blocked.breaker?.tripped) {// A run that tripped the breaker holds nothing: its stopped entry is re-frozen under a fresh request (the attempt// counter starts at zero) and the stalled holds it wrote before the trip are scheduled for a re-screen.- const base: Cursor = { ...blocked, convertedFromFailed: converted }; delete base.pending; delete base.breaker;- const again = await freezeEntry(engine, base, key, assertActive, run);+ const base: Cursor = { ...withoutPending(blocked), convertedFromFailed: converted }; delete base.breaker;+ const again = await freezeEntry(engine, at(base), key, assertActive, run);const rescreen = ((await readGitSourceHolds(engine, { sourceIds: [blocked.sourceId], runId: blocked.runId }))[0]?.holds ?? []).filter(hold => hold.code === PREPARATION_STALLED).map(hold => hold.path);const inTx = async (tx: BrainEngine) => {if (rescreen.length) await requestGitHoldRetry(tx, blocked.sourceId, blocked.incarnation, rescreen);if ('hold' in again) await heldWrite(blocked, again.hold, run.observedAt!)(tx);+ if ('settled' in again) await holdClear(blocked, again.settled.path, run.observedAt!)!(tx);await recordSyncConversion(tx, blocked.sourceId, blocked.incarnation, { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome: 'refrozen' });};- return saveCursor(engine, key, blocked, 'hold' in again ? advanceHeld(base, converted) : { ...base, pending: again }, false, assertActive, inTx);+ return saveCursor(engine, key, blocked, 'hold' in again ? withHeldKeys(advanceHeld(base, converted, index), again.hold)+ : 'settled' in again ? { ...deletionSettled(base, index), convertedFromFailed: converted } : { ...base, pending: again }, false, assertActive, inTx);}const breaker = breakerAfter(blocked, failed, run.screen!.policy);if (breaker.tripped) return saveCursor(engine, key, blocked, { ...blocked, breaker }, false, assertActive);- const hold = preparationStalledHold(entry, previous.slug, previous.pageId, failed, previous.intent.content ?? null, previous.intent.blobOid, resumeArgsOf(blocked, run));- const base: Cursor = { ...blocked, breaker }; delete base.pending; delete base.group; delete base.window;- const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id, base });- return held === 'pending' ? blocked : held;+ return holdWith(preparationStalledHold(entry, previous.slug, previous.pageId, failed, previous.intent.content ?? null, previous.intent.blobOid, resumeArgsOf(blocked, run)),+ { ...withoutPending(blocked), breaker });}const fence = fenceReceiptLocation(failed);const compacted = !fence && failed.compacted === true && failed.error_message == null && ['invalid_params', 'take_row_collision'].includes(failed.error_code ?? '');@@ -657,29 +697,23 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sif (hold) {// The file may have been committed meanwhile: a re-freeze then imports HEAD's bytes instead of holding the stale conflict.if (hold.code === 'worktree_dirty' && headCommittedBytes(blocked, entry.path)?.rawHash !== undefined) {- const base: Cursor = { ...blocked }; delete base.pending;- const again = await freezeEntry(engine, base, key, assertActive, run);+ const base = withoutPending(blocked);+ const again = await freezeEntry(engine, at(base), key, assertActive, run);+ if ('hold' in again) return holdWith(again.hold);+ if ('settled' in again) return settleWith(base, again);const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];- if ('hold' in again) {- const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold: again.hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id });- return held === 'pending' ? blocked : held;- }- return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive,+ return saveCursor(engine, key, blocked, { ...base, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive,tx => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation, { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome: 'refrozen' }));}- const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id });- return held === 'pending' ? blocked : held;+ return holdWith(hold);}}if (!fence && !compacted && !isContentRefusal(failed.error_code, failed.error_message)) return blocked;- const base: Cursor = { ...blocked }; delete base.pending;- const again = await freezeEntry(engine, base, key, assertActive, run);+ const base = withoutPending(blocked);+ const again = await freezeEntry(engine, at(base), key, assertActive, run);const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];- const holdWith = async (hold: HeldEntry) => {- const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id });- return held === 'pending' ? blocked : held;- };if ('hold' in again) return holdWith(again.hold);+ if ('settled' in again) return settleWith(base, again);const sameBytes = again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content;if (fence && sameBytes && again.intent.kind === 'managed_sync_import' && again.intent.content !== null && entry?.path === again.intent.path) {return holdWith(prepareTimeFenceHold(entry, again.slug, again.pageId, fence, again.intent.content, again.intent.blobOid));@@ -688,107 +722,80 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sconst unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [blocked.sourceId]);assertActive();if (unfinished.length) return blocked;- return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive,+ return saveCursor(engine, key, blocked, { ...base, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive,tx => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation, { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome: 'refrozen' }));}/**- * #6188 (E10): a page request of this run that failed with a fence refusal (or, #6194, a- * `revision_conflict` proven to come from a concurrent database-only write, or, #6278, a- * `preparation_stalled` receipt for an import or a delete) is held in the same run instead- * of blocking it (the single path, and a bulk group's failed member, which the group step- * leaves as the single pending entry). The hold waits behind the narrowed gate- * (`holdUnderGate`) within the run's wait budget; when a request that can still change the- * entry's outcome is running the run returns `partial` and the next run's start-of-run- * conversion holds the entry. The failed request is converted once (`convertedFromFailed`,- * so it no longer blocks the checkpoint), gets no failure-ledger row, and is logged as a- * conversion. Null when it is not such a receipt, when the entry is the checkpoint, or when- * the run does not hold files (`sync.holds=fail`, company-brain sources).+ * #6188 (E10) / #6712: a page request of this run that ended without committing on a positively classified page fault+ * is settled in the same run instead of blocking it (the single path, and a bulk group's failed member, which the group+ * step leaves as the single pending entry): a fence refusal, a `revision_conflict` proven to come from a concurrent+ * database-only write or whose page really moved, a pinned-worktree conflict (`worktree_dirty`) and a+ * `preparation_stalled` receipt are held behind the gate (`holdUnderGate`); a file that changed after admission is+ * deferred past the manifest end (`deferChangedEntry`). When a request that can still change the entry's outcome is+ * running the run returns `partial` and the next run's start-of-run conversion holds the entry. The failed request is+ * converted (`convertedFromFailed`, so it no longer blocks the checkpoint), gets no failure-ledger row, and is logged as+ * a conversion. Null when it is not such a fault, when the entry is the checkpoint, or when the run does not hold files+ * (`sync.holds=fail`, company-brain sources).*/async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key: string, pending: Pending, done: WriteRequest, assertActive: () => void,run: { screen?: SyncScreenRun | null; observedAt?: string; syncOptions: SyncCursorOptions; repoPath?: string }, waitMs: number): Promise<Cursor | 'pending' | { tripped: Cursor } | null> {if (!run.screen || cursor.companyPlan || pending.intent.kind === 'managed_sync_checkpoint') return null;- const entry = cursor.entries[cursor.index];+ const entry = entryOf(cursor, pending);if (!entry || entry.path !== pending.intent.path) return null;const stalled = preparationStalled(done);const page = pending.intent.kind === 'managed_sync_import' && typeof pending.intent.content === 'string';if (!stalled && !page && pending.intent.kind !== 'managed_sync_delete') return null;- let base: Cursor | undefined;+ let base = withoutPending(cursor);if (stalled) {// #6278 (1.5): the breaker counts the receipt first; at the trip the run stops and converts neither this receipt nor a later one.if (cursor.breaker?.tripped) return { tripped: cursor };const breaker = breakerAfter(cursor, done, run.screen.policy);if (breaker.tripped) return { tripped: await saveCursor(engine, key, cursor, { ...cursor, breaker }, false, assertActive) };- base = { ...cursor, breaker }; delete base.pending; delete base.group; delete base.window;+ base = { ...base, breaker };}const fence = stalled || !page ? null : fenceReceiptLocation(done);// #6194 (D4): a revision conflict proven to come from a concurrent database-only write is held the same way; #6340: so is one// whose page really moved with no proof of who moved it, and a pinned-worktree conflict (uncommitted local bytes) holds- // `worktree_dirty` (sync-page-fault.ts). A run-level revision conflict (the page is where it was) still blocks.+ // `worktree_dirty` (sync-page-fault.ts). A run-level revision conflict (the page is where it was) is not a page fault.const fault = stalled || fence ? null : await receiptPageFaultHold(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, entry, pending, done });- // #6340: the file changed after admission (a commit landed between freeze and publication on a live checkout): re-freeze the- // entry once under a fresh request (committed bytes import as HEAD has them; uncommitted ones reach the dirty hold above);- // a second change under the same entry is held, so a file that keeps changing never loops.- if (!stalled && !fence && !fault && page && fileChangedAfterAdmission(done)) {- const refrozen = await freezeEntry(engine, base ?? (() => { const b: Cursor = { ...cursor }; delete b.pending; delete b.group; delete b.window; return b; })(), key, assertActive, run);- assertActive();- if ('hold' in refrozen) return holdUnderGate(engine, { cursor, key, pending, hold: refrozen.hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });- if (pending.converted) return holdUnderGate(engine, { cursor, key, pending, hold: worktreeDirtyHold(entry, pending.slug, pending.pageId, { ...pending.intent, rawHash: refrozen.intent.rawHash }), assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });- return holdUnderGate(engine, { cursor, key, pending, refrozen, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });- }+ const observedAt = run.observedAt ?? new Date().toISOString();+ if (!stalled && !fence && !fault && page && fileChangedAfterAdmission(done)) return deferChangedEntry(engine, { cursor, key, pending, assertActive, observedAt, waitMs, base });if (!stalled && !fence && !fault) return null;const hold = stalled ? preparationStalledHold(entry, pending.slug, pending.pageId, done, pending.intent.content ?? null, pending.intent.blobOid, resumeArgsOf(cursor, run)): fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content!, pending.intent.blobOid) : fault!;- return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });+ return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt, waitMs, base });}-/** #6643: the terminal code of a run that stopped re-freezing knock-ons (per-index limit or per-run breaker). */-export const KNOCK_ON_EXHAUSTED = 'knock_on_exhausted';const CHECKPOINT_REVIVAL_LIMIT = 3;-/**- * #6643: `sync.knock_on_refreeze_limit`, knock-on re-freezes in a row at one index (default 3; 0 turns automatic- * re-freeze off), and `sync.knock_on_run_limit`, the most one run makes before it stops with the root cause (default- * 25 per sync invocation, a breaker like `breakerAfter`; the next invocation starts counting again).- */-export async function knockOnLimits(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ perIndex: number; perRun: number }> {- const read = async (key: string, fallback: number) => {- const raw = (await engine.getConfig(key).catch(() => null))?.trim();- const parsed = raw ? Number(raw) : NaN;- return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;- };- return { perIndex: await read('sync.knock_on_refreeze_limit', 3), perRun: await read('sync.knock_on_run_limit', 25) };-}-type SettleInput = Parameters<typeof settleFailedRequest>[1];-/** #6643: knock-on re-freezes per sync invocation (keyed by its run options object): `sync.knock_on_run_limit` bounds one invocation, and the next starts again. */-const knockOnsByRun = new WeakMap<object, number>();+/** #6712: an entry the run stopped on (a transport or systemic fault, a legacy knock-on) is re-frozen in place at most this many times in a row; then its failure stays recorded until --retry-failed. */+export const STOPS_PER_ENTRY = 3;/**- * #6643: the entry of a knock-on (a page cancelled or refused only because another page of its sync did not commit)- * is re-frozen under a fresh request, whatever the hold policy, the source kind or `--retry-failed`: a knock-on never- * published anything, so it is not a failure of its page. The re-freeze goes through the narrowed gate- * (`holdUnderGate`), which settles the run's suffix under the cursor fence and records every stale receipt at the- * index as superseded. Bounded per index (`sync.knock_on_refreeze_limit`) and per run (`sync.knock_on_run_limit`).+ * #6712: the entry of a request that did not commit and whose fault is not the page's (a transport fault proven by its+ * receipt, a systemic stop an earlier invocation recorded, or a legacy knock-on an older gbrain cancelled) is re-frozen in+ * place under a fresh request: the cursor does not advance past it and the failed receipt is recorded as converted+ * (`convertedFromFailed`), so it never blocks the checkpoint. Bounded by `STOPS_PER_ENTRY` re-freezes in a row at the+ * entry (`Pending.stops`); null past the bound, so the failure is recorded and stays until --retry-failed.*/-async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<null | 'pending' | { cursor: Cursor } | { exhausted: { attempts: number; limit: number; runCount: number; runLimit: number } }> {- const { cursor, key, pending, done, assertActive } = input;- if (pending.intent.kind === 'managed_sync_checkpoint' || !isSyncKnockOn(done)) return null;- const entry = cursor.entries[cursor.index];+async function refreezeInPlace(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {+ const { cursor, key, pending, assertActive } = input;+ if (pending.intent.kind === 'managed_sync_checkpoint' || (pending.stops ?? 0) >= STOPS_PER_ENTRY) return null;+ const entry = entryOf(cursor, pending), index = indexOf(cursor, pending);if (!entry || entry.path !== pending.intent.path) return null;- const limits = await knockOnLimits(engine);- if (limits.perIndex === 0) return null;- const attempts = pending.knockOn?.attempts ?? 0, runCount = knockOnsByRun.get(input.run) ?? 0;- if (attempts >= limits.perIndex || runCount >= limits.perRun) return { exhausted: { attempts, limit: limits.perIndex, runCount, runLimit: limits.perRun } };- const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;- knockOnsByRun.set(input.run, runCount + 1);- const refrozen = await freezeEntry(engine, base, key, assertActive, input.run);+ const base = withoutPending(cursor);+ const fresh = await freezeEntry(engine, { ...base, index }, key, assertActive, input.run);assertActive();+ const converted = [...new Set([...(cursor.convertedFromFailed ?? []), pending.requestId])];const observedAt = input.run.observedAt ?? new Date().toISOString();- const gated = 'hold' in refrozen- ? await holdUnderGate(engine, { cursor, key, pending, hold: refrozen.hold, assertActive, observedAt, waitMs: input.waitMs, failedId: done.id, base })- : await holdUnderGate(engine, { cursor, key, pending, refrozen, knockOn: { attempts: attempts + 1, root: knockOnRoot(done) ?? pending.knockOn?.root ?? null },- assertActive, observedAt, waitMs: input.waitMs, failedId: done.id, base });- return gated === 'pending' ? 'pending' : { cursor: gated };+ if ('settled' in fresh) return saveCursor(engine, key, cursor, { ...deletionSettled(base, index), convertedFromFailed: converted }, false, assertActive, holdClear(cursor, fresh.settled.path, observedAt));+ if ('hold' in fresh) {+ const held = await holdUnderGate(engine, { cursor, key, pending, hold: fresh.hold, assertActive, observedAt, waitMs: input.waitMs, base });+ return held === 'pending' ? null : held;+ }+ return saveCursor(engine, key, cursor, { ...base, convertedFromFailed: converted, pending: { ...fresh, stops: (pending.stops ?? 0) + 1 } }, false, assertActive,+ tx => recordSyncConversion(tx, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'refrozen' }));}/** #6643: checkpoint revivals per sync invocation (keyed by its run options object), so a refusal loop ends the invocation, never the cursor. */@@ -807,46 +814,55 @@ async function reviveCheckpoint(engine: BrainEngine, input: SettleInput): Promisconst refused = revivableCheckpointRefusal(done) || (pending.intent.kind === 'managed_sync_checkpoint' && await slugModeCheckpointRevivable(engine, cursor, pending.intent, done));const revivals = checkpointRevivalsByRun.get(input.run) ?? 0;if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;- const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;+ const base = withoutPending(cursor);const fresh = await freezeEntry(engine, base, key, input.assertActive, input.run);- if ('hold' in fresh) return null;- const blocker = await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null, cursor.entries.length);+ if (!('requestId' in fresh)) return null;+ const blocker = await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null);input.assertActive();if (blocker) return null;checkpointRevivalsByRun.set(input.run, revivals + 1);return saveCursor(engine, key, cursor, { ...base, checkpointRevivals: (cursor.checkpointRevivals ?? 0) + 1, pending: fresh }, false, input.assertActive);}+/** #6643: what caused a blocked checkpoint refused `recovery_required`: the receipt that blocks it. Null for a page (it is its own cause). */+async function syncRootCause(engine: BrainEngine, cursor: Cursor, pending: Pending, done: WriteRequest): Promise<ManagedSyncRootCause | null> {+ if (pending.intent.kind !== 'managed_sync_checkpoint' || done.error_code !== 'recovery_required') return null;+ const rootId = /request ([0-9a-f-]{36})/i.exec(done.error_message ?? '')?.[1];+ if (!rootId) return null;+ const row = await getWriteRequest(engine, cursor.authority.writer.principal, rootId);+ if (!row) return { request_id: rootId, slug: null, state: 'missing', code: null, message: null };+ const cause = cursorFenceCause(row.error_detail);+ return { request_id: row.request_id, slug: row.slug, state: row.state, code: row.error_code ?? null, message: row.error_message ?? null, ...(cause ? { cause } : {}) };+}+/**- * #6643: what caused a blocked entry. A knock-on names the request its canceller recorded, followed while that- * request is itself a knock-on; a checkpoint refused `recovery_required` names the receipt that blocks it. Null for a- * page that failed on its own (it is the root); `unknown` when the knock-on recorded no root.+ * #6712 (#6565): how the run treats a receipt that did not commit, from the terminal classifier: `transport` (a dropped+ * connection, a retryable or unavailable refusal) re-freezes in place now; `page` is a fault of the one entry (held when+ * positively classified, else it blocks under the hold policy); `systemic` (the engine-graduation fence, an unknown+ * P0001, schema skew, any refusal it cannot place) stops the run blocked with the classifier's action.*/-async function syncRootCause(engine: BrainEngine, cursor: Cursor, pending: Pending, done: WriteRequest): Promise<ManagedSyncRootCause | null> {- let rootId: string | null;- if (pending.intent.kind === 'managed_sync_checkpoint') {- if (done.error_code !== 'recovery_required') return null;- rootId = /request ([0-9a-f-]{36})/i.exec(done.error_message ?? '')?.[1] ?? null;- if (!rootId) return null;- } else if (isSyncKnockOn(done)) rootId = knockOnRoot(done) ?? pending.knockOn?.root ?? null;- else return null;- if (!rootId) return { request_id: null, slug: null, state: null, code: null, message: null, unknown: true };- const seen = new Set<string>();- for (;;) {- seen.add(rootId);- const row = await getWriteRequest(engine, cursor.authority.writer.principal, rootId);- if (!row) return { request_id: rootId, slug: null, state: 'missing', code: null, message: null };- const next = isSyncKnockOn(row) ? knockOnRoot(row) : null;- if (next && !seen.has(next) && seen.size < 8) { rootId = next; continue; }- const cause = cursorFenceCause(row.error_detail);- return { request_id: row.request_id, slug: row.slug, state: row.state, code: row.error_code ?? null, message: row.error_message ?? null, ...(cause ? { cause } : {}) };- }+function receiptClass(row: WriteRequest): 'transport' | 'page' | 'systemic' {+ if (row.recovery) return 'systemic';+ const kind = (row.intent as Record<string, unknown> | null)?.kind;+ const verdict = classifyTerminal({ request_id: row.request_id, source_id: row.source_id, slug: row.slug, operation: row.operation, state: row.state, error_code: row.error_code ?? null,+ error_detail: (row.error_detail ?? null) as object | null, recovery: row.recovery, blocked_reason: row.blocked_reason, compacted: row.compacted, publication_started: row.publication_started,+ intent_kind: typeof kind === 'string' ? kind : null, error_message: row.error_message ?? null });+ if (verdict?.category === 'transport' && verdict.code !== 'graduation_in_progress') return 'transport';+ return verdict?.class === 'page' ? 'page' : 'systemic';+}+/** #6712: whether an earlier invocation already stopped this run on `requestId` (its failure is recorded under the cursor key). */+async function stopRecorded(engine: BrainEngine, key: string, requestId: string): Promise<boolean> {+ return (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'observation_id'=$2", [key, requestId])).length > 0;}/**- * A page request of the run ended without committing. #6188: a fence refusal is held in the same- * run (or the run returns `partial` while the source's other requests settle); anything else is- * recorded in the failure ledger and blocks the run with its diagnostic.+ * A page request of the run ended without committing; #6712 routes it by its fault class (`receiptClass`, #6565): a+ * positively classified page fault is held with its index settled in one cursor step (`holdFailedFenceRequest`), or+ * deferred when its file changed after admission; a transport fault, or a legacy knock-on, is re-frozen in place without+ * advancing (`refreezeInPlace`); any other fault is recorded in the failure ledger and blocks the run with its+ * diagnostic and the classifier's action, and for a systemic fault the next invocation re-freezes the entry in place+ * (`stopRecorded`), so a plain sync converges once the cause is gone. Nothing after the entry is cancelled: requests+ * admitted after it stay in the cursor's window and are settled by their own receipts.*/async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; done: WriteRequest; assertActive: () => void;run: { screen?: SyncScreenRun | null; observedAt?: string; repoPath?: string; syncOptions: SyncCursorOptions }; syncOptions: SyncCursorOptions; processingOptions: SyncProcessingOptions;@@ -857,27 +873,26 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;const current = await currentCursor(engine, key, cursor);if (current.runId !== cursor.runId) return { cursor: current };}- const knockOn = await recoverKnockOn(engine, input);- if (knockOn === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };- if (knockOn && 'cursor' in knockOn) { input.assertActive(); return { cursor: knockOn.cursor }; }const revived = await reviveCheckpoint(engine, input);if (revived) { input.assertActive(); return { cursor: revived }; }- const converted = knockOn ? null : await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs);+ const fault = receiptClass(done);+ if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, key, pending.requestId))) {+ const refrozen = await refreezeInPlace(engine, input);+ if (refrozen) { input.assertActive(); return { cursor: refrozen }; }+ }+ const converted = fault !== 'transport' ? await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs) : null;if (converted === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };if (converted && 'tripped' in converted) return { result: breakerResult(converted.tripped, pending, done, remote) };if (converted) { input.assertActive(); return { cursor: converted }; }// #6513: a checkpoint another run superseded records nothing; this run goes on with the winning cursor as it stands.if (checkpointSuperseded(pending, done)) return { cursor: await currentCursor(engine, key, cursor) };const rootCause = await syncRootCause(engine, cursor, pending, done);- const exhausted = knockOn && 'exhausted' in knockOn ? knockOn.exhausted : null;const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',- code: exhausted ? KNOCK_ON_EXHAUSTED : done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'),- message: exhausted ? `This page was re-frozen ${exhausted.attempts} time(s) at the same index (sync.knock_on_refreeze_limit ${exhausted.limit}), or this run re-froze ${exhausted.runCount} knock-on page(s) (sync.knock_on_run_limit ${exhausted.runLimit}), and an earlier page of the same sync still did not commit; the run stopped instead of re-freezing again.`- : done.error_message ?? 'The accepted sync request did not commit.',+ code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',...(rootCause ? { root_cause: rootCause } : {}),request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,- phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: exhausted ? `${pending.requestId}:${KNOCK_ON_EXHAUSTED}` : pending.requestId,+ phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,first_seen: new Date(done.completed_at ?? done.updated_at).toISOString(), ...(done.error_detail ? { write_error_detail: publicFailureDetail(done.error_detail) } : {}) });// #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.const hint = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT && !remote ? await checkpointTimeoutHint(engine,@@ -1003,7 +1018,7 @@ async function screenWaiverRun(engine: BrainEngine, cursor: Cursor, head: Pendinextend: for (let next = cursor.index + 1; run.length < max && next < cursor.entries.length;) {const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));- const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound+ const screened = await Promise.all(frozen.map((entry, i) => entry && 'requestId' in entry && !entry.rebound? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config, frozenRun.signal,frozenSnapshots.has(entry as Pending) ? { snapshot: frozenSnapshots.get(entry as Pending)! } : undefined).catch(() => null) : null));for (const [i, waived] of screened.entries()) {@@ -1018,7 +1033,7 @@ async function screenWaiverRun(engine: BrainEngine, cursor: Cursor, head: Pendin/** #5984 bulk: freezes the followers of an eligible head and records them with it as the cursor's group. */async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,assertActive: () => void): Promise<Cursor> {- const followers = await freezeFollowers(engine, head, config, groupSize(head, bulk) - 1, freezeAt(head));+ const followers = await freezeFollowers(engine, head, config, groupSize(head, bulk) - 1, freezeAt(head), [...inFlight(head), ...dependencyKeys(pending)]);if (!followers.length) return head;// Members name their group (the head's request ID), so a consumer can claim them together.const lane = laneRunOf(head, bulk);@@ -1036,6 +1051,10 @@ async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, kereturn currentCursor(engine, key, head);}}+/** #6712: the page keys followers may not share: every request the cursor holds in flight (its pending entry, its group and the window admitted ahead) and every entry this run held. */+function inFlight(cursor: Cursor): string[] {+ return [...[...(cursor.pending ? [cursor.pending] : []), ...(cursor.group ?? []), ...(cursor.window ?? []).flat()].flatMap(dependencyKeys), ...Object.keys(cursor.heldKeys ?? {})];+}/** The size of the next group this pass forms: the drain's first group is small; lanes size by their measured apply time. */function groupSize(cursor: Cursor, bulk: BulkPass): number {const lanes = (bulk.settings.lanes ?? 1) > 1;@@ -1141,7 +1160,7 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulkconst size = Math.min(groupSize(base, bulk), room - formed.flat().length);if (size < 1) break;// A freeze refusal here is left for the single path to raise in order, after the publishing groups.- const frozen = await freezeFollowers(engine, base, config, size, freezeAt(base)).catch(() => []);+ const frozen = await freezeFollowers(engine, base, config, size, freezeAt(base), [...inFlight(current), ...formed.flat().flatMap(dependencyKeys)]).catch(() => []);if (!frozen.length) break;const after = (formed.at(-1) ?? window.at(-1) ?? current.group!).at(-1)!.requestId;formed.push(frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after, ...(lane ? { lane } : {}) } })));@@ -1175,7 +1194,8 @@ async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string/*** #5984 bulk: admits the cursor's group, waits for it and advances over the* committed prefix. A terminal failure leaves that member as the single- * pending entry, so the single path records and reports it.+ * pending entry, so the single path settles it by its fault class; #6712: the+ * members after it stay admitted at the head of the window.*/async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, wait: { waitMs: number; signal?: AbortSignal },drainStartedAt: number, onProgress: SyncOpts['onProgress'], ahead?: (cursor: Cursor) => Promise<Cursor>): Promise<{ cursor: Cursor } | { result: SyncResult }> {@@ -1251,16 +1271,14 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:const [promoted, ...rest] = next.window ?? [];if (promoted) { next.pending = promoted[0]; next.group = promoted; } else { delete next.pending; delete next.group; }if (rest.length) next.window = rest; else delete next.window;- } else { next.pending = stuck; if (failed) delete next.group; else next.group = members.slice(committed); }- // A failed page stops the run: groups admitted ahead of it are cancelled, never published after it.- // #6643: fenced on the cursor this pass read, and naming the stuck request as the cancelled groups' knock-on root.- if (failed && next.window) {- if (!await cancelWindow(engine, next.window, principal, stuck!.requestId, { cursorKey: key, expectedRequestId: cursor.pending!.requestId, principal, worktreeId: cursor.binding.worktree_id })) {- return { cursor: await currentCursor(engine, key, cursor) };- }- next.dropped = withDropped(next.dropped, next.window, stuck!.requestId);- delete next.window;- }+ } else if (failed) {+ // #6712: one page, one fate. The failed member becomes the single pending entry (the single path settles it by its+ // fault class); the members after it stay admitted and lead the window, so every admitted follower's identity stays+ // in the cursor until its own receipt is read, whenever it commits.+ next.pending = stuck; delete next.group;+ const rest = members.slice(committed + 1);+ if (rest.length) next.window = [rest, ...(next.window ?? [])];+ } else { next.pending = stuck; next.group = members.slice(committed); }const saved = committed || failed || next.group?.length !== members.length ? await saveCursor(engine, key, cursor, next) : cursor;for (let index = cursor.index + 1; index <= saved.index && index <= next.index; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length });if (stuck && stuckRow && !isTerminalWriteState(stuckRow.state) && saved.index === next.index) {@@ -1334,8 +1352,8 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: stringconst { opts, context, authority, processingOptions, syncOptions, assertActive } = input;const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;assertActive();- // #6643: a knock-on, and a checkpoint refused only by a receipt that no longer blocks it, recover in place in the drain- // (settleFailedRequest), which waits only on the narrowed gate; neither rediscovers the frozen manifest.+ // #6643/#6712: a legacy knock-on (re-frozen in place, `refreezeInPlace`) and a checkpoint refused only by a receipt that no+ // longer blocks it recover in the drain (settleFailedRequest); neither rediscovers the frozen manifest.if (failed && cursor.pending && (isSyncKnockOn(failed) || (cursor.pending.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)))) return null;const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);assertActive();@@ -1456,7 +1474,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);assertActive();- // #6643: a knock-on recovers in the drain (recoverKnockOn), which keeps its per-index and per-run budgets.+ // #6712: a legacy knock-on is re-frozen in place by the drain (refreezeInPlace), within its stop bound.if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) || !cursor.pending && !cursor.processingOptions)) {if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',@@ -1555,14 +1573,25 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP}foregroundWaitStart = 0;phase = 'freeze'; stampDrainStep('freeze', signal);- const frozen = await freezeEntry(engine, cursor, key, assertActive, frozenRun);+ // #6712: past the manifest's last entry, entries deferred because their file changed after admission are retried before the checkpoint.+ const deferredAt: number | undefined = cursor.index >= cursor.entries.length ? cursor.deferred?.[0]?.index : undefined;+ let frozen = await freezeEntry(engine, deferredAt === undefined ? cursor : { ...cursor, index: deferredAt }, key, assertActive, frozenRun);+ if ('settled' in frozen) {+ cursor = await saveCursor(engine, key, cursor, deletionSettled(cursor, deferredAt ?? cursor.index), false, assertActive, holdClear(cursor, frozen.settled.path, observedAt));+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true }); assertActive();+ continue;+ }+ // #6712 dependency edge: an entry sharing a slug or page id with one this run held waits on that hold.+ const blockedOn = 'requestId' in frozen ? dependencyKeys(frozen).map(page => cursor!.heldKeys?.[page]).find(Boolean) : undefined;+ const entryAt: SyncDiscovery['entries'][number] | undefined = cursor.entries[deferredAt ?? cursor.index];+ if (blockedOn && entryAt && 'requestId' in frozen) frozen = { hold: dependentHold(entryAt, frozen.slug, frozen.pageId, frozen.intent, blockedOn) };if ('hold' in frozen) {- cursor = await saveCursor(engine, key, cursor, { ...advanceHeld(cursor), ...(frozen.overtaken ? { overtaken: true as const } : {}) }, false, assertActive, heldWrite(cursor, frozen.hold, observedAt));+ cursor = await saveCursor(engine, key, cursor, { ...withHeldKeys(advanceHeld(cursor, undefined, deferredAt ?? cursor.index), frozen.hold), ...(frozen.overtaken ? { overtaken: true as const } : {}) }, false, assertActive, heldWrite(cursor, frozen.hold, observedAt));opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index }); assertActive();if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');continue;}- const waived: Cursor | null = waiveBatch && !frozen.rebound ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,+ const waived: Cursor | null = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');if (waived) { cursor = waived; continue; }@@ -1576,7 +1605,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP// #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.const screened: Cursor = cursor;const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,- (tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },+ (tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop, indexOf(screened, pending)), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened), signal);if (waived) {cursor = waived;@@ -1586,8 +1615,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPif (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');continue;}- const freezeAt: FreezeAt = base => async index => { const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'hold' in frozen ? null : frozen; };- if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && !pending.knockOn && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);+ const freezeAt: FreezeAt = base => async index => { const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'requestId' in frozen ? frozen : null; };+ if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);@@ -1642,7 +1671,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPfinishing(cursor); return withLinks(cursor, await finishCheckpoint(engine, key, cursor, !!company, assertActive));}// The frozen manifest is shared; only the cursor header changes per page.- const next: Cursor = { ...cursor, ...committedBreaker(cursor), index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete next.pending; delete next.group;+ const next: Cursor = committedPast({ ...cursor, ...committedBreaker(cursor), counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }, pending);countCommitted(next.counts, pending, done.outcome);cursor = await saveCursor(engine, key, cursor, next);opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 7f91f4b73a..d7942a6c28 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -261,7 +261,7 @@ export async function readCheckpointBlockers(engine: BrainEngine, sourceId: striasync function checkpointBlockers(engine: BrainEngine, header: CursorHeader | null): Promise<{ checkpoint_blockers: Array<Awaited<ReturnType<typeof listIncompleteSyncReceipts>>[number] & { knock_on: boolean }> }> {const intent = header?.pending?.intent;if (!header || header.done || intent?.kind !== 'managed_sync_checkpoint' || !header.binding?.worktree_id) return { checkpoint_blockers: [] };- const rows = await listIncompleteSyncReceipts(engine, header.binding.worktree_id, header.runId, intent.supersededRequests ?? [], intent.settled ?? null, Number(header.total));+ const rows = await listIncompleteSyncReceipts(engine, header.binding.worktree_id, header.runId, intent.supersededRequests ?? [], intent.settled ?? null);const knockOns = new Set(rows.length ? (await engine.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests rWHERE r.request_id::text = ANY($1::text[]) AND ${syncKnockOnSql('r')}`, [rows.map(row => row.request_id)])).map(row => row.request_id) : []);return { checkpoint_blockers: rows.map(row => ({ ...row, recovery: row.recovery === true, knock_on: knockOns.has(row.request_id) })) };