Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a pinned import's canonical correction no longer deadlocks the managed cursor on newer working-tree bytes (#6513)

garrytan698b2a68a56b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb9e2da9a2..c33d8f19ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.179.0] - 2026-10-12
+
+**A managed sync cursor can no longer deadlock on its own canonical correction (#6513).** On a live checkout, a pinned import whose sanitization (a fixable fence, reflowed frontmatter) has to rewrite the file used to refuse `source_changed` / `pinned_git_worktree_conflict` ("Canonical sanitization cannot overwrite newer working-tree bytes.") when the file already held newer uncommitted bytes, and that refusal blocked the cursor with no exit: `--retry-failed` replayed the same pin against the same bytes, `sources refresh` refused `sync_in_progress` on the unfinished cursor, `--acknowledge-managed` refused `cursor_unfinished`, and doctor called the cursor `resumable`. The production brain's `default` source went 38 hours without a sync and recurred the same day; the only way out was deleting `op_checkpoints` rows by hand. The refusal is now the `worktree_dirty` hold the other pinned-worktree conflict already earned (#6340): the file is held, the local edit is untouched, the rest of the source syncs and the cursor finishes, so the checkout is movable again; committing the file (or `gbrain sync unblock --source <id> --apply`) imports it with its correction, and a file committed at HEAD meanwhile is re-frozen and imported as HEAD has it. A cursor an older release left blocked this way converts in place on its next `--retry-failed` run, without rediscovery. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are no longer a conflict: the page imports and the file is left as it is.
+
+### Itemized changes
+
+- **The canonical-writeback refusal holds the page, not the run.** `pinnedWorktreeConflict` (`sync-page-fault.ts`) recognizes the sync-prepare.ts sanitization refusal, so the run's receipt branch, the start-of-run conversion of an older blocked cursor and the `--retry-failed` conversion all turn it into a `worktree_dirty` hold whose message names the canonical correction; the hold carries the pinned blob and the working hash as before, counts attempts, and clears when the file is committed and re-screened.
+- **An already-applied correction is not a conflict.** When the working-tree bytes hash to exactly the canonical file this import would write, the import proceeds with no file write (`sync-prepare.ts`); any other newer bytes are protected as before.
+- Tests: `test/managed-sync-page-fault-holds.test.ts` adds the three probes on PGLite and Postgres (live run held and cleared by the commit, already-applied writeback, older blocked cursor converted under `--retry-failed`); each fails on the previous release.
+- Docs: [write refusals](docs/guides/write-refusals.md#worktree_dirty) describes the new hold case.
+
+Fixes #6513.
+
## [0.60.178.0] - 2026-10-12
**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 996143692c..08079e7712 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -163,7 +163,7 @@ with each file and fix the ones that need no guessing."*
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
| <a id="preparation_stalled-hold"></a>`preparation_stalled` | The write for this file could not finish *preparing* within its attempt limit, so the sync held the file and kept going. The file is fine: no repair applies, and it is not imported until it is retried. Full reference: [`preparation_stalled`](#preparation_stalled). | `gbrain sources writer status --source <source> --json` (read-only), fix what it names, then `gbrain sources retry-held <source>` and the same sync with its options. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
-| <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |
+| <a id="worktree_dirty"></a>`worktree_dirty` | The working tree holds uncommitted bytes for this file that match neither the pinned commit nor the current page (an agent mid-edit on a live checkout), and importing the pinned version would discard them (#6340). Before this release the refusal (`source_changed` / `pinned_git_worktree_conflict`) stopped the whole run; now the file is held, the local edit is untouched and the rest of the source syncs. The hold keeps the pinned blob (`meta.blob_oid`) and a hash of the working bytes, counts `meta.attempts` each time the same file is held again, and a page held three times is reported `needs_human` by `gbrain sync status`. Bytes that are **committed at HEAD** past the pinned target are not a conflict at all: sync imports them as HEAD has them and the later pin..HEAD diff re-imports the same bytes as a no-op. Since 0.60.179.0 (#6513) the same hold covers a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: that refusal used to block the cursor with no exit, because `--retry-failed` replays the same pin against the same bytes, `sources refresh` refuses `sync_in_progress` on the unfinished cursor and `--acknowledge-managed` refuses `cursor_unfinished`. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are not a conflict either: the page imports and the file is left as it is. | Commit the edit (or restore the file), then `gbrain sync unblock --source <source> --apply` re-screens every held file that is now committed and prints the sync to run (`gbrain sources retry-held <source>` does the same for all holds). A later commit that changes the file re-screens it on its own. Never discard or normalize the local bytes. Runbook: [sync unblock](sync-unblock-runbook.md). |
| <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |
| <a id="takes_holder_invalid"></a>takes holder (`invalid_params`) | `takes_add`, or `takes_supersede` with an explicit `holder`, was given a holder the takes fence cannot carry: empty, whitespace, or not `world`, `brain`, `people/<slug>` or `companies/<slug>` (a legacy bare slug is accepted). The value is trimmed first, so `" world "` is stored as `world`. Nothing was written: before this release such a holder was published into the fence and every later takes write on that page was refused `target_fence_malformed`. A supersede without an override keeps the row's stored holder. A page whose stored holder is already malformed still refuses every takes write (`invalid_fence`); `gbrain repair fences` is the way out. | Resend with a holder in that grammar (`holder: me` on the brain host resolves the owner's holder). For a page already carrying a malformed holder, preview `gbrain repair fences --slug <slug>` and apply it, or edit the `who` cell by hand. Format: [holders](fence-format.md#holders). |
| <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`, `gbrain repair content --apply --expect <h1>[,<h2>]`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash (for the content lane, one hash per kind in lane order). For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 13077c7ba1..2f7cb0dcdd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -467,6 +467,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },
// Fix wave 15 group 1 (managed sync authority and data safety).
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
+ { since: '0.60.179.0', text: 'A managed sync no longer parks forever on a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: the file is held `worktree_dirty` with the rest of the source synced, the cursor finishes, and committing the file (or `gbrain sync unblock --source <id> --apply`) imports it. Before, that refusal (`source_changed` / `pinned_git_worktree_conflict`, "Canonical sanitization cannot overwrite newer working-tree bytes.") blocked the cursor with no exit: `--retry-failed` replayed the same pin, `sources refresh` refused `sync_in_progress` and `--acknowledge-managed` refused `cursor_unfinished`. A cursor an older release left blocked this way converts on its next `--retry-failed` run. Working-tree bytes that already are the correction (gbrain\'s own writeback, published before its request settled) import without a second write.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index fc51577447..d686a4228a 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -126,17 +126,27 @@ export function pageChangedHold(entry: HoldEntry, slug: string, pageId: number |
* so discovery re-screens the hold when a later commit changes the file, and `sources retry-held` re-screens it once
* the edit is committed.
*/
-export function worktreeDirtyHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid' | 'rawHash'>): HeldEntry {
+export function worktreeDirtyHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid' | 'rawHash'>,
+ conflict: 'page' | 'writeback' = 'page'): HeldEntry {
+ const what = conflict === 'writeback' ? `has uncommitted working-tree bytes newer than the pinned commit, which the import's canonical correction would overwrite`
+ : 'has uncommitted working-tree bytes that match neither the pinned commit nor the current page';
return base(entry, slug, pageId, 'worktree_dirty',
- `${entry.path} has uncommitted working-tree bytes that match neither the pinned commit nor the current page, so its import is held and the rest of the source synced; the local edit was not overwritten. Commit the file (or restore it) and the next sync imports it.`,
+ `${entry.path} ${what}, so its import is held and the rest of the source synced; the local edit was not overwritten. Commit the file (or restore it) and the next sync imports it.`,
typeof intent.content === 'string' ? intent.content : null, typeof intent.blobOid === 'string' ? intent.blobOid : null,
{ ...(intent.rawHash ? { working_hash: intent.rawHash } : {}) });
}
-/** The receipt of a `managed_sync_import` that publication refused as `pinned_git_worktree_conflict` (sync-prepare.ts `newerWorkingTree`). */
+/** The sync-prepare.ts refusal of a canonical correction (writeback) whose target file holds newer uncommitted bytes (#6513). */
+export const CANONICAL_WRITEBACK_CONFLICT = 'Canonical sanitization cannot overwrite newer working-tree bytes.';
+
+/**
+ * The receipt of a `managed_sync_import` that publication refused as `pinned_git_worktree_conflict`: sync-prepare.ts
+ * `newerWorkingTree`, or (#6513) its canonical-writeback refusal, which until then blocked the cursor with no exit
+ * because `--retry-failed` replays the same pin against the same newer bytes.
+ */
export function pinnedWorktreeConflict(done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message'>): boolean {
return done.state !== 'committed' && done.error_code === 'source_changed'
- && ['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 ?? '');
+ && ['Newer working-tree bytes and the current page disagree with this pinned Git import.', 'Newer code file bytes disagree with the pinned import.', CANONICAL_WRITEBACK_CONFLICT].includes(done.error_message ?? '');
}
/** The receipt of an import whose file bytes changed between admission and publication (`raw_file_changed` in verb-errors.ts). */
@@ -167,7 +177,7 @@ export async function receiptPageFaultHold(engine: Pick<BrainEngine, 'executeRaw
if (proof) return concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof);
const moved = await pageMovedSinceAdmission(engine, input.sourceId, pending, done);
if (moved) return pageChangedHold(entry, pending.slug, pending.pageId, pending.intent, { proof: null, revision: moved.revision, why: `page ${pending.slug} changed in the database` });
- return page && pinnedWorktreeConflict(done) ? worktreeDirtyHold(entry, pending.slug, pending.pageId, pending.intent) : null;
+ return page && pinnedWorktreeConflict(done) ? worktreeDirtyHold(entry, pending.slug, pending.pageId, pending.intent, done.error_message === CANONICAL_WRITEBACK_CONFLICT ? 'writeback' : 'page') : null;
}
/**
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index deb748be81..7d94cdaf14 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -556,7 +556,11 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
// #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.
enterClaimStep(clock, 'mirror_check', undefined, 'db');
const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);
- const writeback = overlay && !mirrorReadOnly;
+ const canonicalFile = overlay && !mirrorReadOnly ? serializePageToMarkdown(renderedPage, tags) : null;
+ // #6513: working-tree bytes that already are this import's canonical correction (gbrain's own writeback, published
+ // before the request that carried it settled) need no second write; any other newer bytes are protected as before.
+ const writebackApplied = canonicalFile !== null && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && p.rawHash === sha256(canonicalFile);
+ const writeback = canonicalFile !== null && !writebackApplied;
if (writeback && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw syncPublicationRefusal('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.', row, p,
`The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
@@ -568,7 +572,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
validate: async tx => { await validate(tx); await ready.validate(tx); },
deferEmbedding: p.processingOptions?.noEmbed,
- ...(writeback ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
+ ...(writeback ? { file: { root, path: join(root, p.path), content: canonicalFile!, expectedBeforeHash: p.rawHash } } : {}),
...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),
apply: async (tx, preimage) => {
let applied = ready;
diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.ts
index 42f255a36f..a87d19680b 100644
--- a/test/managed-sync-page-fault-holds.test.ts
+++ b/test/managed-sync-page-fault-holds.test.ts
@@ -144,6 +144,102 @@ test('an uncommitted edit under the catch-up is held worktree_dirty with the pin
}
}), 120_000);
+// #6513: a pinned import whose canonical correction (a fixable facts fence: `partnership` maps to `fact`) must rewrite the
+// file, when the file already holds newer uncommitted bytes.
+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+const fixable = (body = 'A synthetic page.') => `---\ntitle: Fixable\n---\n${body}\n\n${FB}\n${FH}\n| 1 | Sentinelzq8 partners with an example vendor | partnership | 1.0 | private | medium | 2026-01-01 | | chat | |\n${FBE}\n`;
+const WRITEBACK_CONFLICT = 'Canonical sanitization cannot overwrite newer working-tree bytes.';
+
+test('#6513: a canonical writeback refused for newer uncommitted bytes is held worktree_dirty instead of blocking the cursor; the committed edit imports next', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.') });
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), note('Beta two.'));
+ mkdirSync(join(f.root, 'people')); writeFileSync(join(f.root, 'people/fixable.md'), fixable());
+ const pin = commit(f.root, 'version two with a fixable fence');
+ await interruptedAfter(engine, f.opts, 1);
+ // An agent edits the new page before the catch-up reaches it: the pinned import wants to rewrite the fence, the file is newer.
+ const edit = fixable('A synthetic page, edited while the catch-up drained.');
+ writeFileSync(join(f.root, 'people/fixable.md'), edit);
+ const resumed = await performManagedSync(engine, f.opts);
+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'people/fixable.md', code: 'worktree_dirty' }] });
+ expect(resumed.managedWrite).toBeUndefined();
+ expect(resumed.held![0]!.message).toContain('canonical correction');
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Beta two.');
+ expect(await engine.getPage('people/fixable', { sourceId: f.id })).toBeNull();
+ expect(readFileSync(join(f.root, 'people/fixable.md'), 'utf8')).toBe(edit);
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
+ expect(pinnedWorktreeConflict({ state: 'conflict', error_code: 'source_changed', error_message: WRITEBACK_CONFLICT })).toBe(true);
+ // The cursor is finished, so the checkout is movable again; the agent commits and the next sync imports (and corrects) its edit.
+ const head = commit(f.root, 'the agent commits its edit');
+ const after = await performManagedSync(engine, f.opts);
+ expect(after).toMatchObject({ status: 'synced', toCommit: head, added: 1 });
+ expect((await engine.getPage('people/fixable', { sourceId: f.id }))?.compiled_truth).toContain('edited while the catch-up drained');
+ expect((await engine.getPage('people/fixable', { sourceId: f.id }))?.compiled_truth).toContain('| fact |');
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);
+ expect(await readGitHold(engine, f.id, source.incarnation, 'people/fixable.md')).toBeNull();
+ }
+}), 120_000);
+
+test('#6513: working-tree bytes that already are the canonical correction import without a second writeback', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ // The correction gbrain itself writes for this fence, taken from a clean sync of the same bytes.
+ const reference = await fixture(engine, { 'people/fixable.md': fixable() });
+ expect((await performManagedSync(engine, reference.opts)).status).toBe('first_sync');
+ const canonical = readFileSync(join(reference.root, 'people/fixable.md'), 'utf8');
+ expect(canonical).not.toBe(fixable()); expect(canonical).toContain('| fact |');
+
+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.') });
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), note('Beta two.'));
+ mkdirSync(join(f.root, 'people')); writeFileSync(join(f.root, 'people/fixable.md'), fixable());
+ const pin = commit(f.root, 'version two with a fixable fence');
+ await interruptedAfter(engine, f.opts, 1);
+ // The writeback landed on disk but the request that carried it never settled: the file is the correction, the page is not there.
+ writeFileSync(join(f.root, 'people/fixable.md'), canonical);
+ const resumed = await performManagedSync(engine, f.opts);
+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin });
+ expect(resumed.held_count ?? 0).toBe(0); expect(resumed.managedWrite).toBeUndefined();
+ expect((await engine.getPage('people/fixable', { sourceId: f.id }))?.compiled_truth).toContain('| fact |');
+ expect(readFileSync(join(f.root, 'people/fixable.md'), 'utf8')).toBe(canonical);
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
+ // Once the correction is committed, the pin..HEAD diff re-imports the same bytes as a no-op.
+ const head = commit(f.root, 'the correction is committed');
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'synced', toCommit: head, added: 0, modified: 0 });
+ }
+}), 120_000);
+
+test('#6513: a cursor an older run left blocked on the canonical-writeback conflict converts in place under --retry-failed', 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.') });
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), note('Beta two.'));
+ mkdirSync(join(f.root, 'people')); writeFileSync(join(f.root, 'people/fixable.md'), fixable());
+ commit(f.root, 'version two with a fixable fence');
+ const edit = fixable('A synthetic page, edited while the catch-up drained.');
+ writeFileSync(join(f.root, 'people/fixable.md'), edit);
+ // The old release: holds off, the refusal blocked the run and left the failed request on the cursor.
+ await engine.setConfig('sync.holds', 'fail');
+ let blocked;
+ try { blocked = await performManagedSync(engine, f.opts); } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'source_changed', reason: 'pinned_git_worktree_conflict' },
+ failures: [{ path: 'people/fixable.md', code: 'source_changed', message: WRITEBACK_CONFLICT }] });
+ const before = await cursorOf(engine, f.id);
+ expect(before.done).toBeFalsy();
+ const discoveries = countDiscoveries(engine, f.id);
+ let converted;
+ try { converted = await performManagedSync(engine, { ...f.opts, retryFailed: true }); }
+ finally { discoveries.restore(); }
+ expect(discoveries.count()).toBe(0);
+ expect(converted).toMatchObject({ status: 'synced', held_count: 1, held: [{ path: 'people/fixable.md', code: 'worktree_dirty' }], converted_from_failed: [blocked.managedWrite!.write_request.request_id] });
+ expect((await cursorOf(engine, f.id))?.run_id).toBe(before.run_id);
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Beta two.');
+ expect(readFileSync(join(f.root, 'people/fixable.md'), 'utf8')).toBe(edit);
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
+ }
+}), 120_000);
+
test('a page edited in the database after the manifest froze is held concurrent_write with its revisions; one that already holds the import is re-bound and waived', async () => withEnv({ GBRAIN_HOME: 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.'), 'd.md': note('Delta one.') });