Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#6340): a file committed between admission and publication (raw_file_changed) is re-frozen once and imported as HEAD has it, held on a second change; writeDiagnostic moves to sync-write-diagnostic.ts

garrytanbe07108b5295
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a486c64345..f973035e1f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,7 @@ The operator loop (`docs/guides/sync-unblock-runbook.md`): `status` every N minu
| Where | What changed |
|---|---|
| A page edited, deleted or re-bound in the database after the manifest froze | Held as `concurrent_write` at freeze time (the hold records `page_revision` and `expected_revision`, and the competing request when #6194's proof finds one); the run finishes `synced` with the hold listed. A page that still holds exactly what the file would import is re-bound to its new revision and passed. A `revision_conflict` receipt whose page really moved converts the same way; a run-level conflict (the page is where it was) still blocks. |
+| A file committed between admission and publication (`source_changed` / `raw_file_changed`) | Re-frozen once under a fresh request: committed bytes import as HEAD has them, uncommitted ones reach the dirty hold; a file that changes again under the re-frozen request is held `worktree_dirty`, never a third request. |
| A file an agent is mid-edit on | Held with the new code `worktree_dirty` (the pinned blob and a hash of the working bytes; the local edit is never touched). A later commit that changes the file re-screens it on its own; `sync unblock --apply` re-screens it as soon as its bytes are committed at HEAD. Held three times, it is reported `needs_human`. |
| A file committed past the pinned target | Imported as HEAD has it (a commit is not an uncoordinated local edit); the pin..HEAD diff later re-imports the same bytes as a no-op. From PR #6323 by @garrytan-agents, moved to freeze time so no receipt is minted. |
| `write ECONNABORTED` / `ETIMEDOUT` / `EPIPE` mid-run | The drain reconnects and retries after 5, 15 and 45 s instead of exiting; a drop that then moves data is not even a warning. Three drops with no page committed between them stop the drain `connection_lost` with the resume command as a loopable `next`. Nothing is recorded against the source. |
@@ -53,7 +54,7 @@ The operator loop (`docs/guides/sync-unblock-runbook.md`): `status` every N minu
### Itemized changes
-- `src/core/persistence/sync-page-fault.ts` (new): `headCommittedBytes`, `pageChangeProof`, `pageChangedHold`, `worktreeDirtyHold`, `pinnedWorktreeConflict`, `pageMovedSinceAdmission`. `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws into holds (or a re-bind) when holds are on; `holdFailedFenceRequest` converts the pinned-worktree and moved-page receipts (imports and deletes); `convertBlockedCursor` converts an older release's blocked cursor and re-freezes a dirty file that is committed now; the `--retry-failed` start converts before it rediscovers; the catch skips the failure ledger for connection errors and statement timeouts.
+- `src/core/persistence/sync-page-fault.ts` (new): `headCommittedBytes`, `pageChangeProof`, `pageChangedHold`, `worktreeDirtyHold`, `originFaultHold`, `receiptPageFaultHold`, `pinnedWorktreeConflict`, `fileChangedAfterAdmission`, `pageMovedSinceAdmission`. `sync-write-diagnostic.ts` (new): `managedSyncWriteDiagnostic`, moved out of `sync-run.ts` unchanged. `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws into holds (or a re-bind) when holds are on; `holdFailedFenceRequest` converts the pinned-worktree and moved-page receipts (imports and deletes); `convertBlockedCursor` converts an older release's blocked cursor and re-freezes a dirty file that is committed now; the `--retry-failed` start converts before it rediscovers; the catch skips the failure ledger for connection errors and statement timeouts.
- `sync-holds.ts`: `worktree_dirty` code, `meta.attempts` (counted by `writeGitHold` per re-hold with the same code), `expected_revision`, `working_hash`, the `dirty` summary counter and repair route; `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the run's hold report route it.
- `retry-matcher.ts`: `ECONNABORTED`, `ETIMEDOUT`, `EPIPE`. `sync-drain.ts`: `isConnectionDrop`, `CONNECTION_RETRY_MS` (5/15/45 s), `CONNECTION_STRIKES`, `DrainInput.reconnect` (`engine.reconnect`), the `connection_lost` stop reason with `drain.connection` and a loopable `next`, `drainManagedSync`'s one extra pass with `drain.extra_pass`.
- `sync-fault-class.ts` (new): `SYNC_FAULT_TABLE` / `classifySyncFault`. `sync-status.ts` (new): `readSyncStatus`, `unblockSync`. `src/commands/sync/operator.ts` (new): `gbrain sync status`, `gbrain sync unblock` (routed in `sync/run.ts`; `cli.ts` skips the sync watchdog and serve delegations for them).
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index aa2ba17a6b..2f4ea08333 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -36,7 +36,8 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
-- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
+- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
+- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.
- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold, refuses `still_dirty`, `concurrent_write`, exhausted and repair-class holds by name with their fix, previews without `--apply`, and is idempotent. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` rendered through `renderAction`. Tests: `test/sync-status-unblock.test.ts`.
- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`.
- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index 5e14cf09ca..fc51577447 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -139,6 +139,12 @@ export function pinnedWorktreeConflict(done: Pick<WriteRequest, 'state' | 'error
&& ['Newer working-tree bytes and the current page disagree with this pinned Git import.', 'Newer code file bytes disagree with the pinned import.'].includes(done.error_message ?? '');
}
+/** The receipt of an import whose file bytes changed between admission and publication (`raw_file_changed` in verb-errors.ts). */
+export function fileChangedAfterAdmission(done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message'>): boolean {
+ return done.state !== 'committed' && done.error_code === 'source_changed'
+ && ['The imported file changed after sync admission.', 'The canonical file changed after preparation.', 'The canonical file changed during preparation.'].includes(done.error_message ?? '');
+}
+
/** A `revision_conflict` receipt whose page really moved (its live revision differs from the frozen one); run-level conflicts stay blocking. */
export async function pageMovedSinceAdmission(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, pending: { slug: string; pageId: number | null; intent: Pick<SyncIntent, 'expected_revision'> },
done: Pick<WriteRequest, 'state' | 'error_code'>): Promise<{ revision: string | null } | null> {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 4543398732..73904cc137 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -43,7 +43,8 @@ import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
-import { headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold } from './sync-page-fault.ts';
+import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
+import { fileChangedAfterAdmission, headCommittedBytes, 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';
@@ -290,35 +291,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
}
-function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): ManagedSyncWriteDiagnostic {
- const terminal = isTerminalWriteState(row.state);
- const code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';
- const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',
- 'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes',
- 'preparation_deadline', 'group_member_waiting'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';
- const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {
- reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',
- suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',
- };
- const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,
- path: pending.intent.path, write_error: code, ...detail, write_request: publicWriteReceipt(receiptFor(row)) };
- // #6194: an import that lost to a database write the hold could not prove; --retry-failed re-imports the Git version over it.
- if (terminal && code === 'revision_conflict' && pending.intent.kind === 'managed_sync_import') diagnostic.suggestion = `The page changed in the database after this import was frozen. `
- + `Before retrying, compare the file and the page with gbrain sources reconcile ${cursor.sourceId} ${pending.slug} --preview (it writes nothing): a retry re-imports the Git version over the database one. ${diagnostic.suggestion}`;
- if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. Skipping failures cannot bypass a managed write.`;
- if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {
- try {
- const bytes = readSyncFile(cursor.root, pending.intent.path);
- if (bytes && sha256(bytes) === pending.intent.rawHash && sha256(bytes) !== sha256(pending.intent.content)
- && bytes.equals(Buffer.from(bytes.toString('utf8')))
- && bytes.toString('utf8').replace(/\r\n/g, '\n') === pending.intent.content.replace(/\r\n/g, '\n')) {
- diagnostic.line_endings = 'crlf_lf_only';
- diagnostic.message += ' The frozen working-tree and Git versions differ only by CRLF/LF line endings; exact byte protection still applies.';
- }
- } catch {}
- }
- return diagnostic;
-}
+const writeDiagnostic = (cursor: Cursor, pending: Pending, row: WriteRequest) => managedSyncWriteDiagnostic({ sourceId: cursor.sourceId, root: cursor.root, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null }, pending, row);
/**
* #5984 G3: the page snapshot each frozen entry was validated against, read right before its sync authority check;
* a waiver run's screen of that entry uses it instead of reading the page and the authority again.
@@ -540,8 +513,10 @@ const resumeArgsOf = (cursor: Cursor, run: { syncOptions: SyncCursorOptions; rep
* predecessor into a committed one; cancelled successors are re-frozen under a
* fresh dependency chain when the run continues.
*/
-async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; hold: HeldEntry; assertActive: () => void;
- observedAt: string; waitMs: number; failedId: string; base?: Cursor }): Promise<Cursor | 'pending'> {
+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 })): 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;
@@ -569,9 +544,10 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:
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)]);
const converted = [...new Set([...(cursor.convertedFromFailed ?? []), ...stale.map(row => row.request_id), pending.requestId])];
- return writeCursor(tx, key, cursor, advanceHeld(base, converted), 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' });
+ const next: Cursor = input.hold ? advanceHeld(base, converted) : { ...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' });
}, true);
});
if (saved) { await faultPoint('sync:mid_checkpoint', { sourceId: cursor.sourceId }); return saved; }
@@ -705,6 +681,16 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:
// 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.
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 });
+ }
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!;
diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.ts
new file mode 100644
index 0000000000..a15de27a45
--- /dev/null
+++ b/src/core/persistence/sync-write-diagnostic.ts
@@ -0,0 +1,46 @@
+/**
+ * The `managedWrite` diagnostic of a managed sync result: what a page request's terminal receipt (or its pending state)
+ * means for the operator, with the retry command and, for a pinned-worktree conflict, whether only line endings differ.
+ * Moved out of `sync-run.ts` unchanged (#6340 kept that module under its size cap).
+ */
+import type { ManagedSyncWriteDiagnostic } from './sync-run.ts';
+import type { SyncCursorOptions, SyncIntent } from './sync-prepare.ts';
+import type { WriteRequest } from './model.ts';
+import type { SyncProcessingOptions } from './sync-authority.ts';
+import { isTerminalWriteState, publicWriteReceipt } from './types.ts';
+import { receiptFor } from './journal.ts';
+import { writeFailureDiagnostic } from './verb-errors.ts';
+import { checkpointRetryCommand } from './checkpoint-validation.ts';
+import { readSyncFile } from './sync-discovery.ts';
+import { sha256 } from './digest.ts';
+
+export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: string; processingOptions?: SyncProcessingOptions; syncOptions: SyncCursorOptions | null },
+ pending: { slug: string; intent: SyncIntent }, row: WriteRequest): ManagedSyncWriteDiagnostic {
+ const terminal = isTerminalWriteState(row.state);
+ const code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';
+ const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',
+ 'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes',
+ 'preparation_deadline', 'group_member_waiting'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';
+ const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {
+ reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',
+ suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',
+ };
+ const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,
+ path: pending.intent.path, write_error: code, ...detail, write_request: publicWriteReceipt(receiptFor(row)) };
+ // #6194: an import that lost to a database write the hold could not prove; --retry-failed re-imports the Git version over it.
+ if (terminal && code === 'revision_conflict' && pending.intent.kind === 'managed_sync_import') diagnostic.suggestion = `The page changed in the database after this import was frozen. `
+ + `Before retrying, compare the file and the page with gbrain sources reconcile ${cursor.sourceId} ${pending.slug} --preview (it writes nothing): a retry re-imports the Git version over the database one. ${diagnostic.suggestion}`;
+ if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. Skipping failures cannot bypass a managed write.`;
+ if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {
+ try {
+ const bytes = readSyncFile(cursor.root, pending.intent.path);
+ if (bytes && sha256(bytes) === pending.intent.rawHash && sha256(bytes) !== sha256(pending.intent.content)
+ && bytes.equals(Buffer.from(bytes.toString('utf8')))
+ && bytes.toString('utf8').replace(/\r\n/g, '\n') === pending.intent.content.replace(/\r\n/g, '\n')) {
+ diagnostic.line_endings = 'crlf_lf_only';
+ diagnostic.message += ' The frozen working-tree and Git versions differ only by CRLF/LF line endings; exact byte protection still applies.';
+ }
+ } catch {}
+ }
+ return diagnostic;
+}
diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.ts
index 59722144ba..42f255a36f 100644
--- a/test/managed-sync-page-fault-holds.test.ts
+++ b/test/managed-sync-page-fault-holds.test.ts
@@ -285,3 +285,44 @@ test('when HEAD moves past the pinned target during the run, the drain takes exa
expect(quiet.status).toBe('up_to_date'); expect(quiet.drain?.extra_pass).toBeUndefined();
}
}), 120_000);
+
+test('a file committed between admission and publication (raw_file_changed) is re-frozen once and imported as HEAD has it; a file that changes again is held', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.') });
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));
+ const pin = commit(f.root, 'version two');
+ // The admission transaction's last statement re-checks the cursor still holds this entry (ENG-A7). Right after it, for b.md,
+ // another agent commits version three: publication then finds the file's bytes changed after admission.
+ const executeRaw = engine.executeRaw;
+ let commits = 0, versions = 0;
+ const armed = (sql: string, params?: unknown[]) => sql.includes("completed_keys->0->'pending'->>'requestId' AS request_id") && sql.includes('FOR SHARE') && String(params?.[2] ?? '').includes('"path":"b.md"');
+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
+ const rows = await executeRaw.call(this, sql, params);
+ if (armed(sql, params) && commits < versions) { writeFileSync(join(f.root, 'b.md'), note(`b round ${versions} change ${commits}, committed after admission.`)); commit(f.root, `b moves after admission ${commits}`); commits++; }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ versions = 1;
+ const once = await performManagedSync(engine, { ...f.opts, noBulk: true });
+ expect(once).toMatchObject({ status: 'synced', toCommit: pin });
+ expect(once.held ?? []).toEqual([]);
+ expect(once.converted_from_failed).toHaveLength(1);
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 1 change 0');
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
+ // A file that moves again under its re-frozen request is held (never a third request for the same entry).
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} four.`));
+ const pin4 = commit(f.root, 'version four');
+ commits = 0; versions = 2;
+ const twice = await performManagedSync(engine, { ...f.opts, noBulk: true });
+ expect(twice).toMatchObject({ status: 'synced', toCommit: pin4, held_count: 1, held: [{ path: 'b.md', code: 'worktree_dirty' }] });
+ expect(commits).toBe(2);
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 1 change 0');
+ // The next sync re-screens the hold (the blob at HEAD differs from the hold's) and imports the latest commit.
+ const settled = await performManagedSync(engine, { ...f.opts, noBulk: true });
+ expect(settled.status).toBe('synced');
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('b round 2 change 1');
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
+ } finally { engine.executeRaw = executeRaw; await disposePersistenceConsumer(engine); }
+ }
+}), 120_000);