Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): hold a managed import that raced a database-only write as concurrent_write (#6194)
garrytan8bc8283f5407
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex a41f13b156..ead4915789 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -679,6 +679,16 @@ config set persistence.max_claim_ms 900000` raises it, and `config set` refusesanything else with `invalid_params`). See[troubleshooting](guides/troubleshooting.md#persistence-write-stall).+<a id="concurrent-write-hold"></a>**A database-only write racing a managed sync import.** When a write that+does not publish the canonical file (write-through off, a sandboxed or a+derived write) commits to a page while managed sync imports a newer Git+version of it, the import's receipt fails `revision_conflict`. If the page's+live revision was written by a committed non-sync request for that page, the+file is held with code `concurrent_write` and the sync continues; neither+version is overwritten (#6194). Resolve it with `gbrain sources reconcile+<source> <slug> --preview`; see+[troubleshooting](guides/troubleshooting.md#concurrent-write-hold).+## JSONB writes: never double-encodeWriting a JS value into a `jsonb` column has exactly two correct forms. Get thisdiff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex dd83ccba8b..9bf3422fcf 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -12,6 +12,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`).- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. #6122: 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`.- `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`).+- `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/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 7c4f16dd55..c6862181fd 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -486,6 +486,16 @@ More: [docs/guides/write-refusals.md#colon_slug_windows_write_through](../../doc|---|---|---|---|---|---|---|| The command failed before it wrote its JSON result. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |+### concurrent_write++<a id="concurrent_write"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed sync import raced a database-only write to the same page, so the file is held and the page keeps the database version; neither was overwritten. | The page's live revision was written by a committed non-sync request after the import was frozen, so the Git file and the database genuinely diverge; choosing either silently would lose the other. | Preview the reconciliation with gbrain sources reconcile <source> <slug> --preview, resolve it with the user, then run gbrain sources retry-held <source> and gbrain sync --source <source> --no-pull. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#concurrent_write](../../docs/guides/write-refusals.md#concurrent_write)+### config_error<a id="config_error"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 10e94be282..b8c8547159 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -43,6 +43,8 @@<a id="held-fence-files"></a>**Sync held a file because of its facts or takes fence (`Held <path>: invalid_fence …`)?** Managed sync succeeded; only that file waits. The hold names the fence, section, row numbers, columns and reason, never a cell. Read the page (`gbrain get --source <id> -- <slug>`), edit only that fence in the file (not the frontmatter; `gbrain repair frontmatter` does not touch fences), commit, and run `gbrain sync --source <id> --no-pull`. A `prepare_time` hold was refused against stored rows (for example a takes row number a stored take already uses): fix it as its `fence.reason` says, and after a database-side fix run `gbrain sources retry-held <id>`. A source a fence blocked before upgrading recovers on its next sync. A fence with one obvious meaning is never held: sync rewrites it losslessly, commits the file and reports `fences_normalized`; a `fence_normalized` notice on a write means re-read the page before editing it. See [fence holds](write-refusals.md#invalid_fence).+<a id="concurrent-write-hold"></a>**Sync held a file with `concurrent_write` (a Git edit and a database-only write to the same page raced)?** Managed sync finished and nothing was overwritten: the page keeps the database version and only that file waits. Run `gbrain sources status <id>` (it names the page and the competing request), preview with `gbrain sources reconcile <id> <slug> --preview`, let the user choose, apply, then run `gbrain sources retry-held <id>` and `gbrain sync --source <id> --no-pull`. Before this release the same race left the source `blocked_by_failures` until `--retry-failed`; such a source converts to the hold on its next sync. See [concurrent_write](write-refusals.md#concurrent_write).+<a id="held-connector-items"></a>**A Google or GitHub item is held after repeated failures (doctor `connector_held_items`, `gbrain waiting` says coverage is partial)?** Run `gbrain sources status <id>`, fix the cause, then after the user agrees run `gbrain sources retry-held <id>` and `gbrain sync --source <id>`. See [held items](google-connect.md#held-items).<a id="checkpoint-validation-timeout"></a>**A managed sync is blocked with `checkpoint_validation_timeout`?** Run the printed commands on the brain host: `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <id> --no-pull --retry-failed …`. Doctor's `persistence_request_growth` warns before lifetime request IDs run out.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 6158f62dfb..105893ee0c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -149,6 +149,7 @@ with each file and fix the ones that need no guessing."*| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. || <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |+| <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. A conflict no such request explains still blocks with `revision_conflict`. | `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="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="changed_since_preview"></a>`changed_since_preview` | A `gbrain repair frontmatter --apply` found a file, its proposed change or its page different from what the preview showed, so that file was not written. | Preview again, show the user the new diff and approve its new hash. |diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.tsindex 4cdc1af583..c1aa434cbc 100644--- a/src/commands/doctor/checks/git-holds.ts+++ b/src/commands/doctor/checks/git-holds.ts@@ -28,10 +28,10 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[const sources = coverage.map(source => {const route = coverageRoute(source);const steps = holdRepairSteps(source.source_id, route);- return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}),+ return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}), ...(route.concurrent ? { concurrent: route.concurrent } : {}),first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,- status: `gbrain sources status ${source.source_id}`, repair: route.others ? `gbrain repair frontmatter --source ${source.source_id}` : `gbrain sync --source ${source.source_id} --no-pull`,+ status: `gbrain sources status ${source.source_id}`, repair: route.others ? `gbrain repair frontmatter --source ${source.source_id}` : route.concurrent ? `gbrain sources reconcile ${source.source_id} <slug> --preview` : `gbrain sync --source ${source.source_id} --no-pull`,argv: steps.argv, next: steps.text };});const held = sources.reduce((sum, source) => sum + source.held, 0);diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 8d5649c4b1..17a8ad371b 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -70,8 +70,9 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {fix: { argv: ['gbrain', 'sources', 'retry-held', sourceId], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };const fences = scheduled.items.filter(item => item.code === 'invalid_fence').length;+ const concurrent = scheduled.items.filter(item => item.code === 'concurrent_write').length;return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `- + `A file that still refuses stays held; ${fences ? holdRepairSteps(sourceId, { fences, others: count - fences }).text : `preview its fix with: gbrain repair frontmatter --source ${sourceId}`}`,+ + `A file that still refuses stays held; ${fences || concurrent ? holdRepairSteps(sourceId, { fences, others: count - fences - concurrent, concurrent }).text : `preview its fix with: gbrain repair frontmatter --source ${sourceId}`}`,fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a201b8fb6b..01411f4f13 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -260,6 +260,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.0.0-wave11', text: 'Doctor\'s new `persistence_write_stall` check warns when a managed write has held its claim longer than `persistence.max_claim_ms` (default 10 minutes) and names the stuck phase; `gbrain sources writer status --json` shows each running request\'s `claim` phase.' },{ since: '0.0.0-wave11', text: 'On a brain whose managed persistence was never activated, `gbrain sources writer deactivate` now releases sources claimed before activation (the dry run lists them as `pre_activation_claims`), so classic `gbrain sync` of them works again; `gbrain sources writer deactivate --dry-run --json` previews it.' },{ since: '0.0.0-wave11', text: 'Writer transfer, `gbrain sources set-path` and reclone now compare only the files Git tracks in a Git checkout, so ignored files such as `.env.local` are never read or need copying and a clean `git clone` verifies; a transfer prepared before this release is prepared again (`writer_manifest_rescope_required`), and upgrading drops the per-file path and hash maps older releases stored.' },+ { since: '0.0.0-wave11', text: 'A managed sync import that races a database-only write to the same page is now held with code `concurrent_write` (the sync finishes, the database version is kept) instead of leaving the source `blocked_by_failures`; `gbrain sources reconcile <source> <slug> --preview` resolves it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 8f98b72d83..5eb2b5f7dc 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -99,6 +99,7 @@ export const CODES = {code_reused: { class: 'caller', summary: "Google connect credential error: code reused.", docs: 'docs/guides/google-connect.md#troubleshooting' },colon_slug_windows_write_through: { class: 'caller', summary: "A colon slug cannot be written through on Windows." },command_failed: { class: 'server', summary: "The command failed before it wrote its JSON result." },+ concurrent_write: { class: 'caller', summary: "A managed sync import raced a database-only write to the same page, so the file is held and the page keeps the database version; neither was overwritten.", why: "The page's live revision was written by a committed non-sync request after the import was frozen, so the Git file and the database genuinely diverge; choosing either silently would lose the other.", docs: 'docs/guides/write-refusals.md#concurrent_write', suggestion: 'Preview the reconciliation with gbrain sources reconcile <source> <slug> --preview, resolve it with the user, then run gbrain sources retry-held <source> and gbrain sync --source <source> --no-pull.' },config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },conflicting_source_scope: { class: 'caller', summary: "--source and --all-sources were both given." },diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex c656785208..904160050c 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -28,7 +28,7 @@ export interface HeldPage { record: GitHoldRecord; revision: string | null }* Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`);* `fences` (present only when some are) counts the #6188 `invalid_fence` holds among them, which route to a fence edit instead of frontmatter repair.*/-export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number }+export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number; concurrent?: number }/** `get_page.file_held`. */export interface FileHeld {@@ -84,24 +84,25 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourcconst ids = scope.sourceIds ?? (scope.sourceId !== undefined && scope.sourceId !== ALL_SOURCES ? [scope.sourceId] : null);if (ids && !ids.length) return Promise.resolve([]);return cached(request, `coverage:${ids ? [...ids].sort().join(',') : '*'}`, async () => {- const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string }>(`SELECT s.id AS source_id,+ const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string; concurrent: number | string }>(`SELECT s.id AS source_id,COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale,- COALESCE((h.completed_keys->0->>'fences')::int,0) AS fences+ COALESCE((h.completed_keys->0->>'fences')::int,0) AS fences, COALESCE((h.completed_keys->0->>'concurrent')::int,0) AS concurrentFROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::textWHERE h.op=$1 AND s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))AND COALESCE((h.completed_keys->0->>'count')::int,0)>0ORDER BY s.id`, [GIT_HOLD_SUMMARY_OP, ids]);return rows.map(row => {const count = Number(row.count), stale = Math.min(Number(row.stale), count), fences = Math.min(Number(row.fences), count);- return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}) };+ const concurrent = Math.min(Number(row.concurrent), count - fences);+ return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}) };});});}/** D6: which repair a held source needs, from its counts. */export function coverageRoute(source: HeldCoverage): HoldRepairRoute {- const fences = source.fences ?? 0;- return { fences, others: Math.max(0, source.missing + source.stale - fences) };+ const fences = source.fences ?? 0, concurrent = source.concurrent ?? 0;+ return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent), ...(concurrent ? { concurrent } : {}) };}function repairArgv(sourceId: string): string[] {@@ -117,10 +118,12 @@ function repairArgv(sourceId: string): string[] {export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; route?: HoldRepairRoute }>, why: string): Action {const frontmatter = sources.filter(source => !source.route || source.route.others > 0).map(source => `'${repairArgv(source.source_id).join(' ')}'`);const fences = sources.filter(source => source.route && source.route.fences > 0).map(source => source.source_id);+ const concurrent = sources.filter(source => source.route?.concurrent).map(source => source.source_id);const first = sources[0]!;const parts = [...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),...(fences.length ? [`Some held files have a facts or takes table gbrain cannot import: on the brain host run ${fences.map(id => `'gbrain sources status ${id}'`).join(', ')} to see which file and table, edit that table and commit, then run ${fences.map(id => `'gbrain sync --source ${id} --no-pull'`).join(', ')}.`] : []),+ ...(concurrent.length ? [`Some notes changed in their files while an agent saved a different version to the brain, so both were kept: on the brain host run ${concurrent.map(id => `'gbrain sources status ${id}'`).join(', ')} and reconcile each named note with 'gbrain sources reconcile <source> <slug> --preview'.`] : []),];return { argv: first.route ? holdRepairSteps(first.source_id, first.route).argv : repairArgv(first.source_id), consent: [], actor: 'host_admin', requires_exclusive: false, why,user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. ${parts.join(' ')}` };@@ -128,7 +131,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout/** The route of one hold record. */export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {- return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : { fences: 0, others: 1 };+ return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : record.code === 'concurrent_write' ? { fences: 0, others: 0, concurrent: 1 } : { fences: 0, others: 1 };}/** `get_page.file_held` for a page whose newer file is held; the path only for trusted local callers. */diff --git a/src/core/persistence/sync-concurrent-write.ts b/src/core/persistence/sync-concurrent-write.tsnew file mode 100644index 0000000000..921b49694f--- /dev/null+++ b/src/core/persistence/sync-concurrent-write.ts@@ -0,0 +1,47 @@+/**+ * #6194 (D4): a managed sync import that failed `revision_conflict` because a+ * database-only write committed to the same page while the import was in+ * flight. The file (Git) and the newer database revision genuinely diverge, so+ * neither side may win silently: the file is held with code `concurrent_write`+ * and the rest of the sync continues; nothing is overwritten. The hold's fix is+ * `gbrain sources reconcile <source> <slug> --preview` (sync-holds.ts router).+ *+ * The proof is revision-linked, not admission order: the page's live revision+ * differs from the revision the import was frozen against, and the committed+ * journal request that wrote that revision (`pages.revision_write_request_id`)+ * is a non-sync request for the same source incarnation and page id. Anything+ * else (no proof) keeps the blocking failure.+ */+import type { BrainEngine } from '../engine.ts';+import { RECOVERY_VERSION } from '../markdown.ts';+import { sha256 } from './digest.ts';+import type { WriteRequest } from './model.ts';+import type { SyncIntent } from './sync-prepare.ts';+import type { HeldEntry } from './sync-screen.ts';++export interface ConcurrentWriteProof { request_id: string; operation: string; revision: string }++/** The proof that `done` failed because a non-sync write changed the page; null when it is not proven. */+export async function concurrentWriteProof(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string;+ pending: { pageId: number | null; intent: SyncIntent }; done: Pick<WriteRequest, 'error_code'> }): Promise<ConcurrentWriteProof | null> {+ const { pending } = input;+ if (input.done.error_code !== 'revision_conflict' || pending.intent.kind !== 'managed_sync_import' || pending.pageId === null) return null;+ const [page] = await engine.executeRaw<{ revision: string | null; writer: string | null }>(+ 'SELECT knowledge_revision::text AS revision, revision_write_request_id::text AS writer FROM pages WHERE id=$1 AND source_id=$2', [pending.pageId, input.sourceId]);+ if (!page?.revision || !page.writer || page.revision === String(pending.intent.expected_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' || String(writer.kind ?? '').startsWith('managed_sync_')+ || writer.incarnation !== input.incarnation || Number(writer.page_id) !== pending.pageId) return null;+ return { request_id: writer.request_id, operation: writer.operation, revision: page.revision };+}++/** The `concurrent_write` hold for a proven race; location and identifiers only, never page content. */+export function concurrentWriteHold(entry: { path: string; sourcePath: string; working?: boolean }, slug: string, pageId: number,+ intent: SyncIntent, proof: ConcurrentWriteProof): HeldEntry {+ return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code: 'concurrent_write',+ message: `${entry.path} changed in Git while ${proof.operation} request ${proof.request_id} wrote page ${slug} straight to the database, so the two versions diverge; neither was overwritten.`,+ upstream_version: typeof intent.content === 'string' ? sha256(intent.content) : null,+ meta: { recovery_version: RECOVERY_VERSION, competing_request_id: proof.request_id, competing_operation: proof.operation, page_revision: proof.revision,+ ...(typeof intent.blobOid === 'string' ? { blob_oid: intent.blobOid } : {}), ...(entry.working ? { working: true } : {}) } };+}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 7c605881ba..5a7f904dc9 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -50,7 +50,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;type Exec = Pick<BrainEngine, 'executeRaw'>;-export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported';+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write';export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | FenceReason;export interface GitHoldMeta {@@ -69,6 +69,10 @@ export interface GitHoldMeta {working?: boolean;/** The held file is a rename destination: the page it moves when the hold clears. */rename_from?: SyncRename;+ /** #6194 `concurrent_write`: the database-only request that wrote the page during the import, and the revision it wrote. */+ competing_request_id?: string;+ competing_operation?: string;+ page_revision?: string;}export interface GitHoldRecord {@@ -134,20 +138,24 @@ async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Pro/*** `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages);- * `images` the #5493 unsupported-image holds, which never escalate; `fences` the #6188 `invalid_fence` holds.+ * `images` the #5493 unsupported-image holds, which never escalate; `fences` the #6188 `invalid_fence` holds;+ * `concurrent` the #6194 `concurrent_write` holds.*/-async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number, fenceDelta: number): Promise<void> {+async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number, fenceDelta: number,+ concurrentDelta: number): Promise<void> {await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)||jsonb_build_object('count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int),'images',GREATEST(0,COALESCE((completed_keys->0->>'images')::int,0)+$5::int),- 'fences',GREATEST(0,COALESCE((completed_keys->0->>'fences')::int,0)+$6::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta, fenceDelta]);+ 'fences',GREATEST(0,COALESCE((completed_keys->0->>'fences')::int,0)+$6::int),+ 'concurrent',GREATEST(0,COALESCE((completed_keys->0->>'concurrent')::int,0)+$7::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta, fenceDelta, concurrentDelta]);}const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record && record.page_id !== null ? 1 : 0;const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'managed_image_sync_unsupported' ? 1 : 0;const fenceWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'invalid_fence' ? 1 : 0;+const concurrentWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'concurrent_write' ? 1 : 0;async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',@@ -171,13 +179,14 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'versionON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,[GIT_HOLD_OP, gitHoldFingerprint(input.source_id, input.incarnation, input.path), JSON.stringify([record])]);if (existing) {- if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing) || fenceWeight(input) !== fenceWeight(existing)) {+ if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing) || fenceWeight(input) !== fenceWeight(existing)+ || concurrentWeight(input) !== concurrentWeight(existing)) {await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing), imageWeight(input) - imageWeight(existing),- fenceWeight(input) - fenceWeight(existing));+ fenceWeight(input) - fenceWeight(existing), concurrentWeight(input) - concurrentWeight(existing));}return 'updated';}- await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input), fenceWeight(input));+ await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input), fenceWeight(input), concurrentWeight(input));return 'inserted';}@@ -193,7 +202,7 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnatconst existing = await readRow(tx, input.sourceId, input.incarnation, input.path);if (!existing || existing.observed_at > input.observedAt) return false;await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);- await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing), -fenceWeight(existing));+ await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing), -fenceWeight(existing), -concurrentWeight(existing));return true;}@@ -277,10 +286,11 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re/*** D6: which repairs a source's holds need. Fence holds are fixed by editing- * the named fence in the file and syncing; every other hold routes to the- * frontmatter repair preview. A source with both names both.+ * the named fence in the file and syncing; #6194 concurrent-write holds by+ * reconciling the page and re-screening the file; every other hold routes to+ * the frontmatter repair preview. A source with several kinds names each.*/-export interface HoldRepairRoute { fences: number; others: number }+export interface HoldRepairRoute { fences: number; others: number; concurrent?: number }/** The source-level next step every surface prints for `route` (sync results, doctor, read notices, the banner, retry-held). */export function holdRepairSteps(sourceId: string, route: HoldRepairRoute): { argv: string[]; commands: string[]; text: string } {@@ -289,6 +299,13 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute): { argconst sync = `gbrain sync --source ${sourceId} --no-pull`;const fenceText = `for each fence hold, read the page (gbrain get --source ${sourceId} -- <slug>), edit the fence that gbrain sources status ${sourceId} names in its file, commit, then run ${sync}`;const frontmatterText = `preview the frontmatter and other fixes with ${frontmatter.join(' ')} (writes nothing until a hash-bound apply)`;+ const concurrentText = `for each concurrent-write hold, preview the reconciliation with gbrain sources reconcile ${sourceId} <slug> --preview `+ + `(gbrain sources status ${sourceId} names each slug and the database write that raced the import), resolve and apply it, then run gbrain sources retry-held ${sourceId} and ${sync}`;+ if (route.concurrent) {+ const parts = [...(route.others ? [frontmatterText] : []), ...(route.fences ? [fenceText] : []), concurrentText];+ const commands = [...(route.others ? [frontmatter.join(' ')] : []), status.join(' '), `gbrain sources retry-held ${sourceId}`, sync];+ return { argv: route.others ? frontmatter : status, commands, text: parts.join('; ') };+ }if (route.fences && !route.others) return { argv: status, commands: [status.join(' '), sync], text: fenceText };if (route.fences) return { argv: frontmatter, commands: [frontmatter.join(' '), status.join(' '), sync], text: `${frontmatterText}; ${fenceText}` };return { argv: frontmatter, commands: [frontmatter.join(' ')], text: frontmatterText };@@ -317,6 +334,15 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cverify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };}+ case 'concurrent_write': {+ const slug = record.slug ?? '<slug>';+ return { argv: ['gbrain', 'sources', 'reconcile', source, slug, '--preview'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `${record.path} changed in Git while ${record.meta.competing_operation ?? 'a database'} request ${record.meta.competing_request_id ?? '(unknown)'} wrote page ${slug} straight to the database, so the two versions diverge and neither was overwritten. `+ + `The reconcile preview shows both and writes nothing; resolve it with the user, apply it, then re-screen the file with gbrain sources retry-held ${source} and gbrain sync --source ${source} --no-pull. The rest of the source is not blocked.`,+ then: { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Schedules ${record.path} for a re-screen on the next sync, after the page is reconciled.`, verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };+ }case 'file_too_large':return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex d6bc30f21e..bd5d8c4268 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -38,6 +38,7 @@ import { isContentRefusal } from '../import-screen.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';+import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';import { faultPoint } from './fault-points.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';@@ -224,6 +225,9 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M};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 {@@ -413,7 +417,8 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: s}/**- * #6188 (E10): a page request of this run that failed with a fence refusal is held in the+ * #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) 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). Other requests of the source settle* first, within the run's wait budget; when they are still running the run returns@@ -427,7 +432,10 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:if (!run.screen || cursor.companyPlan || pending.intent.kind !== 'managed_sync_import' || typeof pending.intent.content !== 'string') return null;const fence = fenceReceiptLocation(done);const entry = cursor.entries[cursor.index];- if (!fence || !entry || entry.path !== pending.intent.path) return null;+ if (!entry || entry.path !== pending.intent.path) return null;+ // #6194 (D4): a revision conflict proven to come from a concurrent database-only write is held the same way (sync-concurrent-write.ts).+ const proof = fence ? null : await concurrentWriteProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pending, done });+ if (!fence && !proof) return null;const deadline = performance.now() + waitMs;for (;;) {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]);@@ -436,7 +444,8 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:if (performance.now() >= deadline) return 'pending';await new Promise(resolve => setTimeout(resolve, 50));}- const hold = prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content, pending.intent.blobOid);+ const hold = fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content, pending.intent.blobOid)+ : concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof!);const base: Cursor = { ...cursor }; delete base.group;return saveCursor(engine, key, cursor, advanceHeld(base, [...(cursor.convertedFromFailed ?? []), pending.requestId]), false, assertActive, async tx => {await heldWrite(cursor, hold, run.observedAt!)(tx);diff --git a/test/managed-sync-concurrent-write-hold.test.ts b/test/managed-sync-concurrent-write-hold.test.tsnew file mode 100644index 0000000000..d0fe9a87a3--- /dev/null+++ b/test/managed-sync-concurrent-write-hold.test.ts@@ -0,0 +1,113 @@+/**+ * #6194 (D4): a database-only write that commits to a page while managed sync imports a newer Git version of it+ * failed the import with `revision_conflict`, and that terminal receipt replayed on every later sync, so the+ * source stayed `blocked_by_failures`. A conflict proven to come from such a write (the live revision was written+ * by a committed non-sync request for the same page) is now a `concurrent_write` hold: the sync finishes, the+ * database version is kept, nothing is overwritten, and the hold points at `sources reconcile --preview`.+ * Without that proof (a revision no journal request wrote) the failure still blocks.+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { readGitHold } from '../src/core/persistence/sync-holds.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { waitFor } from './helpers/wait-for.ts';++const SLUG = 'people/alice-example';+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (body: string) => `---\ntype: person\ntitle: Alice Example\n---\n\n${body}\n`;+async function storedPending(engine: BrainEngine): Promise<string | null> {+ const [row] = await engine.executeRaw<{ slug: string | null }>("SELECT completed_keys->0->'pending'->>'slug' AS slug FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'='default'");+ return row?.slug ?? null;+}++/** First sync imports the page; then Git gets a newer version and a database-only write races the next import. */+async function raced(engine: BrainEngine, root: string, write: () => Promise<unknown>) {+ expect(await performManagedSync(engine, { sourceId: 'default', noPull: true })).toMatchObject({ status: 'first_sync' });+ const before = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });+ writeFileSync(join(root, 'people', 'alice-example.md'), note('Works at acme-example; the Git edit.'));+ commit(root, 'git edit');+ let fired = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'sync:mid_checkpoint' || detail.sourceId !== 'default' || fired || await storedPending(engine) !== SLUG) return;+ fired = true;+ await write();+ });+ try {+ const first = await performManagedSync(engine, { sourceId: 'default', noPull: true });+ expect(fired).toBe(true);+ return { first, before: before! };+ } finally { installFaultHook(undefined); }+}++for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATABASE_URL] : [undefined]) describe(`#6194 concurrent write during import (${databaseUrl ? 'postgres' : 'pglite'})`, () => {+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'people'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, 'people', 'alice-example.md'), note('Works at acme-example.'));+ commit(root, 'notes');+ };++ test('a proven concurrent database-only write becomes a concurrent_write hold; the sync finishes and nothing is overwritten', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.write_through', 'false');+ let requestId = '';+ const { first } = await raced(engine, root, async () => {+ requestId = randomUUID();+ const current = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });+ await submitPageMutation(ctx as OperationContext, { operation: 'put_page', params: { slug: SLUG, request_id: requestId, expected_revision: current!.revision,+ content: note('Works at acme-example; the database-only edit.') } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: 'the database-only put_page commits' });+ });+ expect(first.status).not.toBe('blocked_by_failures');+ expect(first.held?.map(hold => ({ path: hold.path, code: hold.code }))).toEqual([{ path: 'people/alice-example.md', code: 'concurrent_write' }]);+ const item = first.held![0]!;+ expect(item.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', 'default', SLUG, '--preview']);+ expect(item.fix.why).toContain(requestId);+ expect((await engine.getPage(SLUG, { sourceId: 'default' }))?.compiled_truth).toContain('the database-only edit');+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='default'");+ const record = await readGitHold(engine, 'default', source!.incarnation, 'people/alice-example.md');+ expect(record).toMatchObject({ code: 'concurrent_write', meta: { competing_request_id: requestId, competing_operation: 'put_page' } });+ const [summary] = await engine.executeRaw<{ concurrent: number }>("SELECT (completed_keys->0->>'concurrent')::int AS concurrent FROM op_checkpoints WHERE op='sync-hold-summary' AND fingerprint=$1", [`default:${source!.incarnation}`]);+ expect(summary?.concurrent).toBe(1);+ // The next sync does not replay a failure: the file stays held and the page keeps the database version.+ const again = await performManagedSync(engine, { sourceId: 'default', noPull: true });+ expect(again.status).not.toBe('blocked_by_failures');+ expect((await engine.getPage(SLUG, { sourceId: 'default' }))?.compiled_truth).toContain('the database-only edit');+ }, { databaseUrl, setup }), 120_000);++ test('a database-only delete of the page during the import is held the same way and stays deleted', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.write_through', 'false');+ let requestId = '';+ const { first } = await raced(engine, root, async () => {+ requestId = randomUUID();+ const current = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });+ await submitPageMutation(ctx as OperationContext, { operation: 'delete_page', params: { slug: SLUG, request_id: requestId, expected_revision: current!.revision } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE request_id=$1::uuid", [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: 'the database-only delete_page commits' });+ });+ expect(first.held?.map(hold => hold.code)).toEqual(['concurrent_write']);+ expect(first.held![0]!.fix.why).toContain(requestId);+ expect(await engine.getPage(SLUG, { sourceId: 'default' })).toBeNull();+ }, { databaseUrl, setup }), 120_000);++ test('a revision conflict no journal request explains keeps blocking', () => managedBrain(async ({ engine, root }) => {+ const { first } = await raced(engine, root, () => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.putPage(SLUG, {+ type: 'person', title: 'Alice Example', compiled_truth: 'An unattributed database edit.', timeline: '', frontmatter: {}, content_hash: 'unattributed',+ }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION)));+ expect(first).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });+ expect(first.held ?? []).toEqual([]);+ expect(first.managedWrite?.suggestion).toContain(`gbrain sources reconcile default ${SLUG} --preview`);+ }, { databaseUrl, setup }), 120_000);+});