Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): classify a rename onto an occupied slug instead of swallowing it (#5431)
garrytana4fc75a0d6d3
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex 8fbe394e78..26fe6a577c 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Single-source and `--all` deliver that intrinsic >100-file embed deferral the same way: a queued `embed-backfill` on a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit `--no-embed` single-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`. Managed single-source and `--all` CLI envelopes retain structured `failures`, `failure_codes`, `run_id`, `target_commit`, and `counts_scope: run_cumulative`; blocked results exit nonzero. `--retry-failed` requires explicit idle ordinary-source fresh admission with the same options; no managed `--skip-failed`. Google/GitHub API source kinds route before the managed Git cursor. Managed connector `--retry-failed` explicitly admits a linked replacement after authority, source/owner, cursor and idle-state checks; pending work and old terminal receipts are not replaced. Unsupported connector dry-run, Git filtering/working-tree/code and `--skip-failed` options refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority.Refactor wave 1 (W4 sync): `src/commands/sync.ts` is now the façade — it keeps the `SyncResult` / `SyncOpts` types, `runSync`, `resolveParallelism`, `syncOneSource` and re-exports every moved symbol, so importers need no change. The implementation described above lives in `src/commands/sync/` (next entry). Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.-- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain whose pools connect with `retryConnectTimeout`, #5946; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.+- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback; #5431 W14 P1.8: the cheap rename goes through `rename-collision.ts` `renamePageOntoSlug`, which repairs `source_path` inside the rename transaction and classifies a unique violation: a tombstone at the destination is merged in one `maintenanceTransaction` (the tombstone re-keyed `<slug>~purged-<id>` with its history, the page moves with its id), a live destination falls through to the add fallback, any other error fails the file without a checkpoint; the fallback's reconcile carries the stale row's identity onto the destination row first (`carryRenameIdentity`: `recordRenameAlias`, `moveSlugBindings`, `movePageIdReferences`); `test/sync-rename-collision.test.ts` on both engines), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain whose pools connect with `retryConnectTimeout`, #5946; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; `runTakesRebuild` (W9F item 8) is `gbrain takes rebuild`'s parser and renderer, running `takes_rebuild` through a resident owner or the local engine (thin clients refused); queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ffa6d562fc..8547d532a7 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -51,7 +51,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield; `movePageIdReferences` (#5431) moves the page-id-keyed rows of a stale rename row onto the surviving row (`links` from/to/origin, `timeline_entries` page and event, `page_versions`), dropping stale-side duplicates on the `links` composite key and the timeline dedup indexes (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.diff --git a/src/commands/sync/rename-collision.ts b/src/commands/sync/rename-collision.tsnew file mode 100644index 0000000000..170ca95994--- /dev/null+++ b/src/commands/sync/rename-collision.ts@@ -0,0 +1,63 @@+/**+ * #5431 (W14 P1.8): the cheap sync rename, with its unique violation+ * classified instead of swallowed. `updateSlug` moves the row (keeping its id,+ * so every page-id-keyed row follows) and `source_path` is repaired in the+ * same maintenance transaction, so the full-sync purge never reads the live+ * renamed page as a removed file. When the destination slug is occupied:+ *+ * - by a soft-deleted page (a tombstone), the two are merged in one+ * transaction: the tombstone is re-keyed purge-style (`<slug>~purged-<id>`,+ * a name no derived slug can take; its history, edges and slug bindings+ * stay with it, nothing is hard-deleted) and the renamed page moves in;+ * - by a live page, the caller decides (`live_destination`);+ * - any other error propagates: the file fails and the checkpoint stays.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { moveSlugBindings } from '../../core/page-state/rename-alias.ts';+import { maintenanceTransaction } from '../../core/persistence/attribution.ts';++export type RenameOutcome = 'renamed' | 'noop' | 'live_destination';++const UNIQUE_VIOLATION = '23505';++export function isUniqueViolation(error: unknown): boolean {+ return typeof error === 'object' && error !== null && String((error as { code?: unknown }).code) === UNIQUE_VIOLATION;+}++/** The purge-style slug a merged tombstone keeps; `~` is outside the slug grammar, so no file or write can claim it. */+export function purgedSlug(slug: string, pageId: number): string {+ return `${slug}~purged-${pageId}`;+}++export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId: string; oldSlug: string; newSlug: string; to: string }): Promise<RenameOutcome> {+ const { sourceId, oldSlug, newSlug, to } = input;+ const move = async (tx: BrainEngine) => {+ const moved = await tx.updateSlug(oldSlug, newSlug, { sourceId });+ if (moved > 0) await tx.executeRaw('UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3', [to, sourceId, newSlug]);+ return moved;+ };+ try {+ return (await maintenanceTransaction(engine, move)) > 0 ? 'renamed' : 'noop';+ } catch (error) {+ if (!isUniqueViolation(error)) throw error;+ const [destination] = await engine.executeRaw<{ id: number | string; tombstone: boolean }>(+ 'SELECT id, deleted_at IS NOT NULL AS tombstone FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, newSlug]);+ if (!destination) throw error;+ if (!destination.tombstone) return 'live_destination';+ const tombstoneId = Number(destination.id);+ const nothingToMove = Symbol('nothing to move');+ try {+ return await maintenanceTransaction(engine, async tx => {+ const rekeyed = await tx.executeRaw<{ id: number }>(+ 'UPDATE pages SET slug = $1 WHERE id = $2 AND source_id = $3 AND deleted_at IS NOT NULL RETURNING id', [purgedSlug(newSlug, tombstoneId), tombstoneId, sourceId]);+ if (!rekeyed.length) return 'live_destination' as const;+ await moveSlugBindings(tx, sourceId, newSlug, purgedSlug(newSlug, tombstoneId));+ if (await move(tx) === 0) throw nothingToMove;+ return 'renamed' as const;+ });+ } catch (merge) {+ if (merge === nothingToMove) return 'noop';+ throw merge;+ }+ }+}diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.tsindex a24e568cb6..eea86a78c4 100644--- a/src/commands/sync/renames.ts+++ b/src/commands/sync/renames.ts@@ -10,6 +10,9 @@ import { serr } from '../../core/console-prefix.ts';import { DELETE_BATCH_SIZE } from '../../core/engine-constants.ts';import { importFile, isImageFilePath as isImageImportPath, importImageFile } from '../../core/import-file.ts';import { maintenanceTransaction } from '../../core/persistence/attribution.ts';+import type { BrainEngine } from '../../core/engine.ts';+import { movePageIdReferences, moveSlugBindings, recordRenameAlias } from '../../core/page-state/rename-alias.ts';+import { renamePageOntoSlug } from './rename-collision.ts';import {resolveSlugsForRemovedPaths,refusedRemovedPathMessage,@@ -241,44 +244,29 @@ async function applyRename(// #3056: the cheap rename is OBSERVED, not assumed. A zero-row UPDATE// doesn't throw, and a thrown collision used to be swallowed by an// empty catch — both fell through to importFile, which created/updated- // the row at the new path while the old row stayed behind live. Both- // shapes now fall through to the reconcile below.+ // the row at the new path while the old row stayed behind live.+ // #5431 (W14 P1.8): the unique violation is classified instead. A+ // tombstone destination is merged (the tombstone re-keyed purge-style,+ // the page moves with its id), a live destination falls through to the+ // reconcile below, and any other error fails the file without a+ // checkpoint. `source_path` is repaired inside the rename transaction+ // (#3583 gate13: the cheap rename never rewrote it, the unchanged-content+ // reimport writes nothing, and the full-sync purge read the stale path as+ // a removed file and deleted the LIVE renamed page). The scope is the one+ // updateSlug uses: no sourceId means the DEFAULT source, never every+ // source (gate 14).let renameApplied = false;if (oldSlug !== undefined) {try {- renameApplied = (await maintenanceTransaction(engine, tx => tx.updateSlug(oldSlug, newSlug, renameOpts))) > 0;- } catch {- // Destination slug occupied or invalid — treat as add; the- // reconcile below removes the stale old row once the destination- // materialized.+ renameApplied = await renamePageOntoSlug(engine, { sourceId: renameOpts?.sourceId ?? DEFAULT_SOURCE_ID, oldSlug, newSlug, to }) === 'renamed';+ } catch (e: unknown) {+ const msg = e instanceof Error ? e.message : String(e);+ failedFiles.push({ path: to, error: `rename ${from} -> ${to} failed before any row moved: ${msg}` });+ serr(` [sync] rename ${sanitizePathForDisplay(from)} -> ${sanitizePathForDisplay(to)} failed: ${msg}`);+ progress.tick(1, newSlug);+ return undefined;}}- if (renameApplied) {- // #3583 gate13: the cheap rename moves the ROW but updateSlug never- // rewrites source_path — and the unchanged-content reimport below is- // a no-write skip, so the stale bookkeeping survived indefinitely- // and the full-sync purge later read it as "source file removed"- // and hard-deleted the LIVE renamed page. Repair the bookkeeping at- // the moment the rename lands. Best-effort, and nothing downstream- // covers a miss: rows renamed BEFORE this repair — and rows whose- // repair query fails — keep the stale path and stay exposed to the- // full-sync purge exactly as they are on master. That exposure is- // pre-existing (verified against the merge base) and out of scope- // here; this repair stops the shape being manufactured going- // forward.- try {- // Scope EXACTLY the way updateSlug scoped the move it repairs:- // no sourceId means the DEFAULT source, never every source — an- // unqualified UPDATE rewrote a matching (slug, source_path) row- // in ANOTHER source, and that source's later fallback reconcile- // probed the rewritten path, found nothing, and advanced without- // its rename sentinel (gate 14).- await engine.executeRaw(- `UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3 AND source_path = $4`,- [to, opts.sourceId ?? DEFAULT_SOURCE_ID, newSlug, from],- );- } catch { /* bookkeeping only — never fail the rename over it */ }- }// Reimport at new path (picks up content changes). Wrapped to match the// deletes/adds loops: a malformed renamed file is recorded to failedFiles// and skipped, NOT thrown uncaught. importFile still throws on content@@ -357,6 +345,25 @@ async function applyRename(return undefined;}+/**+ * #5431: the stale old row's identity follows the page to the row now live at+ * `newSlug`, in one transaction: `old -> new` is recorded as a slug alias so+ * `[[old]]` keeps resolving, slug-keyed rows (facts, withdrawals, declared+ * aliases) move, and page-id-keyed rows (edges, timeline, versions) move with+ * duplicates on their unique keys dropped from the stale side.+ */+async function carryRenameIdentity(engine: BrainEngine, sourceId: string, staleSlug: string, newSlug: string): Promise<void> {+ const rows = await engine.executeRaw<{ slug: string; id: number | string }>(+ 'SELECT slug, id FROM pages WHERE source_id = $1 AND slug = ANY($2::text[])', [sourceId, [staleSlug, newSlug]]);+ const from = rows.find(r => r.slug === staleSlug), to = rows.find(r => r.slug === newSlug);+ if (!from || !to || from.id === to.id) return;+ await maintenanceTransaction(engine, async tx => {+ await recordRenameAlias(tx, sourceId, staleSlug, newSlug);+ await moveSlugBindings(tx, sourceId, staleSlug, newSlug);+ await movePageIdReferences(tx, Number(from.id), Number(to.id));+ });+}+/*** #3056: when the cheap rename did not apply, the rename fell back to add* semantics; remove the stale old row once the destination materialized.@@ -501,6 +508,11 @@ async function reconcileRenameFallback(// silently assumed safe.for (const s of staleSlugs) {staleSlug = s;+ // #5431: the stale row is the renamed page's old identity; its+ // edges, timeline and versions move to the row that materialized+ // at the destination (deduplicated on the links key) before the+ // row itself is soft-deleted.+ await carryRenameIdentity(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, s, newSlug);// #4587: soft-delete the stale claimant (72h recovery) —// candidates come from activeSlugsBySourcePath, so every s// is an ACTIVE row and the flip always applies. Same scopediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c2b748539f..c21751e868 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -377,6 +377,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.156.0', text: 'A managed checkout deleted and recreated at its recorded path (restore from backup, rebuilt container, Migration Assistant copy) has two deliberate exits instead of `recovery_required` from every verb: `gbrain sources writer transfer prepare/accept <source> --self-transfer --confirm-relocated-root` waives only the directory identity comparison when the stamp and the reservation beside the root agree on everything else, and `gbrain sources set-path <source> <path>` converges a checkout moved behind a symlink at its recorded path, keeping the worktree. `gbrain sources writer deactivate --dry-run` now lists a `physical_root` blocker exactly when its real run would refuse, and the classic (pre-activation) release no longer refuses on a recreated directory whose reservation and stamp still agree.' },// W14 PR1 P1.2 (#6432). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.156.0', text: 'Schema-pack YAML now decodes quoted scalars: a double-quoted value carries the JSON escape subset and a single-quoted value is literal text with `\'\'` for one quote, so a link-type regex written as `"\\\\b"` loads as `\\b` and a `gbrain schema` mutation writes it back unchanged (before, every mutation doubled the backslashes of every quoted scalar). A hand-written double-quoted value that meant two backslashes now means one. A mutation whose emitted YAML does not read back as the manifest refuses with `schema_pack_emit_mismatch` and leaves the file unchanged; a pack file above 8 MiB refuses to load with `schema_pack_too_large` instead of being read, and `gbrain doctor` warns on a mutable pack above 1 MiB with the hand-repair runbook.' },+ // W14 PR1 P1.8 (#5431). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.156.0', text: 'A Git rename onto a slug a soft-deleted page still holds now moves the page onto that slug with its id, history, edges, facts and aliases in one transaction; the tombstone keeps its own history under `<slug>~purged-<id>`, a name no file can take, so nothing is hard-deleted. A rename whose destination a live page holds still imports the renamed content there, but the old row\'s edges, timeline, versions, facts, withdrawals and aliases now move to that page (with `[[old-slug]]` recorded as an alias) before the old row is soft-deleted, instead of being stranded on the tombstone. Any other database error on the rename fails the file and leaves the sync checkpoint where it was, where it used to be swallowed. The renamed page\'s `source_path` is repaired inside the rename transaction, so a later `gbrain sync --full` cannot read the live page as a removed file.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.tsindex c7fa6f86be..768d43615d 100644--- a/src/core/page-state/rename-alias.ts+++ b/src/core/page-state/rename-alias.ts@@ -67,3 +67,38 @@ export async function moveSlugBindings(}}}++/**+ * Move the page-id-keyed rows of a page whose rename fell back to add+ * semantics (#5431) onto the row that materialized at the destination, before+ * the stale row is soft-deleted: edges where it is the source, target or+ * origin, its timeline entries and its version history. Rows the surviving+ * page already holds under the same unique key (`links` composite key,+ * timeline dedup indexes) are dropped from the stale side, never duplicated.+ * Runs inside the caller's transaction and is idempotent.+ */+export async function movePageIdReferences(+ tx: Pick<BrainEngine, 'executeRaw'>,+ fromPageId: number,+ toPageId: number,+): Promise<void> {+ if (fromPageId === toPageId) return;+ const statements: Array<[string, unknown[]]> = [+ [`DELETE FROM links s WHERE s.from_page_id = $1 AND EXISTS (SELECT 1 FROM links o WHERE o.from_page_id = $2 AND o.to_page_id = s.to_page_id+ AND o.link_type = s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [fromPageId, toPageId]],+ [`UPDATE links SET from_page_id = $2 WHERE from_page_id = $1`, [fromPageId, toPageId]],+ [`DELETE FROM links s WHERE s.to_page_id = $1 AND EXISTS (SELECT 1 FROM links o WHERE o.to_page_id = $2 AND o.from_page_id = s.from_page_id+ AND o.link_type = s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [fromPageId, toPageId]],+ [`UPDATE links SET to_page_id = $2 WHERE to_page_id = $1`, [fromPageId, toPageId]],+ [`DELETE FROM links s WHERE s.origin_page_id = $1 AND EXISTS (SELECT 1 FROM links o WHERE o.origin_page_id = $2 AND o.from_page_id = s.from_page_id+ AND o.to_page_id = s.to_page_id AND o.link_type = s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source)`, [fromPageId, toPageId]],+ [`UPDATE links SET origin_page_id = $2 WHERE origin_page_id = $1`, [fromPageId, toPageId]],+ [`DELETE FROM timeline_entries s WHERE s.page_id = $1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.page_id = $2 AND o.date = s.date+ AND md5(o.summary) = md5(s.summary) AND o.source = s.source)`, [fromPageId, toPageId]],+ [`UPDATE timeline_entries SET page_id = $2 WHERE page_id = $1`, [fromPageId, toPageId]],+ [`DELETE FROM timeline_entries s WHERE s.event_page_id = $1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.event_page_id = $2 AND o.date = s.date)`, [fromPageId, toPageId]],+ [`UPDATE timeline_entries SET event_page_id = $2 WHERE event_page_id = $1`, [fromPageId, toPageId]],+ [`UPDATE page_versions SET page_id = $2 WHERE page_id = $1`, [fromPageId, toPageId]],+ ];+ for (const [sql, params] of statements) await tx.executeRaw(sql, params);+}diff --git a/test/e2e/sync-rename-collision.test.ts b/test/e2e/sync-rename-collision.test.tsnew file mode 100644index 0000000000..aae83dc12e--- /dev/null+++ b/test/e2e/sync-rename-collision.test.ts@@ -0,0 +1,4 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// #5431 (W14 P1.8): the rename-collision classifier and the page-id reference mover on Postgres.+await registerPostgresTests(() => import('../sync-rename-collision.test.ts'));diff --git a/test/sync-rename-collision.test.ts b/test/sync-rename-collision.test.tsnew file mode 100644index 0000000000..e0cbeb9a0e--- /dev/null+++ b/test/sync-rename-collision.test.ts@@ -0,0 +1,197 @@+/**+ * #5431 (W14 P1.8): a sync rename whose destination slug is already occupied.+ * Before, `updateSlug`'s unique violation was swallowed and the rename fell+ * back to import + soft-delete: the page's identity (versions, timeline,+ * edges, aliases, withdrawals) stayed on the soft-deleted row, a tombstone at+ * the destination was revived under a foreign id, and the stale `source_path`+ * exposed the live renamed page to the full-sync purge.+ *+ * Now the unique violation is classified. A tombstone destination is merged+ * in one maintenance transaction: the tombstone is re-keyed purge-style+ * (`<slug>~purged-<id>`, history retained, never hard-deleted) and the page+ * moves with its id; `source_path` is repaired in the same transaction. Any+ * other error fails the file without advancing the checkpoint. When the+ * rename still has to fall back to add semantics, `movePageIdReferences`+ * carries the page-id-keyed rows to the row that materialized, deduplicating+ * on the links composite key, before the stale row is soft-deleted.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync } from '../src/commands/sync.ts';+import { movePageIdReferences } from '../src/core/page-state/rename-alias.ts';+import { maintenanceTransaction } from '../src/core/persistence/attribution.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-rename-collision-'));+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const person = (title: string, body: string, aliases: string[] = []) => `---\ntype: person\ntitle: ${title}\n${aliases.length ? `aliases: [${aliases.join(', ')}]\n` : ''}---\n\n${body}\n`;++for (const kind of backends) describe(`sync rename onto an occupied slug (${kind})`, () => {+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });++ async function fixture(run: (f: { source: string; root: string; sync: (opts?: Record<string, unknown>) => Promise<any> }) => Promise<void>) {+ const source = `rc-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, source);+ mkdirSync(join(root, 'people'), { recursive: true });+ git(root, 'init', '-q', '-b', 'main'); git(root, 'config', 'user.email', '[email protected]'); git(root, 'config', 'user.name', 'Example');+ writeFileSync(join(root, 'people', 'alice.md'), person('Alice', 'Alice is a person who [[people/carol]] knows.', ['Ali']));+ writeFileSync(join(root, 'people', 'carol.md'), person('Carol', 'Carol is a person.'));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'initial');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [source, root]);+ const sync = (opts: Record<string, unknown> = {}) => performSync(engine, { repoPath: root, sourceId: source, noPull: true, noEmbed: true, noExtract: true, ...opts });+ await withEnv(env, async () => { await sync(); await run({ source, root, sync }); });+ }+ const page = async (source: string, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null; source_path: string | null; compiled_truth: string }>(+ 'SELECT id, deleted_at, source_path, compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [source, slug]))[0];+ const count = async (sql: string, params: unknown[]) => Number((await engine.executeRaw<{ n: number | string }>(sql, params))[0].n);++ /** Versions, timeline, a fact withdrawal and edges on a page: the identity a rename must carry (its declared alias comes from the file's frontmatter). */+ async function decorate(source: string, id: number, slug: string, peer: number) {+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash) VALUES($1, 'private', $2, 'deadbeef') ON CONFLICT DO NOTHING", [source, slug]);+ await engine.executeRaw("INSERT INTO page_versions(page_id, compiled_truth, frontmatter) VALUES($1, 'older text', '{}'::jsonb)", [id]);+ await engine.executeRaw("INSERT INTO timeline_entries(page_id, date, source, summary) VALUES($1, '2024-01-02', 'test', $2)", [id, `${slug} met someone`]);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source) VALUES($1, $2, 'knows', 'test') ON CONFLICT DO NOTHING", [id, peer]);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source) VALUES($2, $1, 'knows', 'test') ON CONFLICT DO NOTHING", [id, peer]);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source, origin_page_id) VALUES($2, $2, 'self', 'test', $1) ON CONFLICT DO NOTHING", [id, peer]);+ }+ const identity = async (id: number) => ({+ versions: await count('SELECT count(*) AS n FROM page_versions WHERE page_id=$1', [id]),+ timeline: await count('SELECT count(*) AS n FROM timeline_entries WHERE page_id=$1', [id]),+ outbound: await count('SELECT count(*) AS n FROM links WHERE from_page_id=$1', [id]),+ inbound: await count('SELECT count(*) AS n FROM links WHERE to_page_id=$1', [id]),+ origin: await count('SELECT count(*) AS n FROM links WHERE origin_page_id=$1', [id]),+ });++ test('tombstone destination: merged in one transaction, tombstone re-keyed with its history, identity and source_path move with the page', () => fixture(async f => {+ const alice = await page(f.source, 'people/alice'), carol = await page(f.source, 'people/carol');+ await decorate(f.source, alice.id, 'people/alice', carol.id);+ await engine.putPage('people/bob', { type: 'person', title: 'Bob (old)', compiled_truth: 'an earlier bob' }, { sourceId: f.source });+ const bob = await page(f.source, 'people/bob');+ await engine.executeRaw("INSERT INTO page_versions(page_id, compiled_truth, frontmatter) VALUES($1, 'bob v1', '{}'::jsonb)", [bob.id]);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source) VALUES($1, $2, 'knows', 'test')", [bob.id, carol.id]);+ await engine.softDeletePages(['people/bob'], { sourceId: f.source });+ const before = await identity(alice.id);++ renameSync(join(f.root, 'people', 'alice.md'), join(f.root, 'people', 'bob.md'));+ git(f.root, 'add', '-A'); git(f.root, 'commit', '-qm', 'rename alice to bob');+ const result = await f.sync();+ expect(result.status).toBe('synced');++ const moved = await page(f.source, 'people/bob');+ expect(moved.id).toBe(alice.id);+ expect(moved.deleted_at).toBeNull();+ expect(moved.source_path).toBe('people/bob.md');+ expect(moved.compiled_truth).toContain('Alice is a person');+ expect(await page(f.source, 'people/alice')).toBeUndefined();+ const { versions, ...after } = await identity(alice.id);+ const { versions: versionsBefore, ...rest } = before;+ expect(after).toEqual(rest);+ expect(versions >= versionsBefore).toBe(true);+ expect(await engine.executeRaw('SELECT slug FROM page_aliases WHERE source_id=$1 AND alias_norm=$2', [f.source, 'ali'])).toEqual([{ slug: 'people/bob' }]);+ expect(await engine.executeRaw('SELECT subject FROM fact_withdrawals WHERE source_id=$1', [f.source])).toEqual([{ subject: 'people/bob' }]);+ expect(await count("SELECT count(*) AS n FROM slug_aliases WHERE source_id=$1 AND alias_slug='people/alice' AND canonical_slug='people/bob'", [f.source])).toBe(1);++ const tombstone = await page(f.source, `people/bob~purged-${bob.id}`);+ expect(tombstone.id).toBe(bob.id);+ expect(tombstone.deleted_at).not.toBeNull();+ expect(await count('SELECT count(*) AS n FROM page_versions WHERE page_id=$1', [bob.id])).toBe(1);+ expect(await count('SELECT count(*) AS n FROM links WHERE from_page_id=$1', [bob.id])).toBe(1);+ expect(await count('SELECT count(*) AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [f.source])).toBe(2);++ // The full-sync purge must not read the renamed page as a removed file.+ const full = await f.sync({ full: true });+ expect(['synced', 'first_sync']).toContain(full.status);+ expect((await page(f.source, 'people/bob')).deleted_at).toBeNull();+ expect(await count('SELECT count(*) AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [f.source])).toBe(2);+ }), 120_000);++ test('live destination: the add fallback carries the stale row\'s identity onto the destination row before soft-deleting it', () => fixture(async f => {+ const alice = await page(f.source, 'people/alice'), carol = await page(f.source, 'people/carol');+ await decorate(f.source, alice.id, 'people/alice', carol.id);+ await engine.putPage('people/bob', { type: 'person', title: 'Bob (live)', compiled_truth: 'a live bob' }, { sourceId: f.source });+ const bob = await page(f.source, 'people/bob');+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source) VALUES($1, $2, 'knows', 'test')", [bob.id, carol.id]);+ const before = await identity(alice.id);++ renameSync(join(f.root, 'people', 'alice.md'), join(f.root, 'people', 'bob.md'));+ git(f.root, 'add', '-A'); git(f.root, 'commit', '-qm', 'rename alice onto a live bob');+ const result = await f.sync();+ expect(result.status).toBe('synced');++ const moved = await page(f.source, 'people/bob');+ expect(moved.id).toBe(bob.id);+ expect(moved.compiled_truth).toContain('Alice is a person');+ expect((await page(f.source, 'people/alice')).deleted_at).not.toBeNull();+ expect(await identity(alice.id)).toEqual({ versions: 0, timeline: 0, outbound: 0, inbound: 0, origin: 0 });+ const after = await identity(bob.id);+ expect(after.timeline).toBe(before.timeline);+ expect(after.outbound).toBe(before.outbound);+ expect(after.inbound).toBe(before.inbound);+ expect(after.origin).toBe(before.origin);+ expect(after.versions >= before.versions).toBe(true);+ expect(await engine.executeRaw('SELECT slug FROM page_aliases WHERE source_id=$1 AND alias_norm=$2', [f.source, 'ali'])).toEqual([{ slug: 'people/bob' }]);+ expect(await engine.executeRaw('SELECT subject FROM fact_withdrawals WHERE source_id=$1', [f.source])).toEqual([{ subject: 'people/bob' }]);+ expect(await engine.executeRaw('SELECT canonical_slug FROM slug_aliases WHERE source_id=$1 AND alias_slug=$2', [f.source, 'people/alice'])).toEqual([{ canonical_slug: 'people/bob' }]);+ }), 120_000);++ test('another SQLSTATE on the rename fails the file and leaves the checkpoint where it was', () => fixture(async f => {+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION gbrain_test_refuse_slug() RETURNS trigger AS $$+ BEGIN IF NEW.slug = 'people/boom' THEN RAISE EXCEPTION 'injected rename failure' USING ERRCODE = 'P0001'; END IF; RETURN NEW; END $$ LANGUAGE plpgsql`);+ await engine.executeRaw('CREATE TRIGGER gbrain_test_refuse_slug BEFORE UPDATE OF slug ON pages FOR EACH ROW EXECUTE FUNCTION gbrain_test_refuse_slug()');+ try {+ const anchor = (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.source]))[0].last_commit;+ renameSync(join(f.root, 'people', 'alice.md'), join(f.root, 'people', 'boom.md'));+ git(f.root, 'add', '-A'); git(f.root, 'commit', '-qm', 'rename alice to boom');+ const result = await f.sync();+ expect(result.status).toBe('blocked_by_failures');+ expect(result.failedFiles).toBe(1);+ expect((await page(f.source, 'people/alice')).deleted_at).toBeNull();+ expect(await page(f.source, 'people/boom')).toBeUndefined();+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.source]))[0].last_commit).toBe(anchor);+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS gbrain_test_refuse_slug ON pages');+ await engine.executeRaw('DROP FUNCTION IF EXISTS gbrain_test_refuse_slug()');+ }+ const result = await f.sync();+ expect(result.status).toBe('synced');+ expect((await page(f.source, 'people/boom')).compiled_truth).toContain('Alice is a person');+ }), 120_000);++ test('movePageIdReferences carries edges, timeline and versions to the surviving row and deduplicates on the links key', () => fixture(async f => {+ const alice = await page(f.source, 'people/alice'), carol = await page(f.source, 'people/carol');+ await engine.putPage('people/dup', { type: 'person', title: 'Dup', compiled_truth: 'the surviving row' }, { sourceId: f.source });+ const dup = await page(f.source, 'people/dup');+ await decorate(f.source, alice.id, 'people/alice', carol.id);+ await engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source) VALUES($1, $2, 'knows', 'test')", [dup.id, carol.id]);+ await engine.executeRaw("INSERT INTO timeline_entries(page_id, date, source, summary) VALUES($1, '2024-01-02', 'test', 'people/alice met someone')", [dup.id]);+ const total = await count('SELECT count(*) AS n FROM links', []);+ const from = await identity(alice.id), to = await identity(dup.id);++ await maintenanceTransaction(engine, tx => movePageIdReferences(tx, alice.id, dup.id));++ expect(await identity(alice.id)).toEqual({ versions: 0, timeline: 0, outbound: 0, inbound: 0, origin: 0 });+ const after = await identity(dup.id);+ expect(after.versions).toBe(from.versions + to.versions);+ expect(after.timeline).toBe(from.timeline + to.timeline - 1);+ expect(after.outbound).toBe(from.outbound + to.outbound - 1);+ expect(after.inbound).toBe(from.inbound + to.inbound);+ expect(after.origin).toBe(from.origin + to.origin);+ expect(await count('SELECT count(*) AS n FROM links', [])).toBe(total - 1);+ expect(await count('SELECT count(*) AS n FROM links WHERE from_page_id=$1 AND to_page_id=$2 AND link_type=$3', [dup.id, carol.id, 'knows'])).toBe(1);+ }), 120_000);+});