Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): bounded checkpoint sibling probe, timed-out checkpoint revive, legacy-slug adoption (#6735, #6727)

garrytan1b8b17f3e864
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 8d3d51185d..a93ac4c6cd 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -119,6 +119,7 @@ Every hold and error has three fields, from one table
| `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off |
| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
+| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a2b75a3522..cea63027fe 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -199,6 +199,7 @@ with each file and fix the ones that need no guessing."*
| <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 managed-sync hold re-screens on every sync, so either clears it on the next one. |
| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host; a managed-sync hold re-screens on every sync, so the next one imports it. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). |
| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source); an owner allow rule (`gbrain trust allow`) covering the source and the file's path admits it at freeze exactly as at preparation. The hold is `needs_human`, and every sync re-screens it, so the setting switched or an allow rule added clears it on the next sync. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |
+| <a id="legacy_slug_conflict"></a>`legacy_slug_conflict` | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it; with `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. |
| <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. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |
diff --git a/llms-full.txt b/llms-full.txt
index 94b039eb17..b092335d4a 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7361,6 +7361,7 @@ Every hold and error has three fields, from one table
| `managed_image_sync_unsupported` | page | none | no | never: images stay held while multimodal embedding is off |
| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
+| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.ts
index 4ec0835e47..4ece47575f 100644
--- a/src/core/persistence/checkpoint-validation.ts
+++ b/src/core/persistence/checkpoint-validation.ts
@@ -7,7 +7,10 @@
* a non-committed page receipt of the run with no committed sibling at the
* same index). Each probe is served by an index: `persistence_requests_recovery`,
* `persistence_requests_sync_run_open` and, for the sibling lookup,
- * `persistence_requests_sync_run_committed`. A statement timeout of this one
+ * `persistence_requests_sync_run_committed`. #6735: the sibling lookup is a
+ * `LATERAL ... LIMIT 1` probe keyed on (source, run, index), which the planner
+ * cannot flatten into an anti-join over a materialized scan of every committed
+ * receipt of the run, so its cost is linear in the run's non-committed receipts. A statement timeout of this one
* statement is a deterministic failure on a large request table, not
* contention, so it becomes the terminal typed code instead of being released
* as `database_contention` and retried ahead of every other write.
@@ -18,7 +21,7 @@
* `gbrain write-request` / MCP `get_write_request`.
*/
import type { BrainEngine } from '../engine.ts';
-import { opError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } from './schema.ts';
import { docsAnchor } from './connector-errors.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
@@ -35,20 +38,22 @@ const SYNC_PAGE_KINDS = "r.intent->>'kind' IN ('managed_sync_import','managed_sy
* #6712 retired the knock-on exemption ($6): no page is cancelled for another page's failure any more, and the cursor
* converts a legacy knock-on it meets in place (sync-run.ts `refreezeInPlace`).
*/
-export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS request_id FROM persistence_requests r
- WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)
+const incompleteSyncReceiptSql = (limit: number) => `(SELECT r.request_id::text AS request_id FROM persistence_requests r
+ WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT ${limit})
UNION ALL (SELECT r.request_id::text FROM persistence_requests r
WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}
- AND r.state IN ('queued','running','recovering') LIMIT 1)
+ AND r.state IN ('queued','running','recovering') LIMIT ${limit})
UNION ALL (SELECT r.request_id::text FROM persistence_requests r
- WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}
- AND NOT EXISTS (SELECT 1 FROM persistence_requests committed WHERE committed.source_id=r.source_id
+ LEFT JOIN LATERAL (SELECT true AS found FROM persistence_requests committed WHERE committed.source_id=r.source_id
AND committed.intent->>'runId'=$2 AND committed.intent->>'index'=r.intent->>'index'
- AND committed.state='committed' AND committed.intent ? 'runId')
+ AND committed.state='committed' AND committed.intent ? 'runId' LIMIT 1) sibling ON true
+ WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}
+ AND sibling.found IS NULL
AND NOT (r.request_id::text=ANY($3::text[]))
AND NOT (r.state IN ('failed','cancelled','conflict') AND r.recovery IS NULL
- AND EXISTS (SELECT 1 FROM unnest($4::int[], $5::int[]) AS settled(lo, hi) WHERE (r.intent->>'index')::int BETWEEN settled.lo AND settled.hi)) LIMIT 1)
- LIMIT 1`;
+ AND EXISTS (SELECT 1 FROM unnest($4::int[], $5::int[]) AS settled(lo, hi) WHERE (r.intent->>'index')::int BETWEEN settled.lo AND settled.hi)) LIMIT ${limit})
+ LIMIT ${limit}`;
+export const INCOMPLETE_SYNC_RECEIPT_SQL = incompleteSyncReceiptSql(1);
/** #6643: the index ranges a cursor passed without a commit, and the index it began recording them at. */
export interface SyncSettledIndexes { from: number; ranges: Array<[number, number]> }
@@ -76,6 +81,17 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa
}
}
+/**
+ * #6735: `findIncompleteSyncReceipt` as a resume asks it, outside the coordinator: a timeout reads as no known blocker,
+ * so the revived checkpoint is validated again inside its own publication instead of the manifest being rediscovered.
+ */
+export async function probeCheckpointBlocker(...args: Parameters<typeof findIncompleteSyncReceipt>): Promise<string | null> {
+ return findIncompleteSyncReceipt(...args).catch(error => {
+ if (error instanceof OperationError && error.code === CHECKPOINT_VALIDATION_TIMEOUT) return null;
+ throw error;
+ });
+}
+
/**
* #6643: every receipt (up to 20) that would block the run's checkpoint now, with what `sync status` needs to tell a
* knock-on from a root; read-only. The checkpoint itself names only the first (`findIncompleteSyncReceipt`).
@@ -84,7 +100,7 @@ export async function listIncompleteSyncReceipts(engine: Pick<BrainEngine, 'exec
settled: SyncSettledIndexes | null = null): Promise<Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean }>> {
const ranges = settled?.ranges ?? [];
return engine.executeRaw(`SELECT r.request_id::text AS request_id, r.slug, r.state, r.error_code AS code, (r.intent->>'index')::int AS index, r.recovery IS NOT NULL AS recovery
- FROM persistence_requests r WHERE r.request_id::text IN (SELECT request_id FROM (${INCOMPLETE_SYNC_RECEIPT_SQL.replaceAll('LIMIT 1', 'LIMIT 20')}) blockers) ORDER BY r.sequence LIMIT 20`,
+ FROM persistence_requests r WHERE r.request_id::text IN (SELECT request_id FROM (${incompleteSyncReceiptSql(20)}) blockers) ORDER BY r.sequence LIMIT 20`,
[worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1])]);
}
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 5771947d86..2a187e817d 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -33,7 +33,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor
/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */
export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
worktree_dirty: 'drift', file_drift: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',
- concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict',
+ concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict',
invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',
file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',
purged_content: 'content_refused', write_gate_rejected: 'content_refused',
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 637b0e20ff..b664b58cf5 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -9,7 +9,9 @@ import { managedForbiddenFlag, managedSyncFlagRefusal } from './managed-sync-fla
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
-import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
+import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath, slugifyPath } from '../sync.ts';
+import { databaseOnlyPageSql } from './unbound-pages.ts';
+import { validateSlug } from '../utils.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -40,7 +42,9 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'
/** #6712 PR 1: the import provenance matches the pinned blob, the frozen revision and this parser; the no-op kernel decides (sync-prescreen.ts). */
prescreened?: true;
/** #6712 PR 1: the page moved since its last recorded import (or has no record); imported only when the freeze proves it a no-op, else held `file_drift`. */
- drift?: SyncDriftSide; }
+ drift?: SyncDriftSide;
+ /** #6727: live pages with no recorded origin whose slugs fold to this file's slug, several or one the importer cannot write; the freeze holds it `legacy_slug_conflict`. */
+ legacySlugs?: string[]; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
@@ -477,6 +481,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
if (!slug) throw opError('invalid_params', 'The imported file has no usable page slug.',
`${entry.sourcePath} in ${sourceId} yields no page slug from its path or frontmatter; nothing was written. Rename the file or set a frontmatter slug and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
if (!company && entry.action === 'import' && !origin && !isCodeFilePath(entry.sourcePath)) {
+ slug = await adoptLegacyPage(engine, identities, bySlug.get(slug), slug, entry);
entry.slug = slug;
claims.set(slug, [...(claims.get(slug) ?? []), entry]);
continue;
@@ -561,6 +566,36 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
}
return discovered;
}
+type LegacyIdentity = { id: number; slug: string; source_path: string | null; deleted_at: Date | string | null };
+/**
+ * #6727: per discovery, its live pages with no recorded origin whose slug the current fold changes, by folded slug. Built on
+ * first need; database-only pages (never imported from a file) are left out by one read over just those candidates, so a
+ * source without legacy pages issues no extra statement.
+ */
+const legacyByFold = new WeakMap<LegacyIdentity[], Promise<Map<string, string[]>>>();
+async function foldLegacyPages(engine: BrainEngine, identities: LegacyIdentity[]): Promise<Map<string, string[]>> {
+ const candidates = identities.filter(page => page.deleted_at == null && page.source_path == null && slugifyPath(page.slug) !== page.slug);
+ const databaseOnly = new Set(candidates.length ? (await engine.executeRaw<{ id: number }>(
+ `SELECT p.id FROM pages p WHERE p.id=ANY($1::bigint[]) AND ${databaseOnlyPageSql('p')}`, [candidates.map(page => Number(page.id))])).map(row => Number(row.id)) : []);
+ return candidates.filter(page => !databaseOnly.has(Number(page.id)))
+ .reduce((map, page) => map.set(slugifyPath(page.slug), [...map.get(slugifyPath(page.slug)) ?? [], page.slug]), new Map<string, string[]>());
+}
+/**
+ * #6727: the slug a file with no recorded origin imports as. With no live page at its folded slug, exactly one legacy page
+ * (an older gbrain imported it before the current fold) folding to it is the file's: it imports into that page (same id,
+ * links and history). Several, or one whose slug the importer cannot write as it stands (`validateSlug` lowercases), keep
+ * the folded slug and are named on the entry, so the freeze holds the file `legacy_slug_conflict`.
+ */
+async function adoptLegacyPage(engine: BrainEngine, identities: LegacyIdentity[], holder: LegacyIdentity | undefined, slug: string, entry: SyncEntry): Promise<string> {
+ if (holder && holder.deleted_at == null) return slug;
+ let folded = legacyByFold.get(identities);
+ if (!folded) legacyByFold.set(identities, folded = foldLegacyPages(engine, identities));
+ const legacy = (await folded).get(slug) ?? [];
+ const writable = () => { try { return validateSlug(legacy[0]!) === legacy[0]; } catch { return false; } };
+ if (legacy.length === 1 && writable()) return legacy[0]!;
+ if (legacy.length) entry.legacySlugs = [...legacy].sort();
+ return slug;
+}
/** #6517: several live pages (the soft-delete exit is named) or several tombstones record one imported origin. */
function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {
return opError('page_identity_changed', 'Several pages claim the same imported origin.',
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 167b5ea7ac..7e7a491d92 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -71,6 +71,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
human_reason: 'The file carries content the owner purged; delete or edit the file and commit, or (only if the purge was a mistake) the owner clears it with gbrain pages unpurge <slug> --source <source> on the brain host.' },
{ code: 'write_gate_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: write_gate.external_mode=reject is the user\'s setting',
human_reason: 'The write gate refuses the file\'s external instruction-like content under write_gate.external_mode=reject; the user decides whether to edit the file or switch the setting back to quarantine.' },
+ // #6727: pages an older gbrain imported without recording their file fold to the file's slug, several or one sync cannot write; a person decides.
+ { code: 'legacy_slug_conflict', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a person decides which legacy page the file takes over',
+ human_reason: 'Pages an older gbrain imported without recording their file match this file and sync cannot pick one to import into; a person keeps the one that is its page and removes the others (gbrain delete --source <source> -- <slug>), or renames the file, then syncs.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index adc0bff573..8793d8053e 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -68,7 +68,8 @@ 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' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift';
+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
+ | 'legacy_slug_conflict';
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
export interface PreparationStallMeta {
request_id: string;
@@ -132,6 +133,8 @@ export interface GitHoldMeta {
* held in that sync; this entry waits on it with the same code, and discovery re-screens it once that hold is gone.
*/
blocked_on?: string;
+ /** #6727 `legacy_slug_conflict`: the live pages without a recorded origin whose slugs fold to the file's slug. */
+ legacy_slugs?: string[];
}
/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */
@@ -486,10 +489,10 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so
* re-screens whenever multimodal embedding is on, since managed sync then
* imports the image instead of holding it. #6712 PR 2: a `content_rejected`, `write_gate_rejected` or
* `purged_content` hold rests on a setting, an allow rule or a tombstone its fix lets the user change, so it
- * re-screens on every sync too.
+ * re-screens on every sync too. #6727: so does a `legacy_slug_conflict` hold, which rests on the legacy pages a person removes.
*/
export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {
- return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content'].includes(record.code)
+ return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict'].includes(record.code)
// #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.
|| (record.code === 'preparation_stalled' && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)
|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())
@@ -663,6 +666,20 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,
why: 'The same bytes imported before, so only gbrain changed; sync holds the file under GBRAIN_SYNC_PARSER_REGRESSION=hold.' };
+ case 'legacy_slug_conflict': {
+ const slugs = record.meta.legacy_slugs ?? [];
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#legacy_slug_conflict',
+ user_message: slugs.length > 1
+ ? `${record.path} belongs to one of the pages ${slugs.map(slug => JSON.stringify(slug)).join(', ')}, which an older gbrain imported without recording their file, so sync held it rather than guess or create another page. `
+ + `Pick the page that is this file's and remove each other one with gbrain delete --source ${source} -- '<slug>' (recoverable for 72 h), or rename the file if none of them is its page, then run gbrain sync --source ${source} --no-pull.`
+ : `${record.path} matches page ${JSON.stringify(slugs[0] ?? '')}, which an older gbrain imported without recording its file under a slug with capitals that sync cannot write and no gbrain command can address yet, so sync held the file rather than create a second page. `
+ + `Keep the file held (the rest of the source syncs), or rename it to a name that folds to another slug, which imports it as a new page beside the old one (the old page keeps its links), then run gbrain sync --source ${source} --no-pull.`,
+ why: 'Which page a file is cannot be decided from the slugs alone, and sync never writes a slug it would have to change. Once one writable page is left, the next sync imports the file into it (same page id, links and history) and records the file as its origin; until then the rest of the source keeps syncing.',
+ then: { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${record.path} after the other pages are removed (this hold is re-screened on every sync).` },
+ verify };
+ }
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 680c7b2dad..1264348843 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -32,7 +32,7 @@ import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-st
import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure, type ManagedSyncRootCause } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
import { stampDrainStep } from './drain-step.ts';
-import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
+import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, probeCheckpointBlocker, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import { principalKey, type WriteRequest } from './model.ts';
import { readJournalLimits } from './limits.ts';
@@ -349,6 +349,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
// #6340: page faults (the database page moved under the manifest) hold the entry, imports and deletes alike, when holds
// are on; `sync.holds=fail` and company-brain cursors keep the refusals.
const holdsOn = !!run.screen && !cursor.companyPlan;
+ if (entry.legacySlugs?.length && !holdsOn) throw syncRunRefusal('page_identity_changed', 'Legacy pages sync cannot import into match the imported file.', retry, `${entry.path} imports as page ${entry.slug}, but pages ${entry.legacySlugs.join(', ')} of source ${cursor.sourceId}, imported from a file of that name, record no file (sync.holds=fail); keep the file's page, remove the others, then sync again.`);
const [occupant, snapshot] = await Promise.all([alreadyImportedAtOrigin(engine, cursor, entry, originScope).catch(error => {
if (!holdsOn || !(error instanceof OperationError) || error.code !== 'page_identity_changed') throw error;
return { originFault: error };
@@ -795,23 +796,28 @@ async function refreezeInPlace(engine: BrainEngine, input: SettleInput): Promise
/** #6643: checkpoint revivals per sync invocation (keyed by its run options object), so a refusal loop ends the invocation, never the cursor. */
const checkpointRevivalsByRun = new WeakMap<object, number>();
/** A same-run index lag ("The sync cursor is not fully committed.") stays a recorded failure (managed-sync-checkpoint-replaced.test.ts pins it). */
-const revivableCheckpointRefusal = (done: Pick<WriteRequest, 'state' | 'error_code' | 'recovery'>) => !done.recovery && done.state === 'failed' && done.error_code === 'recovery_required';
+const revivableCheckpointRefusal = (done: Pick<WriteRequest, 'state' | 'error_code' | 'recovery'>) => !done.recovery && done.state === 'failed'
+ && (done.error_code === 'recovery_required' || done.error_code === CHECKPOINT_VALIDATION_TIMEOUT);
/**
* #6643: a checkpoint refused because a receipt blocked it (`recovery_required`) is re-assessed whenever the run resumes: when nothing blocks it any more (a
* knock-on, a receipt at an index the cursor settled), a fresh checkpoint request replaces it by cursor swap, and its
* publication validates everything again. The completed manifest and the old receipt stay as they are. Null when it
* still blocks, or after `CHECKPOINT_REVIVAL_LIMIT` revivals in this invocation (the next invocation re-assesses).
* #6694/#6834: a slug-mode refusal the source now admits, or a moved checkpoint at this run's target, revives too (sync-slug-mode.ts).
+ * #6735: so does a validation timeout, once per invocation and only once an earlier invocation recorded the stop, so a resume
+ * re-validates the pinned checkpoint instead of rediscovering the manifest.
*/
async function reviveCheckpoint(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {
const { cursor, key, pending, done } = input;
const refused = revivableCheckpointRefusal(done) || (pending.intent.kind === 'managed_sync_checkpoint' && await checkpointRevival(engine, cursor, pending.intent, done));
const revivals = checkpointRevivalsByRun.get(input.run) ?? 0;
- if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;
+ const timedOut = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT;
+ if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= (timedOut ? 1 : CHECKPOINT_REVIVAL_LIMIT)
+ || (timedOut && !await stopRecorded(engine, key, cursor.runId))) return null;
const base: Cursor = { ...withoutPending(cursor), ...(refused === 'overtaken' ? { overtaken: true as const } : {}) };
const fresh = await freezeEntry(engine, base, key, input.assertActive, input.run);
if (!('requestId' in fresh)) return null;
- const blocker = await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null);
+ const blocker = await probeCheckpointBlocker(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null);
input.assertActive();
if (blocker) return null;
checkpointRevivalsByRun.set(input.run, revivals + 1);
@@ -1348,7 +1354,7 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string
// receipt still blocks (since #6712 a legacy knock-on the cursor never settled is one) rediscovers, as --retry-failed says.
if (failed && cursor.pending && isSyncKnockOn(failed)) return null;
if (failed && cursor.pending?.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)
- && !await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, cursor.convertedFromFailed ?? [], cursor.settled ?? null)) return null;
+ && !await probeCheckpointBlocker(engine, cursor.binding.worktree_id, cursor.runId, cursor.convertedFromFailed ?? [], cursor.settled ?? null)) return null;
const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);
assertActive();
if (!((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed)))) return null;
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 9f9a5009de..13a7c3f237 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -249,6 +249,12 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor
if (entry.renameHeld) {
return heldEntry(entry, slug, pageId, { code: 'rename_held', reason: 'rename_source_changed', message: `${entry.path} is a rename of page ${entry.renameHeld.slug}, which changed after the rename was recorded, so the page was not moved.` }, content, blob);
}
+ if (entry.legacySlugs?.length) {
+ const [only, several] = [entry.legacySlugs[0], entry.legacySlugs.length > 1];
+ const held = heldEntry(entry, slug, pageId, { code: 'legacy_slug_conflict', message: `${entry.path} imports as page ${slug}, but ${several ? `pages ${entry.legacySlugs.join(', ')}` : `page ${only}`}, which an older gbrain imported from a file of that name, `
+ + `record${several ? '' : 's'} no file${several ? ' and sync cannot tell which is its page' : ' and has a slug sync cannot write as it stands'}, so sync held the file instead of creating another page.` }, content, blob);
+ return { ...held, meta: { ...held.meta, legacy_slugs: entry.legacySlugs } };
+ }
// #6188: a fence Tier 1 rewrites is admitted (publication writes the normalized file back); with fences.normalize=false it is held.
const screen = await screenFrozenContent(await frozenImportScreenInput(engine, { ...input, content }, run), run);
if (screen.status === 'importable' && screen.fences?.fixes.length) input.onNormalized?.(screen.fences.fixes);
diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.ts
index 69e4fe530f..c4f1ebbcf5 100644
--- a/test/persistence-sync-checkpoint-validation.test.ts
+++ b/test/persistence-sync-checkpoint-validation.test.ts
@@ -111,8 +111,8 @@ function failValidation(engine: BrainEngine, failure: 'timeout' | 'lock'): () =>
return () => { engine.transaction = transaction; };
}
-test('#5762 a validation statement timeout fails the checkpoint terminally with a typed code and a filled hint; other writes proceed', async () => each(async engine => {
- const f = await fixture(engine);
+/** Runs the fixture's sync until its checkpoint validation times out terminally. */
+async function timedOutSync(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>) {
const restore = failValidation(engine, 'timeout');
let result: Awaited<ReturnType<typeof performManagedSync>>;
try {
@@ -120,10 +120,19 @@ test('#5762 a validation statement timeout fails the checkpoint terminally with
// A real 5 s statement timeout outlasts the sync's own 5 s wait; the same options then report the terminal outcome.
for (let waited = 0; result.status === 'partial' && waited < 30_000; waited += 250) {
await new Promise(resolve => setTimeout(resolve, 250));
- const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint'", [f.id]);
+ const [row] = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence DESC LIMIT 1", [f.id]);
if (row?.state === 'failed') result = await performManagedSync(engine, f.opts);
}
} finally { restore(); }
+ return result;
+}
+
+const checkpointRuns = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ state: string; error_code: string | null; run_id: string }>(
+ "SELECT state, error_code, intent->>'runId' AS run_id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence", [sourceId]);
+
+test('#5762 a validation statement timeout fails the checkpoint terminally with a typed code and a filled hint; other writes proceed', async () => each(async engine => {
+ const f = await fixture(engine);
+ const result = await timedOutSync(engine, f);
expect(result).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'checkpoint_validation_timeout', count: 1 }] });
const diagnostic = result.managedWrite!;
expect(diagnostic).toMatchObject({ write_error: 'checkpoint_validation_timeout', reason: 'checkpoint_validation_timeout', detail: 'indexes_valid',
@@ -149,6 +158,57 @@ test('#5762 a validation statement timeout fails the checkpoint terminally with
// The printed retry admits a fresh run that commits.
expect((await performManagedSync(engine, { ...f.opts, retryFailed: true })).status).toBe('first_sync');
+ // #6735: it re-validated the pinned checkpoint of the timed-out run; it did not rediscover the manifest under a new run.
+ const runs = await checkpointRuns(engine, f.id);
+ expect(runs.at(-1)).toMatchObject({ state: 'committed', run_id: runs[0]!.run_id });
+}), 180_000);
+
+test('#6735 a plain resume re-validates a checkpoint whose validation timed out, once per invocation', async () => each(async engine => {
+ const f = await fixture(engine);
+ expect(await timedOutSync(engine, f)).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'checkpoint_validation_timeout', count: 1 }] });
+ const [failed] = await checkpointRuns(engine, f.id);
+ // A timeout that persists is revived once by the next invocation, then recorded again: the run is never rediscovered.
+ expect(await timedOutSync(engine, f)).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'checkpoint_validation_timeout', count: 1 }] });
+ expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.error_code, row.run_id]))
+ .toEqual([['failed', 'checkpoint_validation_timeout', failed!.run_id], ['failed', 'checkpoint_validation_timeout', failed!.run_id]]);
+ // Once validation fits its budget, the plain sync the run stopped on commits that same checkpoint.
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.run_id]))
+ .toEqual([['failed', failed!.run_id], ['failed', failed!.run_id], ['committed', failed!.run_id]]);
+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [f.id])).toEqual([{ slug: 'a' }, { slug: 'b' }]);
+}), 180_000);
+
+/** Every plan node under `node`, depth first. */
+const planNodes = (node: Record<string, unknown>): Array<Record<string, unknown>> =>
+ [node, ...((node.Plans as Array<Record<string, unknown>> | undefined) ?? []).flatMap(planNodes)];
+
+test('#6735 the committed-sibling lookup reads at most one row per non-committed receipt, whatever join the planner prefers', async () => each(async engine => {
+ const f = await fixture(engine);
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [f.id]);
+ const runId = randomUUID(), committed = 3000, retried = 20;
+ const insert = (state: string, indexes: string) => engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,
+ source_incarnation,slug,worktree_id,digest,intent,authority,intent_bytes,terminal_reservation,state)
+ SELECT 'local_cli','budget',gen_random_uuid(),'submit_job',$1,$2::uuid,'p'||i,$3::uuid,'d',jsonb_build_object('kind','managed_sync_import','runId',$4::text,'index',i),
+ '{}'::jsonb,1,16384,$5 FROM ${indexes} AS i`, [f.id, source!.incarnation, binding.worktree_id, runId, state]);
+ // Every failed receipt was retried and committed at its index, so nothing blocks; the probe still reads each one's sibling.
+ await insert('committed', `generate_series(0, ${committed - 1})`);
+ await insert('failed', `generate_series(0, ${(retried - 1) * 97}, 97)`);
+ await engine.executeRaw('ANALYZE persistence_requests');
+ for (const settings of [[], ['enable_nestloop'], ['enable_nestloop', 'enable_mergejoin']]) {
+ const read = await engine.transaction(async tx => {
+ for (const setting of settings) await tx.executeRaw(`SET LOCAL ${setting}=off`);
+ expect(await findIncompleteSyncReceipt(tx, binding.worktree_id, runId)).toBeNull();
+ const [row] = await tx.executeRaw<Record<string, unknown>>(`EXPLAIN (ANALYZE, FORMAT JSON) ${INCOMPLETE_SYNC_RECEIPT_SQL}`, [binding.worktree_id, runId, [], [], []]);
+ const raw = Object.values(row!)[0];
+ const plan = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Array<{ Plan: Record<string, unknown> }>;
+ return planNodes(plan[0]!.Plan).filter(node => node['Alias'] === 'committed')
+ .reduce((sum, node) => sum + Number(node['Actual Rows']) * Number(node['Actual Loops']), 0);
+ });
+ // Rows read from the committed siblings: the pre-#6735 NOT EXISTS read all 3000 under a merge or hash anti-join.
+ expect({ settings, read }).toEqual({ settings, read: retried });
+ }
+ await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=$1', [f.id]);
}), 180_000);
test('#5762 a lock timeout in the validation stays transient contention', async () => each(async engine => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index d58b06db4a..96041b9099 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -201,6 +201,7 @@ test/sync-handler-drain-6706.test.ts
test/sync-import-provenance-disk.test.ts
test/sync-legacy-holds.test.ts
test/sync-legacy-retry-actions-6696.test.ts
+test/sync-legacy-slug-adoption-6727.test.ts
test/sync-origin-live-wins-6517.test.ts
test/sync-prescreen-drift-6712.test.ts
test/sync-slug-root-mode-6694.test.ts
diff --git a/test/sync-legacy-slug-adoption-6727.test.ts b/test/sync-legacy-slug-adoption-6727.test.ts
new file mode 100644
index 0000000000..05b807d018
--- /dev/null
+++ b/test/sync-legacy-slug-adoption-6727.test.ts
@@ -0,0 +1,162 @@
+/**
+ * #6727: an older gbrain imported a file under its raw path as the slug and recorded no origin (`source_path` NULL). The
+ * current fold gives the same file another slug; with no page there, managed sync used to insert a second live page for
+ * the same file. Now the one legacy page that folds to the file's slug is taken over (same id, slug and links) and records
+ * the file; several such pages, or one whose slug the importer would lowercase, hold the file `legacy_slug_conflict`.
+ * PGLite always; Postgres too when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { slugifyPath } from '../src/core/sync.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-6727-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => {
+ for (const engine of engines) { try { await fn(engine); } finally { await disposePersistenceConsumer(engine); await engine.unsetConfig('sync.holds'); } }
+});
+
+/**
+ * A managed source whose files an older gbrain imported under raw-path slugs: the files are imported, then each page's
+ * slug is set back to its file's path without the extension, lowercased as the importer always wrote it (`rawCase` keeps
+ * the path's case, a slug no importer writes), its origin and import record are dropped, and the source's checkpoint is
+ * cleared so the next sync walks the whole tree, as a catch-up after an upgrade does. `extra` adds legacy rows no file
+ * backs (a copy of the first file's page under another legacy slug).
+ */
+async function legacySource(engine: BrainEngine, files: Record<string, string>, extra: string[] = [], rawCase = false) {
+ const id = `legacy-${randomUUID().slice(0, 8)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ expect((await sync()).status).toBe('first_sync');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw(`UPDATE pages SET slug=${rawCase ? '' : 'lower'}(regexp_replace(source_path, '\\.md$', '')), source_path=NULL WHERE source_id=$1 AND source_path NOT LIKE 'plain/%'`, [id]);
+ for (const slug of extra) {
+ await engine.executeRaw(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash)
+ SELECT source_id, $2, type, title, compiled_truth, timeline, frontmatter, content_hash FROM pages WHERE source_id=$1 AND source_path IS NULL ORDER BY id LIMIT 1`, [id, slug]);
+ }
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [SYNC_IMPORT_PROVENANCE_OP]);
+ await engine.executeRaw('UPDATE sources SET last_commit=NULL WHERE id=$1', [id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const pages = async () => (await engine.executeRaw<{ id: number; slug: string; source_path: string | null }>(
+ 'SELECT id, slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [id])).sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
+ const ids = new Map((await pages()).map(page => [page.slug, Number(page.id)]));
+ return { id, root, ids, pages, sync,
+ held: async () => ((await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? []).map(hold => ({ path: hold.path, code: hold.code, slug: hold.slug, slugs: hold.meta.legacy_slugs })) };
+}
+
+// Each legacy slug is the file's path without its extension, lowercased; the current fold gives each a different slug.
+const SHAPES: Record<string, string> = {
+ 'notes/Foo Bar.md': 'notes/foo bar',
+ 'notes/cards/🤖 foo - bar.md': 'notes/cards/🤖 foo - bar',
+ 'notes/cards/life/café-notes.md': 'notes/cards/life/café-notes',
+ 'summaries/group-.md': 'summaries/group-',
+ 'courses/x/example 2 question.md': 'courses/x/example 2 question',
+ 'notes/pdf/《Some Title》course-draft(1-1).md': 'notes/pdf/《some title》course-draft(1-1)',
+};
+
+test('#6727 a file whose legacy page predates the slug fold is imported into that page, never beside it', () => each(async engine => {
+ for (const [path, slug] of Object.entries(SHAPES)) expect({ path, folds: slugifyPath(slug) !== slug }).toEqual({ path, folds: true });
+ const s = await legacySource(engine, { ...Object.fromEntries(Object.keys(SHAPES).map(path => [path, note(path)])), 'plain/plain.md': note('plain') });
+ const before = await s.pages();
+ expect(before.map(page => page.slug)).toEqual([...Object.values(SHAPES), 'plain/plain'].sort());
+ expect(['first_sync', 'synced']).toContain((await s.sync()).status);
+ expect(await s.held()).toEqual([]);
+ // One page per file: each legacy page kept its id and slug and now records its file.
+ const pages = await s.pages();
+ expect(pages.map(page => [page.slug, page.source_path, Number(page.id)])).toEqual(before.map(page => [page.slug,
+ Object.entries(SHAPES).find(([, slug]) => slug === page.slug)?.[0] ?? 'plain/plain.md', s.ids.get(page.slug)!]));
+ // The origin is recorded now, so the next sync changes nothing and still forks nothing.
+ expect((await s.sync()).status).toBe('up_to_date');
+ expect((await s.pages()).length).toBe(pages.length);
+}), 180_000);
+
+test('#6727 a legacy page whose file moved on is held file_drift on that page; no second page is created', () => each(async engine => {
+ const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar') });
+ writeFileSync(join(s.root, 'notes/Foo Bar.md'), note('Foo Bar, edited'));
+ git(s.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'edit');
+ await s.sync();
+ expect(await s.held()).toEqual([{ path: 'notes/Foo Bar.md', code: 'file_drift', slug: 'notes/foo bar', slugs: undefined }]);
+ expect((await s.pages()).map(page => [page.slug, Number(page.id)])).toEqual([['notes/foo bar', s.ids.get('notes/foo bar')!]]);
+}), 180_000);
+
+test('#6727 several legacy pages that fold to one file hold it until a person keeps one', () => each(async engine => {
+ const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar'), 'notes/other.md': note('other') }, ['notes/foo bar']);
+ await s.sync();
+ expect(await s.held()).toEqual([{ path: 'notes/Foo Bar.md', code: 'legacy_slug_conflict', slug: 'notes/foo-bar', slugs: ['notes/foo bar', 'notes/foo bar'] }]);
+ expect((await s.pages()).map(page => page.slug)).toEqual(['notes/foo bar', 'notes/foo bar', 'notes/other']);
+ // The person keeps notes/foo bar: the other legacy row is soft-deleted (#6212 admits its legacy slug), and the next sync takes the kept page over.
+ const ctx = { engine, config: { engine: engine.kind }, sourceId: s.id, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const doomed = await engine.readPageSnapshot('notes/foo bar', { sourceId: s.id });
+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: 'notes/foo bar', request_id: randomUUID(), expected_revision: doomed!.revision } });
+ await s.sync();
+ expect(await s.held()).toEqual([]);
+ expect((await s.pages()).map(page => [page.slug, page.source_path, Number(page.id)]))
+ .toEqual([['notes/foo bar', 'notes/Foo Bar.md', s.ids.get('notes/foo bar')!], ['notes/other', 'notes/other.md', s.ids.get('notes/other')!]]);
+}), 180_000);
+
+test('#6727 one legacy page under a slug the importer cannot write (capitals) holds the file rather than forking it', () => each(async engine => {
+ const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar') }, [], true);
+ await s.sync();
+ expect(await s.held()).toEqual([{ path: 'notes/Foo Bar.md', code: 'legacy_slug_conflict', slug: 'notes/foo-bar', slugs: ['notes/Foo Bar'] }]);
+ expect((await s.pages()).map(page => [page.slug, page.source_path, Number(page.id)])).toEqual([['notes/Foo Bar', null, s.ids.get('notes/Foo Bar')!]]);
+ // No command addresses a slug with capitals (writes lowercase it), so the named exit is the file's: renamed to a name
+ // that folds elsewhere, it imports as a new page beside the legacy one and its hold clears.
+ git(s.root, 'mv', 'notes/Foo Bar.md', 'notes/foo-bar-imported.md');
+ git(s.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'rename');
+ await s.sync();
+ expect(await s.held()).toEqual([]);
+ expect((await s.pages()).map(page => [page.slug, page.source_path])).toEqual([['notes/Foo Bar', null], ['notes/foo-bar-imported', 'notes/foo-bar-imported.md']]);
+}), 180_000);
+
+test('#6727 a database-only page (never imported from a file) is not taken over by a file whose slug it folds to', () => each(async engine => {
+ const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar') });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1", [s.id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await s.sync();
+ expect(await s.held()).toEqual([]);
+ expect((await s.pages()).map(page => [page.slug, page.source_path])).toEqual([['notes/foo bar', null], ['notes/foo-bar', 'notes/Foo Bar.md']]);
+}), 180_000);
+
+test('#6727 with sync.holds=fail the ambiguous file stops the run instead of creating a page', () => each(async engine => {
+ const s = await legacySource(engine, { 'notes/Foo Bar.md': note('Foo Bar') }, ['notes/foo bar']);
+ await engine.setConfig('sync.holds', 'fail');
+ const error = await s.sync().then(() => null, (caught: { code?: string; message?: string }) => caught);
+ expect(error?.code).toBe('page_identity_changed');
+ expect(error?.message).toContain('Legacy pages sync cannot import into match the imported file.');
+ expect((await s.pages()).map(page => page.slug)).toEqual(['notes/foo bar', 'notes/foo bar']);
+}), 180_000);